shell.c 177 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811
  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. ** If requested, include the SQLite compiler options file for MSVC.
  21. */
  22. #if defined(INCLUDE_MSVC_H)
  23. #include "msvc.h"
  24. #endif
  25. /*
  26. ** No support for loadable extensions in VxWorks.
  27. */
  28. #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
  29. # define SQLITE_OMIT_LOAD_EXTENSION 1
  30. #endif
  31. /*
  32. ** Enable large-file support for fopen() and friends on unix.
  33. */
  34. #ifndef SQLITE_DISABLE_LFS
  35. # define _LARGE_FILE 1
  36. # ifndef _FILE_OFFSET_BITS
  37. # define _FILE_OFFSET_BITS 64
  38. # endif
  39. # define _LARGEFILE_SOURCE 1
  40. #endif
  41. #include <stdlib.h>
  42. #include <string.h>
  43. #include <stdio.h>
  44. #include <assert.h>
  45. #include "sqlite3.h"
  46. #if SQLITE_USER_AUTHENTICATION
  47. # include "sqlite3userauth.h"
  48. #endif
  49. #include <ctype.h>
  50. #include <stdarg.h>
  51. #if !defined(_WIN32) && !defined(WIN32)
  52. # include <signal.h>
  53. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  54. # include <pwd.h>
  55. # endif
  56. # include <unistd.h>
  57. # include <sys/types.h>
  58. #endif
  59. #if HAVE_READLINE
  60. # include <readline/readline.h>
  61. # include <readline/history.h>
  62. #endif
  63. #if HAVE_EDITLINE
  64. # include <editline/readline.h>
  65. #endif
  66. #if HAVE_EDITLINE || HAVE_READLINE
  67. # define shell_add_history(X) add_history(X)
  68. # define shell_read_history(X) read_history(X)
  69. # define shell_write_history(X) write_history(X)
  70. # define shell_stifle_history(X) stifle_history(X)
  71. # define shell_readline(X) readline(X)
  72. #elif HAVE_LINENOISE
  73. # include "linenoise.h"
  74. # define shell_add_history(X) linenoiseHistoryAdd(X)
  75. # define shell_read_history(X) linenoiseHistoryLoad(X)
  76. # define shell_write_history(X) linenoiseHistorySave(X)
  77. # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
  78. # define shell_readline(X) linenoise(X)
  79. #else
  80. # define shell_read_history(X)
  81. # define shell_write_history(X)
  82. # define shell_stifle_history(X)
  83. # define SHELL_USE_LOCAL_GETLINE 1
  84. #endif
  85. #if defined(_WIN32) || defined(WIN32)
  86. # include <io.h>
  87. # include <fcntl.h>
  88. # define isatty(h) _isatty(h)
  89. # ifndef access
  90. # define access(f,m) _access((f),(m))
  91. # endif
  92. # undef popen
  93. # define popen _popen
  94. # undef pclose
  95. # define pclose _pclose
  96. #else
  97. /* Make sure isatty() has a prototype. */
  98. extern int isatty(int);
  99. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  100. /* popen and pclose are not C89 functions and so are
  101. ** sometimes omitted from the <stdio.h> header */
  102. extern FILE *popen(const char*,const char*);
  103. extern int pclose(FILE*);
  104. # else
  105. # define SQLITE_OMIT_POPEN 1
  106. # endif
  107. #endif
  108. #if defined(_WIN32_WCE)
  109. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
  110. * thus we always assume that we have a console. That can be
  111. * overridden with the -batch command line option.
  112. */
  113. #define isatty(x) 1
  114. #endif
  115. /* ctype macros that work with signed characters */
  116. #define IsSpace(X) isspace((unsigned char)X)
  117. #define IsDigit(X) isdigit((unsigned char)X)
  118. #define ToLower(X) (char)tolower((unsigned char)X)
  119. #if defined(_WIN32) || defined(WIN32)
  120. #include <windows.h>
  121. /* string conversion routines only needed on Win32 */
  122. extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
  123. extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
  124. extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
  125. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
  126. #endif
  127. /* On Windows, we normally run with output mode of TEXT so that \n characters
  128. ** are automatically translated into \r\n. However, this behavior needs
  129. ** to be disabled in some cases (ex: when generating CSV output and when
  130. ** rendering quoted strings that contain \n characters). The following
  131. ** routines take care of that.
  132. */
  133. #if defined(_WIN32) || defined(WIN32)
  134. static void setBinaryMode(FILE *file, int isOutput){
  135. if( isOutput ) fflush(file);
  136. _setmode(_fileno(file), _O_BINARY);
  137. }
  138. static void setTextMode(FILE *file, int isOutput){
  139. if( isOutput ) fflush(file);
  140. _setmode(_fileno(file), _O_TEXT);
  141. }
  142. #else
  143. # define setBinaryMode(X,Y)
  144. # define setTextMode(X,Y)
  145. #endif
  146. /* True if the timer is enabled */
  147. static int enableTimer = 0;
  148. /* Return the current wall-clock time */
  149. static sqlite3_int64 timeOfDay(void){
  150. static sqlite3_vfs *clockVfs = 0;
  151. sqlite3_int64 t;
  152. if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
  153. if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
  154. clockVfs->xCurrentTimeInt64(clockVfs, &t);
  155. }else{
  156. double r;
  157. clockVfs->xCurrentTime(clockVfs, &r);
  158. t = (sqlite3_int64)(r*86400000.0);
  159. }
  160. return t;
  161. }
  162. #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
  163. #include <sys/time.h>
  164. #include <sys/resource.h>
  165. /* VxWorks does not support getrusage() as far as we can determine */
  166. #if defined(_WRS_KERNEL) || defined(__RTP__)
  167. struct rusage {
  168. struct timeval ru_utime; /* user CPU time used */
  169. struct timeval ru_stime; /* system CPU time used */
  170. };
  171. #define getrusage(A,B) memset(B,0,sizeof(*B))
  172. #endif
  173. /* Saved resource information for the beginning of an operation */
  174. static struct rusage sBegin; /* CPU time at start */
  175. static sqlite3_int64 iBegin; /* Wall-clock time at start */
  176. /*
  177. ** Begin timing an operation
  178. */
  179. static void beginTimer(void){
  180. if( enableTimer ){
  181. getrusage(RUSAGE_SELF, &sBegin);
  182. iBegin = timeOfDay();
  183. }
  184. }
  185. /* Return the difference of two time_structs in seconds */
  186. static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  187. return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
  188. (double)(pEnd->tv_sec - pStart->tv_sec);
  189. }
  190. /*
  191. ** Print the timing results.
  192. */
  193. static void endTimer(void){
  194. if( enableTimer ){
  195. sqlite3_int64 iEnd = timeOfDay();
  196. struct rusage sEnd;
  197. getrusage(RUSAGE_SELF, &sEnd);
  198. printf("Run Time: real %.3f user %f sys %f\n",
  199. (iEnd - iBegin)*0.001,
  200. timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
  201. timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  202. }
  203. }
  204. #define BEGIN_TIMER beginTimer()
  205. #define END_TIMER endTimer()
  206. #define HAS_TIMER 1
  207. #elif (defined(_WIN32) || defined(WIN32))
  208. /* Saved resource information for the beginning of an operation */
  209. static HANDLE hProcess;
  210. static FILETIME ftKernelBegin;
  211. static FILETIME ftUserBegin;
  212. static sqlite3_int64 ftWallBegin;
  213. typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
  214. LPFILETIME, LPFILETIME);
  215. static GETPROCTIMES getProcessTimesAddr = NULL;
  216. /*
  217. ** Check to see if we have timer support. Return 1 if necessary
  218. ** support found (or found previously).
  219. */
  220. static int hasTimer(void){
  221. if( getProcessTimesAddr ){
  222. return 1;
  223. } else {
  224. /* GetProcessTimes() isn't supported in WIN95 and some other Windows
  225. ** versions. See if the version we are running on has it, and if it
  226. ** does, save off a pointer to it and the current process handle.
  227. */
  228. hProcess = GetCurrentProcess();
  229. if( hProcess ){
  230. HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
  231. if( NULL != hinstLib ){
  232. getProcessTimesAddr =
  233. (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
  234. if( NULL != getProcessTimesAddr ){
  235. return 1;
  236. }
  237. FreeLibrary(hinstLib);
  238. }
  239. }
  240. }
  241. return 0;
  242. }
  243. /*
  244. ** Begin timing an operation
  245. */
  246. static void beginTimer(void){
  247. if( enableTimer && getProcessTimesAddr ){
  248. FILETIME ftCreation, ftExit;
  249. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
  250. &ftKernelBegin,&ftUserBegin);
  251. ftWallBegin = timeOfDay();
  252. }
  253. }
  254. /* Return the difference of two FILETIME structs in seconds */
  255. static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
  256. sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
  257. sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
  258. return (double) ((i64End - i64Start) / 10000000.0);
  259. }
  260. /*
  261. ** Print the timing results.
  262. */
  263. static void endTimer(void){
  264. if( enableTimer && getProcessTimesAddr){
  265. FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
  266. sqlite3_int64 ftWallEnd = timeOfDay();
  267. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
  268. printf("Run Time: real %.3f user %f sys %f\n",
  269. (ftWallEnd - ftWallBegin)*0.001,
  270. timeDiff(&ftUserBegin, &ftUserEnd),
  271. timeDiff(&ftKernelBegin, &ftKernelEnd));
  272. }
  273. }
  274. #define BEGIN_TIMER beginTimer()
  275. #define END_TIMER endTimer()
  276. #define HAS_TIMER hasTimer()
  277. #else
  278. #define BEGIN_TIMER
  279. #define END_TIMER
  280. #define HAS_TIMER 0
  281. #endif
  282. /*
  283. ** Used to prevent warnings about unused parameters
  284. */
  285. #define UNUSED_PARAMETER(x) (void)(x)
  286. /*
  287. ** If the following flag is set, then command execution stops
  288. ** at an error if we are not interactive.
  289. */
  290. static int bail_on_error = 0;
  291. /*
  292. ** Threat stdin as an interactive input if the following variable
  293. ** is true. Otherwise, assume stdin is connected to a file or pipe.
  294. */
  295. static int stdin_is_interactive = 1;
  296. /*
  297. ** On Windows systems we have to know if standard output is a console
  298. ** in order to translate UTF-8 into MBCS. The following variable is
  299. ** true if translation is required.
  300. */
  301. static int stdout_is_console = 1;
  302. /*
  303. ** The following is the open SQLite database. We make a pointer
  304. ** to this database a static variable so that it can be accessed
  305. ** by the SIGINT handler to interrupt database processing.
  306. */
  307. static sqlite3 *globalDb = 0;
  308. /*
  309. ** True if an interrupt (Control-C) has been received.
  310. */
  311. static volatile int seenInterrupt = 0;
  312. /*
  313. ** This is the name of our program. It is set in main(), used
  314. ** in a number of other places, mostly for error messages.
  315. */
  316. static char *Argv0;
  317. /*
  318. ** Prompt strings. Initialized in main. Settable with
  319. ** .prompt main continue
  320. */
  321. static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
  322. static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
  323. /*
  324. ** Render output like fprintf(). Except, if the output is going to the
  325. ** console and if this is running on a Windows machine, translate the
  326. ** output from UTF-8 into MBCS.
  327. */
  328. #if defined(_WIN32) || defined(WIN32)
  329. void utf8_printf(FILE *out, const char *zFormat, ...){
  330. va_list ap;
  331. va_start(ap, zFormat);
  332. if( stdout_is_console && (out==stdout || out==stderr) ){
  333. char *z1 = sqlite3_vmprintf(zFormat, ap);
  334. char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
  335. sqlite3_free(z1);
  336. fputs(z2, out);
  337. sqlite3_free(z2);
  338. }else{
  339. vfprintf(out, zFormat, ap);
  340. }
  341. va_end(ap);
  342. }
  343. #elif !defined(utf8_printf)
  344. # define utf8_printf fprintf
  345. #endif
  346. /*
  347. ** Render output like fprintf(). This should not be used on anything that
  348. ** includes string formatting (e.g. "%s").
  349. */
  350. #if !defined(raw_printf)
  351. # define raw_printf fprintf
  352. #endif
  353. /*
  354. ** Write I/O traces to the following stream.
  355. */
  356. #ifdef SQLITE_ENABLE_IOTRACE
  357. static FILE *iotrace = 0;
  358. #endif
  359. /*
  360. ** This routine works like printf in that its first argument is a
  361. ** format string and subsequent arguments are values to be substituted
  362. ** in place of % fields. The result of formatting this string
  363. ** is written to iotrace.
  364. */
  365. #ifdef SQLITE_ENABLE_IOTRACE
  366. static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
  367. va_list ap;
  368. char *z;
  369. if( iotrace==0 ) return;
  370. va_start(ap, zFormat);
  371. z = sqlite3_vmprintf(zFormat, ap);
  372. va_end(ap);
  373. utf8_printf(iotrace, "%s", z);
  374. sqlite3_free(z);
  375. }
  376. #endif
  377. /*
  378. ** Determines if a string is a number of not.
  379. */
  380. static int isNumber(const char *z, int *realnum){
  381. if( *z=='-' || *z=='+' ) z++;
  382. if( !IsDigit(*z) ){
  383. return 0;
  384. }
  385. z++;
  386. if( realnum ) *realnum = 0;
  387. while( IsDigit(*z) ){ z++; }
  388. if( *z=='.' ){
  389. z++;
  390. if( !IsDigit(*z) ) return 0;
  391. while( IsDigit(*z) ){ z++; }
  392. if( realnum ) *realnum = 1;
  393. }
  394. if( *z=='e' || *z=='E' ){
  395. z++;
  396. if( *z=='+' || *z=='-' ) z++;
  397. if( !IsDigit(*z) ) return 0;
  398. while( IsDigit(*z) ){ z++; }
  399. if( realnum ) *realnum = 1;
  400. }
  401. return *z==0;
  402. }
  403. /*
  404. ** A global char* and an SQL function to access its current value
  405. ** from within an SQL statement. This program used to use the
  406. ** sqlite_exec_printf() API to substitue a string into an SQL statement.
  407. ** The correct way to do this with sqlite3 is to use the bind API, but
  408. ** since the shell is built around the callback paradigm it would be a lot
  409. ** of work. Instead just use this hack, which is quite harmless.
  410. */
  411. static const char *zShellStatic = 0;
  412. static void shellstaticFunc(
  413. sqlite3_context *context,
  414. int argc,
  415. sqlite3_value **argv
  416. ){
  417. assert( 0==argc );
  418. assert( zShellStatic );
  419. UNUSED_PARAMETER(argc);
  420. UNUSED_PARAMETER(argv);
  421. sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
  422. }
  423. /*
  424. ** Compute a string length that is limited to what can be stored in
  425. ** lower 30 bits of a 32-bit signed integer.
  426. */
  427. static int strlen30(const char *z){
  428. const char *z2 = z;
  429. while( *z2 ){ z2++; }
  430. return 0x3fffffff & (int)(z2 - z);
  431. }
  432. /*
  433. ** This routine reads a line of text from FILE in, stores
  434. ** the text in memory obtained from malloc() and returns a pointer
  435. ** to the text. NULL is returned at end of file, or if malloc()
  436. ** fails.
  437. **
  438. ** If zLine is not NULL then it is a malloced buffer returned from
  439. ** a previous call to this routine that may be reused.
  440. */
  441. static char *local_getline(char *zLine, FILE *in){
  442. int nLine = zLine==0 ? 0 : 100;
  443. int n = 0;
  444. while( 1 ){
  445. if( n+100>nLine ){
  446. nLine = nLine*2 + 100;
  447. zLine = realloc(zLine, nLine);
  448. if( zLine==0 ) return 0;
  449. }
  450. if( fgets(&zLine[n], nLine - n, in)==0 ){
  451. if( n==0 ){
  452. free(zLine);
  453. return 0;
  454. }
  455. zLine[n] = 0;
  456. break;
  457. }
  458. while( zLine[n] ) n++;
  459. if( n>0 && zLine[n-1]=='\n' ){
  460. n--;
  461. if( n>0 && zLine[n-1]=='\r' ) n--;
  462. zLine[n] = 0;
  463. break;
  464. }
  465. }
  466. #if defined(_WIN32) || defined(WIN32)
  467. /* For interactive input on Windows systems, translate the
  468. ** multi-byte characterset characters into UTF-8. */
  469. if( stdin_is_interactive && in==stdin ){
  470. char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
  471. if( zTrans ){
  472. int nTrans = strlen30(zTrans)+1;
  473. if( nTrans>nLine ){
  474. zLine = realloc(zLine, nTrans);
  475. if( zLine==0 ){
  476. sqlite3_free(zTrans);
  477. return 0;
  478. }
  479. }
  480. memcpy(zLine, zTrans, nTrans);
  481. sqlite3_free(zTrans);
  482. }
  483. }
  484. #endif /* defined(_WIN32) || defined(WIN32) */
  485. return zLine;
  486. }
  487. /*
  488. ** Retrieve a single line of input text.
  489. **
  490. ** If in==0 then read from standard input and prompt before each line.
  491. ** If isContinuation is true, then a continuation prompt is appropriate.
  492. ** If isContinuation is zero, then the main prompt should be used.
  493. **
  494. ** If zPrior is not NULL then it is a buffer from a prior call to this
  495. ** routine that can be reused.
  496. **
  497. ** The result is stored in space obtained from malloc() and must either
  498. ** be freed by the caller or else passed back into this routine via the
  499. ** zPrior argument for reuse.
  500. */
  501. static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
  502. char *zPrompt;
  503. char *zResult;
  504. if( in!=0 ){
  505. zResult = local_getline(zPrior, in);
  506. }else{
  507. zPrompt = isContinuation ? continuePrompt : mainPrompt;
  508. #if SHELL_USE_LOCAL_GETLINE
  509. printf("%s", zPrompt);
  510. fflush(stdout);
  511. zResult = local_getline(zPrior, stdin);
  512. #else
  513. free(zPrior);
  514. zResult = shell_readline(zPrompt);
  515. if( zResult && *zResult ) shell_add_history(zResult);
  516. #endif
  517. }
  518. return zResult;
  519. }
  520. #if defined(SQLITE_ENABLE_SESSION)
  521. /*
  522. ** State information for a single open session
  523. */
  524. typedef struct OpenSession OpenSession;
  525. struct OpenSession {
  526. char *zName; /* Symbolic name for this session */
  527. int nFilter; /* Number of xFilter rejection GLOB patterns */
  528. char **azFilter; /* Array of xFilter rejection GLOB patterns */
  529. sqlite3_session *p; /* The open session */
  530. };
  531. #endif
  532. /*
  533. ** Shell output mode information from before ".explain on",
  534. ** saved so that it can be restored by ".explain off"
  535. */
  536. typedef struct SavedModeInfo SavedModeInfo;
  537. struct SavedModeInfo {
  538. int valid; /* Is there legit data in here? */
  539. int mode; /* Mode prior to ".explain on" */
  540. int showHeader; /* The ".header" setting prior to ".explain on" */
  541. int colWidth[100]; /* Column widths prior to ".explain on" */
  542. };
  543. /*
  544. ** State information about the database connection is contained in an
  545. ** instance of the following structure.
  546. */
  547. typedef struct ShellState ShellState;
  548. struct ShellState {
  549. sqlite3 *db; /* The database */
  550. int echoOn; /* True to echo input commands */
  551. int autoExplain; /* Automatically turn on .explain mode */
  552. int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
  553. int statsOn; /* True to display memory stats before each finalize */
  554. int scanstatsOn; /* True to display scan stats before each finalize */
  555. int countChanges; /* True to display change counts */
  556. int backslashOn; /* Resolve C-style \x escapes in SQL input text */
  557. int outCount; /* Revert to stdout when reaching zero */
  558. int cnt; /* Number of records displayed so far */
  559. FILE *out; /* Write results here */
  560. FILE *traceOut; /* Output for sqlite3_trace() */
  561. int nErr; /* Number of errors seen */
  562. int mode; /* An output mode setting */
  563. int cMode; /* temporary output mode for the current query */
  564. int normalMode; /* Output mode before ".explain on" */
  565. int writableSchema; /* True if PRAGMA writable_schema=ON */
  566. int showHeader; /* True to show column names in List or Column mode */
  567. int nCheck; /* Number of ".check" commands run */
  568. unsigned shellFlgs; /* Various flags */
  569. char *zDestTable; /* Name of destination table when MODE_Insert */
  570. char zTestcase[30]; /* Name of current test case */
  571. char colSeparator[20]; /* Column separator character for several modes */
  572. char rowSeparator[20]; /* Row separator character for MODE_Ascii */
  573. int colWidth[100]; /* Requested width of each column when in column mode*/
  574. int actualWidth[100]; /* Actual width of each column */
  575. char nullValue[20]; /* The text to print when a NULL comes back from
  576. ** the database */
  577. char outfile[FILENAME_MAX]; /* Filename for *out */
  578. const char *zDbFilename; /* name of the database file */
  579. char *zFreeOnClose; /* Filename to free when closing */
  580. const char *zVfs; /* Name of VFS to use */
  581. sqlite3_stmt *pStmt; /* Current statement if any. */
  582. FILE *pLog; /* Write log output here */
  583. int *aiIndent; /* Array of indents used in MODE_Explain */
  584. int nIndent; /* Size of array aiIndent[] */
  585. int iIndent; /* Index of current op in aiIndent[] */
  586. #if defined(SQLITE_ENABLE_SESSION)
  587. int nSession; /* Number of active sessions */
  588. OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
  589. #endif
  590. };
  591. /*
  592. ** These are the allowed shellFlgs values
  593. */
  594. #define SHFLG_Scratch 0x00001 /* The --scratch option is used */
  595. #define SHFLG_Pagecache 0x00002 /* The --pagecache option is used */
  596. #define SHFLG_Lookaside 0x00004 /* Lookaside memory is used */
  597. /*
  598. ** These are the allowed modes.
  599. */
  600. #define MODE_Line 0 /* One column per line. Blank line between records */
  601. #define MODE_Column 1 /* One record per line in neat columns */
  602. #define MODE_List 2 /* One record per line with a separator */
  603. #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
  604. #define MODE_Html 4 /* Generate an XHTML table */
  605. #define MODE_Insert 5 /* Generate SQL "insert" statements */
  606. #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */
  607. #define MODE_Csv 7 /* Quote strings, numbers are plain */
  608. #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */
  609. #define MODE_Ascii 9 /* Use ASCII unit and record separators (0x1F/0x1E) */
  610. #define MODE_Pretty 10 /* Pretty-print schemas */
  611. static const char *modeDescr[] = {
  612. "line",
  613. "column",
  614. "list",
  615. "semi",
  616. "html",
  617. "insert",
  618. "tcl",
  619. "csv",
  620. "explain",
  621. "ascii",
  622. "prettyprint",
  623. };
  624. /*
  625. ** These are the column/row/line separators used by the various
  626. ** import/export modes.
  627. */
  628. #define SEP_Column "|"
  629. #define SEP_Row "\n"
  630. #define SEP_Tab "\t"
  631. #define SEP_Space " "
  632. #define SEP_Comma ","
  633. #define SEP_CrLf "\r\n"
  634. #define SEP_Unit "\x1F"
  635. #define SEP_Record "\x1E"
  636. /*
  637. ** Number of elements in an array
  638. */
  639. #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
  640. /*
  641. ** A callback for the sqlite3_log() interface.
  642. */
  643. static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  644. ShellState *p = (ShellState*)pArg;
  645. if( p->pLog==0 ) return;
  646. utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  647. fflush(p->pLog);
  648. }
  649. /*
  650. ** Output the given string as a hex-encoded blob (eg. X'1234' )
  651. */
  652. static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  653. int i;
  654. char *zBlob = (char *)pBlob;
  655. raw_printf(out,"X'");
  656. for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
  657. raw_printf(out,"'");
  658. }
  659. /*
  660. ** Output the given string as a quoted string using SQL quoting conventions.
  661. */
  662. static void output_quoted_string(FILE *out, const char *z){
  663. int i;
  664. int nSingle = 0;
  665. setBinaryMode(out, 1);
  666. for(i=0; z[i]; i++){
  667. if( z[i]=='\'' ) nSingle++;
  668. }
  669. if( nSingle==0 ){
  670. utf8_printf(out,"'%s'",z);
  671. }else{
  672. raw_printf(out,"'");
  673. while( *z ){
  674. for(i=0; z[i] && z[i]!='\''; i++){}
  675. if( i==0 ){
  676. raw_printf(out,"''");
  677. z++;
  678. }else if( z[i]=='\'' ){
  679. utf8_printf(out,"%.*s''",i,z);
  680. z += i+1;
  681. }else{
  682. utf8_printf(out,"%s",z);
  683. break;
  684. }
  685. }
  686. raw_printf(out,"'");
  687. }
  688. setTextMode(out, 1);
  689. }
  690. /*
  691. ** Output the given string as a quoted according to C or TCL quoting rules.
  692. */
  693. static void output_c_string(FILE *out, const char *z){
  694. unsigned int c;
  695. fputc('"', out);
  696. while( (c = *(z++))!=0 ){
  697. if( c=='\\' ){
  698. fputc(c, out);
  699. fputc(c, out);
  700. }else if( c=='"' ){
  701. fputc('\\', out);
  702. fputc('"', out);
  703. }else if( c=='\t' ){
  704. fputc('\\', out);
  705. fputc('t', out);
  706. }else if( c=='\n' ){
  707. fputc('\\', out);
  708. fputc('n', out);
  709. }else if( c=='\r' ){
  710. fputc('\\', out);
  711. fputc('r', out);
  712. }else if( !isprint(c&0xff) ){
  713. raw_printf(out, "\\%03o", c&0xff);
  714. }else{
  715. fputc(c, out);
  716. }
  717. }
  718. fputc('"', out);
  719. }
  720. /*
  721. ** Output the given string with characters that are special to
  722. ** HTML escaped.
  723. */
  724. static void output_html_string(FILE *out, const char *z){
  725. int i;
  726. if( z==0 ) z = "";
  727. while( *z ){
  728. for(i=0; z[i]
  729. && z[i]!='<'
  730. && z[i]!='&'
  731. && z[i]!='>'
  732. && z[i]!='\"'
  733. && z[i]!='\'';
  734. i++){}
  735. if( i>0 ){
  736. utf8_printf(out,"%.*s",i,z);
  737. }
  738. if( z[i]=='<' ){
  739. raw_printf(out,"&lt;");
  740. }else if( z[i]=='&' ){
  741. raw_printf(out,"&amp;");
  742. }else if( z[i]=='>' ){
  743. raw_printf(out,"&gt;");
  744. }else if( z[i]=='\"' ){
  745. raw_printf(out,"&quot;");
  746. }else if( z[i]=='\'' ){
  747. raw_printf(out,"&#39;");
  748. }else{
  749. break;
  750. }
  751. z += i + 1;
  752. }
  753. }
  754. /*
  755. ** If a field contains any character identified by a 1 in the following
  756. ** array, then the string must be quoted for CSV.
  757. */
  758. static const char needCsvQuote[] = {
  759. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  760. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  761. 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  767. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  768. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  769. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  770. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  771. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  772. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  773. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  774. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  775. };
  776. /*
  777. ** Output a single term of CSV. Actually, p->colSeparator is used for
  778. ** the separator, which may or may not be a comma. p->nullValue is
  779. ** the null value. Strings are quoted if necessary. The separator
  780. ** is only issued if bSep is true.
  781. */
  782. static void output_csv(ShellState *p, const char *z, int bSep){
  783. FILE *out = p->out;
  784. if( z==0 ){
  785. utf8_printf(out,"%s",p->nullValue);
  786. }else{
  787. int i;
  788. int nSep = strlen30(p->colSeparator);
  789. for(i=0; z[i]; i++){
  790. if( needCsvQuote[((unsigned char*)z)[i]]
  791. || (z[i]==p->colSeparator[0] &&
  792. (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
  793. i = 0;
  794. break;
  795. }
  796. }
  797. if( i==0 ){
  798. putc('"', out);
  799. for(i=0; z[i]; i++){
  800. if( z[i]=='"' ) putc('"', out);
  801. putc(z[i], out);
  802. }
  803. putc('"', out);
  804. }else{
  805. utf8_printf(out, "%s", z);
  806. }
  807. }
  808. if( bSep ){
  809. utf8_printf(p->out, "%s", p->colSeparator);
  810. }
  811. }
  812. #ifdef SIGINT
  813. /*
  814. ** This routine runs when the user presses Ctrl-C
  815. */
  816. static void interrupt_handler(int NotUsed){
  817. UNUSED_PARAMETER(NotUsed);
  818. seenInterrupt++;
  819. if( seenInterrupt>2 ) exit(1);
  820. if( globalDb ) sqlite3_interrupt(globalDb);
  821. }
  822. #endif
  823. #ifndef SQLITE_OMIT_AUTHORIZATION
  824. /*
  825. ** When the ".auth ON" is set, the following authorizer callback is
  826. ** invoked. It always returns SQLITE_OK.
  827. */
  828. static int shellAuth(
  829. void *pClientData,
  830. int op,
  831. const char *zA1,
  832. const char *zA2,
  833. const char *zA3,
  834. const char *zA4
  835. ){
  836. ShellState *p = (ShellState*)pClientData;
  837. static const char *azAction[] = { 0,
  838. "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
  839. "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
  840. "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
  841. "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
  842. "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
  843. "DROP_TRIGGER", "DROP_VIEW", "INSERT",
  844. "PRAGMA", "READ", "SELECT",
  845. "TRANSACTION", "UPDATE", "ATTACH",
  846. "DETACH", "ALTER_TABLE", "REINDEX",
  847. "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
  848. "FUNCTION", "SAVEPOINT", "RECURSIVE"
  849. };
  850. int i;
  851. const char *az[4];
  852. az[0] = zA1;
  853. az[1] = zA2;
  854. az[2] = zA3;
  855. az[3] = zA4;
  856. utf8_printf(p->out, "authorizer: %s", azAction[op]);
  857. for(i=0; i<4; i++){
  858. raw_printf(p->out, " ");
  859. if( az[i] ){
  860. output_c_string(p->out, az[i]);
  861. }else{
  862. raw_printf(p->out, "NULL");
  863. }
  864. }
  865. raw_printf(p->out, "\n");
  866. return SQLITE_OK;
  867. }
  868. #endif
  869. /*
  870. ** This is the callback routine that the shell
  871. ** invokes for each row of a query result.
  872. */
  873. static int shell_callback(
  874. void *pArg,
  875. int nArg, /* Number of result columns */
  876. char **azArg, /* Text of each result column */
  877. char **azCol, /* Column names */
  878. int *aiType /* Column types */
  879. ){
  880. int i;
  881. ShellState *p = (ShellState*)pArg;
  882. switch( p->cMode ){
  883. case MODE_Line: {
  884. int w = 5;
  885. if( azArg==0 ) break;
  886. for(i=0; i<nArg; i++){
  887. int len = strlen30(azCol[i] ? azCol[i] : "");
  888. if( len>w ) w = len;
  889. }
  890. if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
  891. for(i=0; i<nArg; i++){
  892. utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
  893. azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
  894. }
  895. break;
  896. }
  897. case MODE_Explain:
  898. case MODE_Column: {
  899. static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
  900. const int *colWidth;
  901. int showHdr;
  902. char *rowSep;
  903. if( p->cMode==MODE_Column ){
  904. colWidth = p->colWidth;
  905. showHdr = p->showHeader;
  906. rowSep = p->rowSeparator;
  907. }else{
  908. colWidth = aExplainWidths;
  909. showHdr = 1;
  910. rowSep = SEP_Row;
  911. }
  912. if( p->cnt++==0 ){
  913. for(i=0; i<nArg; i++){
  914. int w, n;
  915. if( i<ArraySize(p->colWidth) ){
  916. w = colWidth[i];
  917. }else{
  918. w = 0;
  919. }
  920. if( w==0 ){
  921. w = strlen30(azCol[i] ? azCol[i] : "");
  922. if( w<10 ) w = 10;
  923. n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullValue);
  924. if( w<n ) w = n;
  925. }
  926. if( i<ArraySize(p->actualWidth) ){
  927. p->actualWidth[i] = w;
  928. }
  929. if( showHdr ){
  930. if( w<0 ){
  931. utf8_printf(p->out,"%*.*s%s",-w,-w,azCol[i],
  932. i==nArg-1 ? rowSep : " ");
  933. }else{
  934. utf8_printf(p->out,"%-*.*s%s",w,w,azCol[i],
  935. i==nArg-1 ? rowSep : " ");
  936. }
  937. }
  938. }
  939. if( showHdr ){
  940. for(i=0; i<nArg; i++){
  941. int w;
  942. if( i<ArraySize(p->actualWidth) ){
  943. w = p->actualWidth[i];
  944. if( w<0 ) w = -w;
  945. }else{
  946. w = 10;
  947. }
  948. utf8_printf(p->out,"%-*.*s%s",w,w,
  949. "----------------------------------------------------------"
  950. "----------------------------------------------------------",
  951. i==nArg-1 ? rowSep : " ");
  952. }
  953. }
  954. }
  955. if( azArg==0 ) break;
  956. for(i=0; i<nArg; i++){
  957. int w;
  958. if( i<ArraySize(p->actualWidth) ){
  959. w = p->actualWidth[i];
  960. }else{
  961. w = 10;
  962. }
  963. if( p->cMode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){
  964. w = strlen30(azArg[i]);
  965. }
  966. if( i==1 && p->aiIndent && p->pStmt ){
  967. if( p->iIndent<p->nIndent ){
  968. utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
  969. }
  970. p->iIndent++;
  971. }
  972. if( w<0 ){
  973. utf8_printf(p->out,"%*.*s%s",-w,-w,
  974. azArg[i] ? azArg[i] : p->nullValue,
  975. i==nArg-1 ? rowSep : " ");
  976. }else{
  977. utf8_printf(p->out,"%-*.*s%s",w,w,
  978. azArg[i] ? azArg[i] : p->nullValue,
  979. i==nArg-1 ? rowSep : " ");
  980. }
  981. }
  982. break;
  983. }
  984. case MODE_Semi: { /* .schema and .fullschema output */
  985. utf8_printf(p->out, "%s;\n", azArg[0]);
  986. break;
  987. }
  988. case MODE_Pretty: { /* .schema and .fullschema with --indent */
  989. char *z;
  990. int j;
  991. int nParen = 0;
  992. char cEnd = 0;
  993. char c;
  994. int nLine = 0;
  995. assert( nArg==1 );
  996. if( azArg[0]==0 ) break;
  997. if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
  998. || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
  999. ){
  1000. utf8_printf(p->out, "%s;\n", azArg[0]);
  1001. break;
  1002. }
  1003. z = sqlite3_mprintf("%s", azArg[0]);
  1004. j = 0;
  1005. for(i=0; IsSpace(z[i]); i++){}
  1006. for(; (c = z[i])!=0; i++){
  1007. if( IsSpace(c) ){
  1008. if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
  1009. }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
  1010. j--;
  1011. }
  1012. z[j++] = c;
  1013. }
  1014. while( j>0 && IsSpace(z[j-1]) ){ j--; }
  1015. z[j] = 0;
  1016. if( strlen30(z)>=79 ){
  1017. for(i=j=0; (c = z[i])!=0; i++){
  1018. if( c==cEnd ){
  1019. cEnd = 0;
  1020. }else if( c=='"' || c=='\'' || c=='`' ){
  1021. cEnd = c;
  1022. }else if( c=='[' ){
  1023. cEnd = ']';
  1024. }else if( c=='(' ){
  1025. nParen++;
  1026. }else if( c==')' ){
  1027. nParen--;
  1028. if( nLine>0 && nParen==0 && j>0 ){
  1029. utf8_printf(p->out, "%.*s\n", j, z);
  1030. j = 0;
  1031. }
  1032. }
  1033. z[j++] = c;
  1034. if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
  1035. if( c=='\n' ) j--;
  1036. utf8_printf(p->out, "%.*s\n ", j, z);
  1037. j = 0;
  1038. nLine++;
  1039. while( IsSpace(z[i+1]) ){ i++; }
  1040. }
  1041. }
  1042. z[j] = 0;
  1043. }
  1044. utf8_printf(p->out, "%s;\n", z);
  1045. sqlite3_free(z);
  1046. break;
  1047. }
  1048. case MODE_List: {
  1049. if( p->cnt++==0 && p->showHeader ){
  1050. for(i=0; i<nArg; i++){
  1051. utf8_printf(p->out,"%s%s",azCol[i],
  1052. i==nArg-1 ? p->rowSeparator : p->colSeparator);
  1053. }
  1054. }
  1055. if( azArg==0 ) break;
  1056. for(i=0; i<nArg; i++){
  1057. char *z = azArg[i];
  1058. if( z==0 ) z = p->nullValue;
  1059. utf8_printf(p->out, "%s", z);
  1060. if( i<nArg-1 ){
  1061. utf8_printf(p->out, "%s", p->colSeparator);
  1062. }else{
  1063. utf8_printf(p->out, "%s", p->rowSeparator);
  1064. }
  1065. }
  1066. break;
  1067. }
  1068. case MODE_Html: {
  1069. if( p->cnt++==0 && p->showHeader ){
  1070. raw_printf(p->out,"<TR>");
  1071. for(i=0; i<nArg; i++){
  1072. raw_printf(p->out,"<TH>");
  1073. output_html_string(p->out, azCol[i]);
  1074. raw_printf(p->out,"</TH>\n");
  1075. }
  1076. raw_printf(p->out,"</TR>\n");
  1077. }
  1078. if( azArg==0 ) break;
  1079. raw_printf(p->out,"<TR>");
  1080. for(i=0; i<nArg; i++){
  1081. raw_printf(p->out,"<TD>");
  1082. output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  1083. raw_printf(p->out,"</TD>\n");
  1084. }
  1085. raw_printf(p->out,"</TR>\n");
  1086. break;
  1087. }
  1088. case MODE_Tcl: {
  1089. if( p->cnt++==0 && p->showHeader ){
  1090. for(i=0; i<nArg; i++){
  1091. output_c_string(p->out,azCol[i] ? azCol[i] : "");
  1092. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  1093. }
  1094. utf8_printf(p->out, "%s", p->rowSeparator);
  1095. }
  1096. if( azArg==0 ) break;
  1097. for(i=0; i<nArg; i++){
  1098. output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  1099. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  1100. }
  1101. utf8_printf(p->out, "%s", p->rowSeparator);
  1102. break;
  1103. }
  1104. case MODE_Csv: {
  1105. setBinaryMode(p->out, 1);
  1106. if( p->cnt++==0 && p->showHeader ){
  1107. for(i=0; i<nArg; i++){
  1108. output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  1109. }
  1110. utf8_printf(p->out, "%s", p->rowSeparator);
  1111. }
  1112. if( nArg>0 ){
  1113. for(i=0; i<nArg; i++){
  1114. output_csv(p, azArg[i], i<nArg-1);
  1115. }
  1116. utf8_printf(p->out, "%s", p->rowSeparator);
  1117. }
  1118. setTextMode(p->out, 1);
  1119. break;
  1120. }
  1121. case MODE_Insert: {
  1122. p->cnt++;
  1123. if( azArg==0 ) break;
  1124. utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
  1125. if( p->showHeader ){
  1126. raw_printf(p->out,"(");
  1127. for(i=0; i<nArg; i++){
  1128. char *zSep = i>0 ? ",": "";
  1129. utf8_printf(p->out, "%s%s", zSep, azCol[i]);
  1130. }
  1131. raw_printf(p->out,")");
  1132. }
  1133. raw_printf(p->out," VALUES(");
  1134. for(i=0; i<nArg; i++){
  1135. char *zSep = i>0 ? ",": "";
  1136. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  1137. utf8_printf(p->out,"%sNULL",zSep);
  1138. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  1139. if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
  1140. output_quoted_string(p->out, azArg[i]);
  1141. }else if( aiType && (aiType[i]==SQLITE_INTEGER
  1142. || aiType[i]==SQLITE_FLOAT) ){
  1143. utf8_printf(p->out,"%s%s",zSep, azArg[i]);
  1144. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  1145. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  1146. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  1147. if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
  1148. output_hex_blob(p->out, pBlob, nBlob);
  1149. }else if( isNumber(azArg[i], 0) ){
  1150. utf8_printf(p->out,"%s%s",zSep, azArg[i]);
  1151. }else{
  1152. if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
  1153. output_quoted_string(p->out, azArg[i]);
  1154. }
  1155. }
  1156. raw_printf(p->out,");\n");
  1157. break;
  1158. }
  1159. case MODE_Ascii: {
  1160. if( p->cnt++==0 && p->showHeader ){
  1161. for(i=0; i<nArg; i++){
  1162. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  1163. utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
  1164. }
  1165. utf8_printf(p->out, "%s", p->rowSeparator);
  1166. }
  1167. if( azArg==0 ) break;
  1168. for(i=0; i<nArg; i++){
  1169. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  1170. utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
  1171. }
  1172. utf8_printf(p->out, "%s", p->rowSeparator);
  1173. break;
  1174. }
  1175. }
  1176. return 0;
  1177. }
  1178. /*
  1179. ** This is the callback routine that the SQLite library
  1180. ** invokes for each row of a query result.
  1181. */
  1182. static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  1183. /* since we don't have type info, call the shell_callback with a NULL value */
  1184. return shell_callback(pArg, nArg, azArg, azCol, NULL);
  1185. }
  1186. /*
  1187. ** Set the destination table field of the ShellState structure to
  1188. ** the name of the table given. Escape any quote characters in the
  1189. ** table name.
  1190. */
  1191. static void set_table_name(ShellState *p, const char *zName){
  1192. int i, n;
  1193. int needQuote;
  1194. char *z;
  1195. if( p->zDestTable ){
  1196. free(p->zDestTable);
  1197. p->zDestTable = 0;
  1198. }
  1199. if( zName==0 ) return;
  1200. needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
  1201. for(i=n=0; zName[i]; i++, n++){
  1202. if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
  1203. needQuote = 1;
  1204. if( zName[i]=='\'' ) n++;
  1205. }
  1206. }
  1207. if( needQuote ) n += 2;
  1208. z = p->zDestTable = malloc( n+1 );
  1209. if( z==0 ){
  1210. raw_printf(stderr,"Error: out of memory\n");
  1211. exit(1);
  1212. }
  1213. n = 0;
  1214. if( needQuote ) z[n++] = '\'';
  1215. for(i=0; zName[i]; i++){
  1216. z[n++] = zName[i];
  1217. if( zName[i]=='\'' ) z[n++] = '\'';
  1218. }
  1219. if( needQuote ) z[n++] = '\'';
  1220. z[n] = 0;
  1221. }
  1222. /* zIn is either a pointer to a NULL-terminated string in memory obtained
  1223. ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  1224. ** added to zIn, and the result returned in memory obtained from malloc().
  1225. ** zIn, if it was not NULL, is freed.
  1226. **
  1227. ** If the third argument, quote, is not '\0', then it is used as a
  1228. ** quote character for zAppend.
  1229. */
  1230. static char *appendText(char *zIn, char const *zAppend, char quote){
  1231. int len;
  1232. int i;
  1233. int nAppend = strlen30(zAppend);
  1234. int nIn = (zIn?strlen30(zIn):0);
  1235. len = nAppend+nIn+1;
  1236. if( quote ){
  1237. len += 2;
  1238. for(i=0; i<nAppend; i++){
  1239. if( zAppend[i]==quote ) len++;
  1240. }
  1241. }
  1242. zIn = (char *)realloc(zIn, len);
  1243. if( !zIn ){
  1244. return 0;
  1245. }
  1246. if( quote ){
  1247. char *zCsr = &zIn[nIn];
  1248. *zCsr++ = quote;
  1249. for(i=0; i<nAppend; i++){
  1250. *zCsr++ = zAppend[i];
  1251. if( zAppend[i]==quote ) *zCsr++ = quote;
  1252. }
  1253. *zCsr++ = quote;
  1254. *zCsr++ = '\0';
  1255. assert( (zCsr-zIn)==len );
  1256. }else{
  1257. memcpy(&zIn[nIn], zAppend, nAppend);
  1258. zIn[len-1] = '\0';
  1259. }
  1260. return zIn;
  1261. }
  1262. /*
  1263. ** Execute a query statement that will generate SQL output. Print
  1264. ** the result columns, comma-separated, on a line and then add a
  1265. ** semicolon terminator to the end of that line.
  1266. **
  1267. ** If the number of columns is 1 and that column contains text "--"
  1268. ** then write the semicolon on a separate line. That way, if a
  1269. ** "--" comment occurs at the end of the statement, the comment
  1270. ** won't consume the semicolon terminator.
  1271. */
  1272. static int run_table_dump_query(
  1273. ShellState *p, /* Query context */
  1274. const char *zSelect, /* SELECT statement to extract content */
  1275. const char *zFirstRow /* Print before first row, if not NULL */
  1276. ){
  1277. sqlite3_stmt *pSelect;
  1278. int rc;
  1279. int nResult;
  1280. int i;
  1281. const char *z;
  1282. rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
  1283. if( rc!=SQLITE_OK || !pSelect ){
  1284. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  1285. sqlite3_errmsg(p->db));
  1286. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  1287. return rc;
  1288. }
  1289. rc = sqlite3_step(pSelect);
  1290. nResult = sqlite3_column_count(pSelect);
  1291. while( rc==SQLITE_ROW ){
  1292. if( zFirstRow ){
  1293. utf8_printf(p->out, "%s", zFirstRow);
  1294. zFirstRow = 0;
  1295. }
  1296. z = (const char*)sqlite3_column_text(pSelect, 0);
  1297. utf8_printf(p->out, "%s", z);
  1298. for(i=1; i<nResult; i++){
  1299. utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
  1300. }
  1301. if( z==0 ) z = "";
  1302. while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
  1303. if( z[0] ){
  1304. raw_printf(p->out, "\n;\n");
  1305. }else{
  1306. raw_printf(p->out, ";\n");
  1307. }
  1308. rc = sqlite3_step(pSelect);
  1309. }
  1310. rc = sqlite3_finalize(pSelect);
  1311. if( rc!=SQLITE_OK ){
  1312. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  1313. sqlite3_errmsg(p->db));
  1314. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  1315. }
  1316. return rc;
  1317. }
  1318. /*
  1319. ** Allocate space and save off current error string.
  1320. */
  1321. static char *save_err_msg(
  1322. sqlite3 *db /* Database to query */
  1323. ){
  1324. int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
  1325. char *zErrMsg = sqlite3_malloc64(nErrMsg);
  1326. if( zErrMsg ){
  1327. memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
  1328. }
  1329. return zErrMsg;
  1330. }
  1331. #ifdef __linux__
  1332. /*
  1333. ** Attempt to display I/O stats on Linux using /proc/PID/io
  1334. */
  1335. static void displayLinuxIoStats(FILE *out){
  1336. FILE *in;
  1337. char z[200];
  1338. sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
  1339. in = fopen(z, "rb");
  1340. if( in==0 ) return;
  1341. while( fgets(z, sizeof(z), in)!=0 ){
  1342. static const struct {
  1343. const char *zPattern;
  1344. const char *zDesc;
  1345. } aTrans[] = {
  1346. { "rchar: ", "Bytes received by read():" },
  1347. { "wchar: ", "Bytes sent to write():" },
  1348. { "syscr: ", "Read() system calls:" },
  1349. { "syscw: ", "Write() system calls:" },
  1350. { "read_bytes: ", "Bytes read from storage:" },
  1351. { "write_bytes: ", "Bytes written to storage:" },
  1352. { "cancelled_write_bytes: ", "Cancelled write bytes:" },
  1353. };
  1354. int i;
  1355. for(i=0; i<ArraySize(aTrans); i++){
  1356. int n = (int)strlen(aTrans[i].zPattern);
  1357. if( strncmp(aTrans[i].zPattern, z, n)==0 ){
  1358. utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
  1359. break;
  1360. }
  1361. }
  1362. }
  1363. fclose(in);
  1364. }
  1365. #endif
  1366. /*
  1367. ** Display memory stats.
  1368. */
  1369. static int display_stats(
  1370. sqlite3 *db, /* Database to query */
  1371. ShellState *pArg, /* Pointer to ShellState */
  1372. int bReset /* True to reset the stats */
  1373. ){
  1374. int iCur;
  1375. int iHiwtr;
  1376. if( pArg && pArg->out ){
  1377. iHiwtr = iCur = -1;
  1378. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset);
  1379. raw_printf(pArg->out,
  1380. "Memory Used: %d (max %d) bytes\n",
  1381. iCur, iHiwtr);
  1382. iHiwtr = iCur = -1;
  1383. sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset);
  1384. raw_printf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n",
  1385. iCur, iHiwtr);
  1386. if( pArg->shellFlgs & SHFLG_Pagecache ){
  1387. iHiwtr = iCur = -1;
  1388. sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset);
  1389. raw_printf(pArg->out,
  1390. "Number of Pcache Pages Used: %d (max %d) pages\n",
  1391. iCur, iHiwtr);
  1392. }
  1393. iHiwtr = iCur = -1;
  1394. sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset);
  1395. raw_printf(pArg->out,
  1396. "Number of Pcache Overflow Bytes: %d (max %d) bytes\n",
  1397. iCur, iHiwtr);
  1398. if( pArg->shellFlgs & SHFLG_Scratch ){
  1399. iHiwtr = iCur = -1;
  1400. sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset);
  1401. raw_printf(pArg->out,
  1402. "Number of Scratch Allocations Used: %d (max %d)\n",
  1403. iCur, iHiwtr);
  1404. }
  1405. iHiwtr = iCur = -1;
  1406. sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset);
  1407. raw_printf(pArg->out,
  1408. "Number of Scratch Overflow Bytes: %d (max %d) bytes\n",
  1409. iCur, iHiwtr);
  1410. iHiwtr = iCur = -1;
  1411. sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset);
  1412. raw_printf(pArg->out, "Largest Allocation: %d bytes\n",
  1413. iHiwtr);
  1414. iHiwtr = iCur = -1;
  1415. sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset);
  1416. raw_printf(pArg->out, "Largest Pcache Allocation: %d bytes\n",
  1417. iHiwtr);
  1418. iHiwtr = iCur = -1;
  1419. sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset);
  1420. raw_printf(pArg->out, "Largest Scratch Allocation: %d bytes\n",
  1421. iHiwtr);
  1422. #ifdef YYTRACKMAXSTACKDEPTH
  1423. iHiwtr = iCur = -1;
  1424. sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset);
  1425. raw_printf(pArg->out, "Deepest Parser Stack: %d (max %d)\n",
  1426. iCur, iHiwtr);
  1427. #endif
  1428. }
  1429. if( pArg && pArg->out && db ){
  1430. if( pArg->shellFlgs & SHFLG_Lookaside ){
  1431. iHiwtr = iCur = -1;
  1432. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
  1433. &iCur, &iHiwtr, bReset);
  1434. raw_printf(pArg->out,
  1435. "Lookaside Slots Used: %d (max %d)\n",
  1436. iCur, iHiwtr);
  1437. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
  1438. &iCur, &iHiwtr, bReset);
  1439. raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
  1440. iHiwtr);
  1441. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
  1442. &iCur, &iHiwtr, bReset);
  1443. raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
  1444. iHiwtr);
  1445. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
  1446. &iCur, &iHiwtr, bReset);
  1447. raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
  1448. iHiwtr);
  1449. }
  1450. iHiwtr = iCur = -1;
  1451. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
  1452. raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
  1453. iCur);
  1454. iHiwtr = iCur = -1;
  1455. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
  1456. raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
  1457. iHiwtr = iCur = -1;
  1458. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
  1459. raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
  1460. iHiwtr = iCur = -1;
  1461. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
  1462. raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
  1463. iHiwtr = iCur = -1;
  1464. sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
  1465. raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
  1466. iCur);
  1467. iHiwtr = iCur = -1;
  1468. sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
  1469. raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
  1470. iCur);
  1471. }
  1472. if( pArg && pArg->out && db && pArg->pStmt ){
  1473. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
  1474. bReset);
  1475. raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
  1476. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
  1477. raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
  1478. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
  1479. raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
  1480. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
  1481. raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
  1482. }
  1483. #ifdef __linux__
  1484. displayLinuxIoStats(pArg->out);
  1485. #endif
  1486. /* Do not remove this machine readable comment: extra-stats-output-here */
  1487. return 0;
  1488. }
  1489. /*
  1490. ** Display scan stats.
  1491. */
  1492. static void display_scanstats(
  1493. sqlite3 *db, /* Database to query */
  1494. ShellState *pArg /* Pointer to ShellState */
  1495. ){
  1496. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  1497. UNUSED_PARAMETER(db);
  1498. UNUSED_PARAMETER(pArg);
  1499. #else
  1500. int i, k, n, mx;
  1501. raw_printf(pArg->out, "-------- scanstats --------\n");
  1502. mx = 0;
  1503. for(k=0; k<=mx; k++){
  1504. double rEstLoop = 1.0;
  1505. for(i=n=0; 1; i++){
  1506. sqlite3_stmt *p = pArg->pStmt;
  1507. sqlite3_int64 nLoop, nVisit;
  1508. double rEst;
  1509. int iSid;
  1510. const char *zExplain;
  1511. if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
  1512. break;
  1513. }
  1514. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
  1515. if( iSid>mx ) mx = iSid;
  1516. if( iSid!=k ) continue;
  1517. if( n==0 ){
  1518. rEstLoop = (double)nLoop;
  1519. if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
  1520. }
  1521. n++;
  1522. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
  1523. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
  1524. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
  1525. utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
  1526. rEstLoop *= rEst;
  1527. raw_printf(pArg->out,
  1528. " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
  1529. nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
  1530. );
  1531. }
  1532. }
  1533. raw_printf(pArg->out, "---------------------------\n");
  1534. #endif
  1535. }
  1536. /*
  1537. ** Parameter azArray points to a zero-terminated array of strings. zStr
  1538. ** points to a single nul-terminated string. Return non-zero if zStr
  1539. ** is equal, according to strcmp(), to any of the strings in the array.
  1540. ** Otherwise, return zero.
  1541. */
  1542. static int str_in_array(const char *zStr, const char **azArray){
  1543. int i;
  1544. for(i=0; azArray[i]; i++){
  1545. if( 0==strcmp(zStr, azArray[i]) ) return 1;
  1546. }
  1547. return 0;
  1548. }
  1549. /*
  1550. ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
  1551. ** and populate the ShellState.aiIndent[] array with the number of
  1552. ** spaces each opcode should be indented before it is output.
  1553. **
  1554. ** The indenting rules are:
  1555. **
  1556. ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
  1557. ** all opcodes that occur between the p2 jump destination and the opcode
  1558. ** itself by 2 spaces.
  1559. **
  1560. ** * For each "Goto", if the jump destination is earlier in the program
  1561. ** and ends on one of:
  1562. ** Yield SeekGt SeekLt RowSetRead Rewind
  1563. ** or if the P1 parameter is one instead of zero,
  1564. ** then indent all opcodes between the earlier instruction
  1565. ** and "Goto" by 2 spaces.
  1566. */
  1567. static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
  1568. const char *zSql; /* The text of the SQL statement */
  1569. const char *z; /* Used to check if this is an EXPLAIN */
  1570. int *abYield = 0; /* True if op is an OP_Yield */
  1571. int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
  1572. int iOp; /* Index of operation in p->aiIndent[] */
  1573. const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
  1574. "NextIfOpen", "PrevIfOpen", 0 };
  1575. const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
  1576. "Rewind", 0 };
  1577. const char *azGoto[] = { "Goto", 0 };
  1578. /* Try to figure out if this is really an EXPLAIN statement. If this
  1579. ** cannot be verified, return early. */
  1580. if( sqlite3_column_count(pSql)!=8 ){
  1581. p->cMode = p->mode;
  1582. return;
  1583. }
  1584. zSql = sqlite3_sql(pSql);
  1585. if( zSql==0 ) return;
  1586. for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
  1587. if( sqlite3_strnicmp(z, "explain", 7) ){
  1588. p->cMode = p->mode;
  1589. return;
  1590. }
  1591. for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
  1592. int i;
  1593. int iAddr = sqlite3_column_int(pSql, 0);
  1594. const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
  1595. /* Set p2 to the P2 field of the current opcode. Then, assuming that
  1596. ** p2 is an instruction address, set variable p2op to the index of that
  1597. ** instruction in the aiIndent[] array. p2 and p2op may be different if
  1598. ** the current instruction is part of a sub-program generated by an
  1599. ** SQL trigger or foreign key. */
  1600. int p2 = sqlite3_column_int(pSql, 3);
  1601. int p2op = (p2 + (iOp-iAddr));
  1602. /* Grow the p->aiIndent array as required */
  1603. if( iOp>=nAlloc ){
  1604. if( iOp==0 ){
  1605. /* Do further verfication that this is explain output. Abort if
  1606. ** it is not */
  1607. static const char *explainCols[] = {
  1608. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
  1609. int jj;
  1610. for(jj=0; jj<ArraySize(explainCols); jj++){
  1611. if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
  1612. p->cMode = p->mode;
  1613. sqlite3_reset(pSql);
  1614. return;
  1615. }
  1616. }
  1617. }
  1618. nAlloc += 100;
  1619. p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
  1620. abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
  1621. }
  1622. abYield[iOp] = str_in_array(zOp, azYield);
  1623. p->aiIndent[iOp] = 0;
  1624. p->nIndent = iOp+1;
  1625. if( str_in_array(zOp, azNext) ){
  1626. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  1627. }
  1628. if( str_in_array(zOp, azGoto) && p2op<p->nIndent
  1629. && (abYield[p2op] || sqlite3_column_int(pSql, 2))
  1630. ){
  1631. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  1632. }
  1633. }
  1634. p->iIndent = 0;
  1635. sqlite3_free(abYield);
  1636. sqlite3_reset(pSql);
  1637. }
  1638. /*
  1639. ** Free the array allocated by explain_data_prepare().
  1640. */
  1641. static void explain_data_delete(ShellState *p){
  1642. sqlite3_free(p->aiIndent);
  1643. p->aiIndent = 0;
  1644. p->nIndent = 0;
  1645. p->iIndent = 0;
  1646. }
  1647. /*
  1648. ** Disable and restore .wheretrace and .selecttrace settings.
  1649. */
  1650. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  1651. extern int sqlite3SelectTrace;
  1652. static int savedSelectTrace;
  1653. #endif
  1654. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  1655. extern int sqlite3WhereTrace;
  1656. static int savedWhereTrace;
  1657. #endif
  1658. static void disable_debug_trace_modes(void){
  1659. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  1660. savedSelectTrace = sqlite3SelectTrace;
  1661. sqlite3SelectTrace = 0;
  1662. #endif
  1663. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  1664. savedWhereTrace = sqlite3WhereTrace;
  1665. sqlite3WhereTrace = 0;
  1666. #endif
  1667. }
  1668. static void restore_debug_trace_modes(void){
  1669. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  1670. sqlite3SelectTrace = savedSelectTrace;
  1671. #endif
  1672. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  1673. sqlite3WhereTrace = savedWhereTrace;
  1674. #endif
  1675. }
  1676. /*
  1677. ** Run a prepared statement
  1678. */
  1679. static void exec_prepared_stmt(
  1680. ShellState *pArg, /* Pointer to ShellState */
  1681. sqlite3_stmt *pStmt, /* Statment to run */
  1682. int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
  1683. ){
  1684. int rc;
  1685. /* perform the first step. this will tell us if we
  1686. ** have a result set or not and how wide it is.
  1687. */
  1688. rc = sqlite3_step(pStmt);
  1689. /* if we have a result set... */
  1690. if( SQLITE_ROW == rc ){
  1691. /* if we have a callback... */
  1692. if( xCallback ){
  1693. /* allocate space for col name ptr, value ptr, and type */
  1694. int nCol = sqlite3_column_count(pStmt);
  1695. void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
  1696. if( !pData ){
  1697. rc = SQLITE_NOMEM;
  1698. }else{
  1699. char **azCols = (char **)pData; /* Names of result columns */
  1700. char **azVals = &azCols[nCol]; /* Results */
  1701. int *aiTypes = (int *)&azVals[nCol]; /* Result types */
  1702. int i, x;
  1703. assert(sizeof(int) <= sizeof(char *));
  1704. /* save off ptrs to column names */
  1705. for(i=0; i<nCol; i++){
  1706. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  1707. }
  1708. do{
  1709. /* extract the data and data types */
  1710. for(i=0; i<nCol; i++){
  1711. aiTypes[i] = x = sqlite3_column_type(pStmt, i);
  1712. if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
  1713. azVals[i] = "";
  1714. }else{
  1715. azVals[i] = (char*)sqlite3_column_text(pStmt, i);
  1716. }
  1717. if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
  1718. rc = SQLITE_NOMEM;
  1719. break; /* from for */
  1720. }
  1721. } /* end for */
  1722. /* if data and types extracted successfully... */
  1723. if( SQLITE_ROW == rc ){
  1724. /* call the supplied callback with the result row data */
  1725. if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
  1726. rc = SQLITE_ABORT;
  1727. }else{
  1728. rc = sqlite3_step(pStmt);
  1729. }
  1730. }
  1731. } while( SQLITE_ROW == rc );
  1732. sqlite3_free(pData);
  1733. }
  1734. }else{
  1735. do{
  1736. rc = sqlite3_step(pStmt);
  1737. } while( rc == SQLITE_ROW );
  1738. }
  1739. }
  1740. }
  1741. /*
  1742. ** Execute a statement or set of statements. Print
  1743. ** any result rows/columns depending on the current mode
  1744. ** set via the supplied callback.
  1745. **
  1746. ** This is very similar to SQLite's built-in sqlite3_exec()
  1747. ** function except it takes a slightly different callback
  1748. ** and callback data argument.
  1749. */
  1750. static int shell_exec(
  1751. sqlite3 *db, /* An open database */
  1752. const char *zSql, /* SQL to be evaluated */
  1753. int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
  1754. /* (not the same as sqlite3_exec) */
  1755. ShellState *pArg, /* Pointer to ShellState */
  1756. char **pzErrMsg /* Error msg written here */
  1757. ){
  1758. sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
  1759. int rc = SQLITE_OK; /* Return Code */
  1760. int rc2;
  1761. const char *zLeftover; /* Tail of unprocessed SQL */
  1762. if( pzErrMsg ){
  1763. *pzErrMsg = NULL;
  1764. }
  1765. while( zSql[0] && (SQLITE_OK == rc) ){
  1766. static const char *zStmtSql;
  1767. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  1768. if( SQLITE_OK != rc ){
  1769. if( pzErrMsg ){
  1770. *pzErrMsg = save_err_msg(db);
  1771. }
  1772. }else{
  1773. if( !pStmt ){
  1774. /* this happens for a comment or white-space */
  1775. zSql = zLeftover;
  1776. while( IsSpace(zSql[0]) ) zSql++;
  1777. continue;
  1778. }
  1779. zStmtSql = sqlite3_sql(pStmt);
  1780. while( IsSpace(zStmtSql[0]) ) zStmtSql++;
  1781. /* save off the prepared statment handle and reset row count */
  1782. if( pArg ){
  1783. pArg->pStmt = pStmt;
  1784. pArg->cnt = 0;
  1785. }
  1786. /* echo the sql statement if echo on */
  1787. if( pArg && pArg->echoOn ){
  1788. utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  1789. }
  1790. /* Show the EXPLAIN QUERY PLAN if .eqp is on */
  1791. if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
  1792. sqlite3_stmt *pExplain;
  1793. char *zEQP;
  1794. disable_debug_trace_modes();
  1795. zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
  1796. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  1797. if( rc==SQLITE_OK ){
  1798. while( sqlite3_step(pExplain)==SQLITE_ROW ){
  1799. raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
  1800. raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
  1801. raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
  1802. utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
  1803. }
  1804. }
  1805. sqlite3_finalize(pExplain);
  1806. sqlite3_free(zEQP);
  1807. if( pArg->autoEQP>=2 ){
  1808. /* Also do an EXPLAIN for ".eqp full" mode */
  1809. zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
  1810. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  1811. if( rc==SQLITE_OK ){
  1812. pArg->cMode = MODE_Explain;
  1813. explain_data_prepare(pArg, pExplain);
  1814. exec_prepared_stmt(pArg, pExplain, xCallback);
  1815. explain_data_delete(pArg);
  1816. }
  1817. sqlite3_finalize(pExplain);
  1818. sqlite3_free(zEQP);
  1819. }
  1820. restore_debug_trace_modes();
  1821. }
  1822. if( pArg ){
  1823. pArg->cMode = pArg->mode;
  1824. if( pArg->autoExplain
  1825. && sqlite3_column_count(pStmt)==8
  1826. && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
  1827. ){
  1828. pArg->cMode = MODE_Explain;
  1829. }
  1830. /* If the shell is currently in ".explain" mode, gather the extra
  1831. ** data required to add indents to the output.*/
  1832. if( pArg->cMode==MODE_Explain ){
  1833. explain_data_prepare(pArg, pStmt);
  1834. }
  1835. }
  1836. exec_prepared_stmt(pArg, pStmt, xCallback);
  1837. explain_data_delete(pArg);
  1838. /* print usage stats if stats on */
  1839. if( pArg && pArg->statsOn ){
  1840. display_stats(db, pArg, 0);
  1841. }
  1842. /* print loop-counters if required */
  1843. if( pArg && pArg->scanstatsOn ){
  1844. display_scanstats(db, pArg);
  1845. }
  1846. /* Finalize the statement just executed. If this fails, save a
  1847. ** copy of the error message. Otherwise, set zSql to point to the
  1848. ** next statement to execute. */
  1849. rc2 = sqlite3_finalize(pStmt);
  1850. if( rc!=SQLITE_NOMEM ) rc = rc2;
  1851. if( rc==SQLITE_OK ){
  1852. zSql = zLeftover;
  1853. while( IsSpace(zSql[0]) ) zSql++;
  1854. }else if( pzErrMsg ){
  1855. *pzErrMsg = save_err_msg(db);
  1856. }
  1857. /* clear saved stmt handle */
  1858. if( pArg ){
  1859. pArg->pStmt = NULL;
  1860. }
  1861. }
  1862. } /* end while */
  1863. return rc;
  1864. }
  1865. /*
  1866. ** This is a different callback routine used for dumping the database.
  1867. ** Each row received by this callback consists of a table name,
  1868. ** the table type ("index" or "table") and SQL to create the table.
  1869. ** This routine should print text sufficient to recreate the table.
  1870. */
  1871. static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
  1872. int rc;
  1873. const char *zTable;
  1874. const char *zType;
  1875. const char *zSql;
  1876. const char *zPrepStmt = 0;
  1877. ShellState *p = (ShellState *)pArg;
  1878. UNUSED_PARAMETER(azCol);
  1879. if( nArg!=3 ) return 1;
  1880. zTable = azArg[0];
  1881. zType = azArg[1];
  1882. zSql = azArg[2];
  1883. if( strcmp(zTable, "sqlite_sequence")==0 ){
  1884. zPrepStmt = "DELETE FROM sqlite_sequence;\n";
  1885. }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
  1886. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  1887. }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  1888. return 0;
  1889. }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  1890. char *zIns;
  1891. if( !p->writableSchema ){
  1892. raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
  1893. p->writableSchema = 1;
  1894. }
  1895. zIns = sqlite3_mprintf(
  1896. "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
  1897. "VALUES('table','%q','%q',0,'%q');",
  1898. zTable, zTable, zSql);
  1899. utf8_printf(p->out, "%s\n", zIns);
  1900. sqlite3_free(zIns);
  1901. return 0;
  1902. }else{
  1903. utf8_printf(p->out, "%s;\n", zSql);
  1904. }
  1905. if( strcmp(zType, "table")==0 ){
  1906. sqlite3_stmt *pTableInfo = 0;
  1907. char *zSelect = 0;
  1908. char *zTableInfo = 0;
  1909. char *zTmp = 0;
  1910. int nRow = 0;
  1911. zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
  1912. zTableInfo = appendText(zTableInfo, zTable, '"');
  1913. zTableInfo = appendText(zTableInfo, ");", 0);
  1914. rc = sqlite3_prepare_v2(p->db, zTableInfo, -1, &pTableInfo, 0);
  1915. free(zTableInfo);
  1916. if( rc!=SQLITE_OK || !pTableInfo ){
  1917. return 1;
  1918. }
  1919. zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
  1920. /* Always quote the table name, even if it appears to be pure ascii,
  1921. ** in case it is a keyword. Ex: INSERT INTO "table" ... */
  1922. zTmp = appendText(zTmp, zTable, '"');
  1923. if( zTmp ){
  1924. zSelect = appendText(zSelect, zTmp, '\'');
  1925. free(zTmp);
  1926. }
  1927. zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
  1928. rc = sqlite3_step(pTableInfo);
  1929. while( rc==SQLITE_ROW ){
  1930. const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
  1931. zSelect = appendText(zSelect, "quote(", 0);
  1932. zSelect = appendText(zSelect, zText, '"');
  1933. rc = sqlite3_step(pTableInfo);
  1934. if( rc==SQLITE_ROW ){
  1935. zSelect = appendText(zSelect, "), ", 0);
  1936. }else{
  1937. zSelect = appendText(zSelect, ") ", 0);
  1938. }
  1939. nRow++;
  1940. }
  1941. rc = sqlite3_finalize(pTableInfo);
  1942. if( rc!=SQLITE_OK || nRow==0 ){
  1943. free(zSelect);
  1944. return 1;
  1945. }
  1946. zSelect = appendText(zSelect, "|| ')' FROM ", 0);
  1947. zSelect = appendText(zSelect, zTable, '"');
  1948. rc = run_table_dump_query(p, zSelect, zPrepStmt);
  1949. if( rc==SQLITE_CORRUPT ){
  1950. zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
  1951. run_table_dump_query(p, zSelect, 0);
  1952. }
  1953. free(zSelect);
  1954. }
  1955. return 0;
  1956. }
  1957. /*
  1958. ** Run zQuery. Use dump_callback() as the callback routine so that
  1959. ** the contents of the query are output as SQL statements.
  1960. **
  1961. ** If we get a SQLITE_CORRUPT error, rerun the query after appending
  1962. ** "ORDER BY rowid DESC" to the end.
  1963. */
  1964. static int run_schema_dump_query(
  1965. ShellState *p,
  1966. const char *zQuery
  1967. ){
  1968. int rc;
  1969. char *zErr = 0;
  1970. rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
  1971. if( rc==SQLITE_CORRUPT ){
  1972. char *zQ2;
  1973. int len = strlen30(zQuery);
  1974. raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  1975. if( zErr ){
  1976. utf8_printf(p->out, "/****** %s ******/\n", zErr);
  1977. sqlite3_free(zErr);
  1978. zErr = 0;
  1979. }
  1980. zQ2 = malloc( len+100 );
  1981. if( zQ2==0 ) return rc;
  1982. sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
  1983. rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
  1984. if( rc ){
  1985. utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
  1986. }else{
  1987. rc = SQLITE_CORRUPT;
  1988. }
  1989. sqlite3_free(zErr);
  1990. free(zQ2);
  1991. }
  1992. return rc;
  1993. }
  1994. /*
  1995. ** Text of a help message
  1996. */
  1997. static char zHelp[] =
  1998. #ifndef SQLITE_OMIT_AUTHORIZATION
  1999. ".auth ON|OFF Show authorizer callbacks\n"
  2000. #endif
  2001. ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
  2002. ".bail on|off Stop after hitting an error. Default OFF\n"
  2003. ".binary on|off Turn binary output on or off. Default OFF\n"
  2004. ".changes on|off Show number of rows changed by SQL\n"
  2005. ".check GLOB Fail if output since .testcase does not match\n"
  2006. ".clone NEWDB Clone data into NEWDB from the existing database\n"
  2007. ".databases List names and files of attached databases\n"
  2008. ".dbinfo ?DB? Show status information about the database\n"
  2009. ".dump ?TABLE? ... Dump the database in an SQL text format\n"
  2010. " If TABLE specified, only dump tables matching\n"
  2011. " LIKE pattern TABLE.\n"
  2012. ".echo on|off Turn command echo on or off\n"
  2013. ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
  2014. ".exit Exit this program\n"
  2015. ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
  2016. ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
  2017. ".headers on|off Turn display of headers on or off\n"
  2018. ".help Show this message\n"
  2019. ".import FILE TABLE Import data from FILE into TABLE\n"
  2020. ".indexes ?TABLE? Show names of all indexes\n"
  2021. " If TABLE specified, only show indexes for tables\n"
  2022. " matching LIKE pattern TABLE.\n"
  2023. #ifdef SQLITE_ENABLE_IOTRACE
  2024. ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
  2025. #endif
  2026. ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
  2027. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  2028. ".load FILE ?ENTRY? Load an extension library\n"
  2029. #endif
  2030. ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
  2031. ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
  2032. " ascii Columns/rows delimited by 0x1F and 0x1E\n"
  2033. " csv Comma-separated values\n"
  2034. " column Left-aligned columns. (See .width)\n"
  2035. " html HTML <table> code\n"
  2036. " insert SQL insert statements for TABLE\n"
  2037. " line One value per line\n"
  2038. " list Values delimited by .separator strings\n"
  2039. " tabs Tab-separated values\n"
  2040. " tcl TCL list elements\n"
  2041. ".nullvalue STRING Use STRING in place of NULL values\n"
  2042. ".once FILENAME Output for the next SQL command only to FILENAME\n"
  2043. ".open ?--new? ?FILE? Close existing database and reopen FILE\n"
  2044. " The --new starts with an empty file\n"
  2045. ".output ?FILENAME? Send output to FILENAME or stdout\n"
  2046. ".print STRING... Print literal STRING\n"
  2047. ".prompt MAIN CONTINUE Replace the standard prompts\n"
  2048. ".quit Exit this program\n"
  2049. ".read FILENAME Execute SQL in FILENAME\n"
  2050. ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
  2051. ".save FILE Write in-memory database into FILE\n"
  2052. ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
  2053. ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
  2054. " Add --indent for pretty-printing\n"
  2055. ".separator COL ?ROW? Change the column separator and optionally the row\n"
  2056. " separator for both the output mode and .import\n"
  2057. #if defined(SQLITE_ENABLE_SESSION)
  2058. ".session CMD ... Create or control sessions\n"
  2059. #endif
  2060. ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
  2061. ".show Show the current values for various settings\n"
  2062. ".stats ?on|off? Show stats or turn stats on or off\n"
  2063. ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
  2064. ".tables ?TABLE? List names of tables\n"
  2065. " If TABLE specified, only list tables matching\n"
  2066. " LIKE pattern TABLE.\n"
  2067. ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
  2068. ".timeout MS Try opening locked tables for MS milliseconds\n"
  2069. ".timer on|off Turn SQL timer on or off\n"
  2070. ".trace FILE|off Output each SQL statement as it is run\n"
  2071. ".vfsinfo ?AUX? Information about the top-level VFS\n"
  2072. ".vfslist List all available VFSes\n"
  2073. ".vfsname ?AUX? Print the name of the VFS stack\n"
  2074. ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
  2075. " Negative values right-justify\n"
  2076. ;
  2077. #if defined(SQLITE_ENABLE_SESSION)
  2078. /*
  2079. ** Print help information for the ".sessions" command
  2080. */
  2081. void session_help(ShellState *p){
  2082. raw_printf(p->out,
  2083. ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
  2084. "If ?NAME? is omitted, the first defined session is used.\n"
  2085. "Subcommands:\n"
  2086. " attach TABLE Attach TABLE\n"
  2087. " changeset FILE Write a changeset into FILE\n"
  2088. " close Close one session\n"
  2089. " enable ?BOOLEAN? Set or query the enable bit\n"
  2090. " filter GLOB... Reject tables matching GLOBs\n"
  2091. " indirect ?BOOLEAN? Mark or query the indirect status\n"
  2092. " isempty Query whether the session is empty\n"
  2093. " list List currently open session names\n"
  2094. " open DB NAME Open a new session on DB\n"
  2095. " patchset FILE Write a patchset into FILE\n"
  2096. );
  2097. }
  2098. #endif
  2099. /* Forward reference */
  2100. static int process_input(ShellState *p, FILE *in);
  2101. /*
  2102. ** Read the content of a file into memory obtained from sqlite3_malloc64().
  2103. ** The caller is responsible for freeing the memory.
  2104. **
  2105. ** NULL is returned if any error is encountered.
  2106. */
  2107. static char *readFile(const char *zName){
  2108. FILE *in = fopen(zName, "rb");
  2109. long nIn;
  2110. size_t nRead;
  2111. char *pBuf;
  2112. if( in==0 ) return 0;
  2113. fseek(in, 0, SEEK_END);
  2114. nIn = ftell(in);
  2115. rewind(in);
  2116. pBuf = sqlite3_malloc64( nIn+1 );
  2117. if( pBuf==0 ) return 0;
  2118. nRead = fread(pBuf, nIn, 1, in);
  2119. fclose(in);
  2120. if( nRead!=1 ){
  2121. sqlite3_free(pBuf);
  2122. return 0;
  2123. }
  2124. pBuf[nIn] = 0;
  2125. return pBuf;
  2126. }
  2127. /*
  2128. ** Implementation of the "readfile(X)" SQL function. The entire content
  2129. ** of the file named X is read and returned as a BLOB. NULL is returned
  2130. ** if the file does not exist or is unreadable.
  2131. */
  2132. static void readfileFunc(
  2133. sqlite3_context *context,
  2134. int argc,
  2135. sqlite3_value **argv
  2136. ){
  2137. const char *zName;
  2138. void *pBuf;
  2139. UNUSED_PARAMETER(argc);
  2140. zName = (const char*)sqlite3_value_text(argv[0]);
  2141. if( zName==0 ) return;
  2142. pBuf = readFile(zName);
  2143. if( pBuf ) sqlite3_result_blob(context, pBuf, -1, sqlite3_free);
  2144. }
  2145. /*
  2146. ** Implementation of the "writefile(X,Y)" SQL function. The argument Y
  2147. ** is written into file X. The number of bytes written is returned. Or
  2148. ** NULL is returned if something goes wrong, such as being unable to open
  2149. ** file X for writing.
  2150. */
  2151. static void writefileFunc(
  2152. sqlite3_context *context,
  2153. int argc,
  2154. sqlite3_value **argv
  2155. ){
  2156. FILE *out;
  2157. const char *z;
  2158. sqlite3_int64 rc;
  2159. const char *zFile;
  2160. UNUSED_PARAMETER(argc);
  2161. zFile = (const char*)sqlite3_value_text(argv[0]);
  2162. if( zFile==0 ) return;
  2163. out = fopen(zFile, "wb");
  2164. if( out==0 ) return;
  2165. z = (const char*)sqlite3_value_blob(argv[1]);
  2166. if( z==0 ){
  2167. rc = 0;
  2168. }else{
  2169. rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
  2170. }
  2171. fclose(out);
  2172. sqlite3_result_int64(context, rc);
  2173. }
  2174. #if defined(SQLITE_ENABLE_SESSION)
  2175. /*
  2176. ** Close a single OpenSession object and release all of its associated
  2177. ** resources.
  2178. */
  2179. static void session_close(OpenSession *pSession){
  2180. int i;
  2181. sqlite3session_delete(pSession->p);
  2182. sqlite3_free(pSession->zName);
  2183. for(i=0; i<pSession->nFilter; i++){
  2184. sqlite3_free(pSession->azFilter[i]);
  2185. }
  2186. sqlite3_free(pSession->azFilter);
  2187. memset(pSession, 0, sizeof(OpenSession));
  2188. }
  2189. #endif
  2190. /*
  2191. ** Close all OpenSession objects and release all associated resources.
  2192. */
  2193. #if defined(SQLITE_ENABLE_SESSION)
  2194. static void session_close_all(ShellState *p){
  2195. int i;
  2196. for(i=0; i<p->nSession; i++){
  2197. session_close(&p->aSession[i]);
  2198. }
  2199. p->nSession = 0;
  2200. }
  2201. #else
  2202. # define session_close_all(X)
  2203. #endif
  2204. /*
  2205. ** Implementation of the xFilter function for an open session. Omit
  2206. ** any tables named by ".session filter" but let all other table through.
  2207. */
  2208. #if defined(SQLITE_ENABLE_SESSION)
  2209. static int session_filter(void *pCtx, const char *zTab){
  2210. OpenSession *pSession = (OpenSession*)pCtx;
  2211. int i;
  2212. for(i=0; i<pSession->nFilter; i++){
  2213. if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
  2214. }
  2215. return 1;
  2216. }
  2217. #endif
  2218. /*
  2219. ** Make sure the database is open. If it is not, then open it. If
  2220. ** the database fails to open, print an error message and exit.
  2221. */
  2222. static void open_db(ShellState *p, int keepAlive){
  2223. if( p->db==0 ){
  2224. sqlite3_initialize();
  2225. sqlite3_open(p->zDbFilename, &p->db);
  2226. globalDb = p->db;
  2227. if( p->db && sqlite3_errcode(p->db)==SQLITE_OK ){
  2228. sqlite3_create_function(p->db, "shellstatic", 0, SQLITE_UTF8, 0,
  2229. shellstaticFunc, 0, 0);
  2230. }
  2231. if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
  2232. utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
  2233. p->zDbFilename, sqlite3_errmsg(p->db));
  2234. if( keepAlive ) return;
  2235. exit(1);
  2236. }
  2237. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  2238. sqlite3_enable_load_extension(p->db, 1);
  2239. #endif
  2240. sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
  2241. readfileFunc, 0, 0);
  2242. sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
  2243. writefileFunc, 0, 0);
  2244. }
  2245. }
  2246. /*
  2247. ** Do C-language style dequoting.
  2248. **
  2249. ** \a -> alarm
  2250. ** \b -> backspace
  2251. ** \t -> tab
  2252. ** \n -> newline
  2253. ** \v -> vertical tab
  2254. ** \f -> form feed
  2255. ** \r -> carriage return
  2256. ** \s -> space
  2257. ** \" -> "
  2258. ** \' -> '
  2259. ** \\ -> backslash
  2260. ** \NNN -> ascii character NNN in octal
  2261. */
  2262. static void resolve_backslashes(char *z){
  2263. int i, j;
  2264. char c;
  2265. while( *z && *z!='\\' ) z++;
  2266. for(i=j=0; (c = z[i])!=0; i++, j++){
  2267. if( c=='\\' && z[i+1]!=0 ){
  2268. c = z[++i];
  2269. if( c=='a' ){
  2270. c = '\a';
  2271. }else if( c=='b' ){
  2272. c = '\b';
  2273. }else if( c=='t' ){
  2274. c = '\t';
  2275. }else if( c=='n' ){
  2276. c = '\n';
  2277. }else if( c=='v' ){
  2278. c = '\v';
  2279. }else if( c=='f' ){
  2280. c = '\f';
  2281. }else if( c=='r' ){
  2282. c = '\r';
  2283. }else if( c=='"' ){
  2284. c = '"';
  2285. }else if( c=='\'' ){
  2286. c = '\'';
  2287. }else if( c=='\\' ){
  2288. c = '\\';
  2289. }else if( c>='0' && c<='7' ){
  2290. c -= '0';
  2291. if( z[i+1]>='0' && z[i+1]<='7' ){
  2292. i++;
  2293. c = (c<<3) + z[i] - '0';
  2294. if( z[i+1]>='0' && z[i+1]<='7' ){
  2295. i++;
  2296. c = (c<<3) + z[i] - '0';
  2297. }
  2298. }
  2299. }
  2300. }
  2301. z[j] = c;
  2302. }
  2303. if( j<i ) z[j] = 0;
  2304. }
  2305. /*
  2306. ** Return the value of a hexadecimal digit. Return -1 if the input
  2307. ** is not a hex digit.
  2308. */
  2309. static int hexDigitValue(char c){
  2310. if( c>='0' && c<='9' ) return c - '0';
  2311. if( c>='a' && c<='f' ) return c - 'a' + 10;
  2312. if( c>='A' && c<='F' ) return c - 'A' + 10;
  2313. return -1;
  2314. }
  2315. /*
  2316. ** Interpret zArg as an integer value, possibly with suffixes.
  2317. */
  2318. static sqlite3_int64 integerValue(const char *zArg){
  2319. sqlite3_int64 v = 0;
  2320. static const struct { char *zSuffix; int iMult; } aMult[] = {
  2321. { "KiB", 1024 },
  2322. { "MiB", 1024*1024 },
  2323. { "GiB", 1024*1024*1024 },
  2324. { "KB", 1000 },
  2325. { "MB", 1000000 },
  2326. { "GB", 1000000000 },
  2327. { "K", 1000 },
  2328. { "M", 1000000 },
  2329. { "G", 1000000000 },
  2330. };
  2331. int i;
  2332. int isNeg = 0;
  2333. if( zArg[0]=='-' ){
  2334. isNeg = 1;
  2335. zArg++;
  2336. }else if( zArg[0]=='+' ){
  2337. zArg++;
  2338. }
  2339. if( zArg[0]=='0' && zArg[1]=='x' ){
  2340. int x;
  2341. zArg += 2;
  2342. while( (x = hexDigitValue(zArg[0]))>=0 ){
  2343. v = (v<<4) + x;
  2344. zArg++;
  2345. }
  2346. }else{
  2347. while( IsDigit(zArg[0]) ){
  2348. v = v*10 + zArg[0] - '0';
  2349. zArg++;
  2350. }
  2351. }
  2352. for(i=0; i<ArraySize(aMult); i++){
  2353. if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
  2354. v *= aMult[i].iMult;
  2355. break;
  2356. }
  2357. }
  2358. return isNeg? -v : v;
  2359. }
  2360. /*
  2361. ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
  2362. ** for TRUE and FALSE. Return the integer value if appropriate.
  2363. */
  2364. static int booleanValue(char *zArg){
  2365. int i;
  2366. if( zArg[0]=='0' && zArg[1]=='x' ){
  2367. for(i=2; hexDigitValue(zArg[i])>=0; i++){}
  2368. }else{
  2369. for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
  2370. }
  2371. if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
  2372. if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
  2373. return 1;
  2374. }
  2375. if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
  2376. return 0;
  2377. }
  2378. utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
  2379. zArg);
  2380. return 0;
  2381. }
  2382. /*
  2383. ** Close an output file, assuming it is not stderr or stdout
  2384. */
  2385. static void output_file_close(FILE *f){
  2386. if( f && f!=stdout && f!=stderr ) fclose(f);
  2387. }
  2388. /*
  2389. ** Try to open an output file. The names "stdout" and "stderr" are
  2390. ** recognized and do the right thing. NULL is returned if the output
  2391. ** filename is "off".
  2392. */
  2393. static FILE *output_file_open(const char *zFile){
  2394. FILE *f;
  2395. if( strcmp(zFile,"stdout")==0 ){
  2396. f = stdout;
  2397. }else if( strcmp(zFile, "stderr")==0 ){
  2398. f = stderr;
  2399. }else if( strcmp(zFile, "off")==0 ){
  2400. f = 0;
  2401. }else{
  2402. f = fopen(zFile, "wb");
  2403. if( f==0 ){
  2404. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  2405. }
  2406. }
  2407. return f;
  2408. }
  2409. /*
  2410. ** A routine for handling output from sqlite3_trace().
  2411. */
  2412. static int sql_trace_callback(
  2413. unsigned mType,
  2414. void *pArg,
  2415. void *pP,
  2416. void *pX
  2417. ){
  2418. FILE *f = (FILE*)pArg;
  2419. UNUSED_PARAMETER(mType);
  2420. UNUSED_PARAMETER(pP);
  2421. if( f ){
  2422. const char *z = (const char*)pX;
  2423. int i = (int)strlen(z);
  2424. while( i>0 && z[i-1]==';' ){ i--; }
  2425. utf8_printf(f, "%.*s;\n", i, z);
  2426. }
  2427. return 0;
  2428. }
  2429. /*
  2430. ** A no-op routine that runs with the ".breakpoint" doc-command. This is
  2431. ** a useful spot to set a debugger breakpoint.
  2432. */
  2433. static void test_breakpoint(void){
  2434. static int nCall = 0;
  2435. nCall++;
  2436. }
  2437. /*
  2438. ** An object used to read a CSV and other files for import.
  2439. */
  2440. typedef struct ImportCtx ImportCtx;
  2441. struct ImportCtx {
  2442. const char *zFile; /* Name of the input file */
  2443. FILE *in; /* Read the CSV text from this input stream */
  2444. char *z; /* Accumulated text for a field */
  2445. int n; /* Number of bytes in z */
  2446. int nAlloc; /* Space allocated for z[] */
  2447. int nLine; /* Current line number */
  2448. int cTerm; /* Character that terminated the most recent field */
  2449. int cColSep; /* The column separator character. (Usually ",") */
  2450. int cRowSep; /* The row separator character. (Usually "\n") */
  2451. };
  2452. /* Append a single byte to z[] */
  2453. static void import_append_char(ImportCtx *p, int c){
  2454. if( p->n+1>=p->nAlloc ){
  2455. p->nAlloc += p->nAlloc + 100;
  2456. p->z = sqlite3_realloc64(p->z, p->nAlloc);
  2457. if( p->z==0 ){
  2458. raw_printf(stderr, "out of memory\n");
  2459. exit(1);
  2460. }
  2461. }
  2462. p->z[p->n++] = (char)c;
  2463. }
  2464. /* Read a single field of CSV text. Compatible with rfc4180 and extended
  2465. ** with the option of having a separator other than ",".
  2466. **
  2467. ** + Input comes from p->in.
  2468. ** + Store results in p->z of length p->n. Space to hold p->z comes
  2469. ** from sqlite3_malloc64().
  2470. ** + Use p->cSep as the column separator. The default is ",".
  2471. ** + Use p->rSep as the row separator. The default is "\n".
  2472. ** + Keep track of the line number in p->nLine.
  2473. ** + Store the character that terminates the field in p->cTerm. Store
  2474. ** EOF on end-of-file.
  2475. ** + Report syntax errors on stderr
  2476. */
  2477. static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
  2478. int c;
  2479. int cSep = p->cColSep;
  2480. int rSep = p->cRowSep;
  2481. p->n = 0;
  2482. c = fgetc(p->in);
  2483. if( c==EOF || seenInterrupt ){
  2484. p->cTerm = EOF;
  2485. return 0;
  2486. }
  2487. if( c=='"' ){
  2488. int pc, ppc;
  2489. int startLine = p->nLine;
  2490. int cQuote = c;
  2491. pc = ppc = 0;
  2492. while( 1 ){
  2493. c = fgetc(p->in);
  2494. if( c==rSep ) p->nLine++;
  2495. if( c==cQuote ){
  2496. if( pc==cQuote ){
  2497. pc = 0;
  2498. continue;
  2499. }
  2500. }
  2501. if( (c==cSep && pc==cQuote)
  2502. || (c==rSep && pc==cQuote)
  2503. || (c==rSep && pc=='\r' && ppc==cQuote)
  2504. || (c==EOF && pc==cQuote)
  2505. ){
  2506. do{ p->n--; }while( p->z[p->n]!=cQuote );
  2507. p->cTerm = c;
  2508. break;
  2509. }
  2510. if( pc==cQuote && c!='\r' ){
  2511. utf8_printf(stderr, "%s:%d: unescaped %c character\n",
  2512. p->zFile, p->nLine, cQuote);
  2513. }
  2514. if( c==EOF ){
  2515. utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
  2516. p->zFile, startLine, cQuote);
  2517. p->cTerm = c;
  2518. break;
  2519. }
  2520. import_append_char(p, c);
  2521. ppc = pc;
  2522. pc = c;
  2523. }
  2524. }else{
  2525. while( c!=EOF && c!=cSep && c!=rSep ){
  2526. import_append_char(p, c);
  2527. c = fgetc(p->in);
  2528. }
  2529. if( c==rSep ){
  2530. p->nLine++;
  2531. if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
  2532. }
  2533. p->cTerm = c;
  2534. }
  2535. if( p->z ) p->z[p->n] = 0;
  2536. return p->z;
  2537. }
  2538. /* Read a single field of ASCII delimited text.
  2539. **
  2540. ** + Input comes from p->in.
  2541. ** + Store results in p->z of length p->n. Space to hold p->z comes
  2542. ** from sqlite3_malloc64().
  2543. ** + Use p->cSep as the column separator. The default is "\x1F".
  2544. ** + Use p->rSep as the row separator. The default is "\x1E".
  2545. ** + Keep track of the row number in p->nLine.
  2546. ** + Store the character that terminates the field in p->cTerm. Store
  2547. ** EOF on end-of-file.
  2548. ** + Report syntax errors on stderr
  2549. */
  2550. static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
  2551. int c;
  2552. int cSep = p->cColSep;
  2553. int rSep = p->cRowSep;
  2554. p->n = 0;
  2555. c = fgetc(p->in);
  2556. if( c==EOF || seenInterrupt ){
  2557. p->cTerm = EOF;
  2558. return 0;
  2559. }
  2560. while( c!=EOF && c!=cSep && c!=rSep ){
  2561. import_append_char(p, c);
  2562. c = fgetc(p->in);
  2563. }
  2564. if( c==rSep ){
  2565. p->nLine++;
  2566. }
  2567. p->cTerm = c;
  2568. if( p->z ) p->z[p->n] = 0;
  2569. return p->z;
  2570. }
  2571. /*
  2572. ** Try to transfer data for table zTable. If an error is seen while
  2573. ** moving forward, try to go backwards. The backwards movement won't
  2574. ** work for WITHOUT ROWID tables.
  2575. */
  2576. static void tryToCloneData(
  2577. ShellState *p,
  2578. sqlite3 *newDb,
  2579. const char *zTable
  2580. ){
  2581. sqlite3_stmt *pQuery = 0;
  2582. sqlite3_stmt *pInsert = 0;
  2583. char *zQuery = 0;
  2584. char *zInsert = 0;
  2585. int rc;
  2586. int i, j, n;
  2587. int nTable = (int)strlen(zTable);
  2588. int k = 0;
  2589. int cnt = 0;
  2590. const int spinRate = 10000;
  2591. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
  2592. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  2593. if( rc ){
  2594. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  2595. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  2596. zQuery);
  2597. goto end_data_xfer;
  2598. }
  2599. n = sqlite3_column_count(pQuery);
  2600. zInsert = sqlite3_malloc64(200 + nTable + n*3);
  2601. if( zInsert==0 ){
  2602. raw_printf(stderr, "out of memory\n");
  2603. goto end_data_xfer;
  2604. }
  2605. sqlite3_snprintf(200+nTable,zInsert,
  2606. "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
  2607. i = (int)strlen(zInsert);
  2608. for(j=1; j<n; j++){
  2609. memcpy(zInsert+i, ",?", 2);
  2610. i += 2;
  2611. }
  2612. memcpy(zInsert+i, ");", 3);
  2613. rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
  2614. if( rc ){
  2615. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  2616. sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
  2617. zQuery);
  2618. goto end_data_xfer;
  2619. }
  2620. for(k=0; k<2; k++){
  2621. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  2622. for(i=0; i<n; i++){
  2623. switch( sqlite3_column_type(pQuery, i) ){
  2624. case SQLITE_NULL: {
  2625. sqlite3_bind_null(pInsert, i+1);
  2626. break;
  2627. }
  2628. case SQLITE_INTEGER: {
  2629. sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
  2630. break;
  2631. }
  2632. case SQLITE_FLOAT: {
  2633. sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
  2634. break;
  2635. }
  2636. case SQLITE_TEXT: {
  2637. sqlite3_bind_text(pInsert, i+1,
  2638. (const char*)sqlite3_column_text(pQuery,i),
  2639. -1, SQLITE_STATIC);
  2640. break;
  2641. }
  2642. case SQLITE_BLOB: {
  2643. sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
  2644. sqlite3_column_bytes(pQuery,i),
  2645. SQLITE_STATIC);
  2646. break;
  2647. }
  2648. }
  2649. } /* End for */
  2650. rc = sqlite3_step(pInsert);
  2651. if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  2652. utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
  2653. sqlite3_errmsg(newDb));
  2654. }
  2655. sqlite3_reset(pInsert);
  2656. cnt++;
  2657. if( (cnt%spinRate)==0 ){
  2658. printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
  2659. fflush(stdout);
  2660. }
  2661. } /* End while */
  2662. if( rc==SQLITE_DONE ) break;
  2663. sqlite3_finalize(pQuery);
  2664. sqlite3_free(zQuery);
  2665. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
  2666. zTable);
  2667. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  2668. if( rc ){
  2669. utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
  2670. break;
  2671. }
  2672. } /* End for(k=0...) */
  2673. end_data_xfer:
  2674. sqlite3_finalize(pQuery);
  2675. sqlite3_finalize(pInsert);
  2676. sqlite3_free(zQuery);
  2677. sqlite3_free(zInsert);
  2678. }
  2679. /*
  2680. ** Try to transfer all rows of the schema that match zWhere. For
  2681. ** each row, invoke xForEach() on the object defined by that row.
  2682. ** If an error is encountered while moving forward through the
  2683. ** sqlite_master table, try again moving backwards.
  2684. */
  2685. static void tryToCloneSchema(
  2686. ShellState *p,
  2687. sqlite3 *newDb,
  2688. const char *zWhere,
  2689. void (*xForEach)(ShellState*,sqlite3*,const char*)
  2690. ){
  2691. sqlite3_stmt *pQuery = 0;
  2692. char *zQuery = 0;
  2693. int rc;
  2694. const unsigned char *zName;
  2695. const unsigned char *zSql;
  2696. char *zErrMsg = 0;
  2697. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  2698. " WHERE %s", zWhere);
  2699. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  2700. if( rc ){
  2701. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  2702. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  2703. zQuery);
  2704. goto end_schema_xfer;
  2705. }
  2706. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  2707. zName = sqlite3_column_text(pQuery, 0);
  2708. zSql = sqlite3_column_text(pQuery, 1);
  2709. printf("%s... ", zName); fflush(stdout);
  2710. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  2711. if( zErrMsg ){
  2712. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  2713. sqlite3_free(zErrMsg);
  2714. zErrMsg = 0;
  2715. }
  2716. if( xForEach ){
  2717. xForEach(p, newDb, (const char*)zName);
  2718. }
  2719. printf("done\n");
  2720. }
  2721. if( rc!=SQLITE_DONE ){
  2722. sqlite3_finalize(pQuery);
  2723. sqlite3_free(zQuery);
  2724. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  2725. " WHERE %s ORDER BY rowid DESC", zWhere);
  2726. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  2727. if( rc ){
  2728. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  2729. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  2730. zQuery);
  2731. goto end_schema_xfer;
  2732. }
  2733. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  2734. zName = sqlite3_column_text(pQuery, 0);
  2735. zSql = sqlite3_column_text(pQuery, 1);
  2736. printf("%s... ", zName); fflush(stdout);
  2737. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  2738. if( zErrMsg ){
  2739. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  2740. sqlite3_free(zErrMsg);
  2741. zErrMsg = 0;
  2742. }
  2743. if( xForEach ){
  2744. xForEach(p, newDb, (const char*)zName);
  2745. }
  2746. printf("done\n");
  2747. }
  2748. }
  2749. end_schema_xfer:
  2750. sqlite3_finalize(pQuery);
  2751. sqlite3_free(zQuery);
  2752. }
  2753. /*
  2754. ** Open a new database file named "zNewDb". Try to recover as much information
  2755. ** as possible out of the main database (which might be corrupt) and write it
  2756. ** into zNewDb.
  2757. */
  2758. static void tryToClone(ShellState *p, const char *zNewDb){
  2759. int rc;
  2760. sqlite3 *newDb = 0;
  2761. if( access(zNewDb,0)==0 ){
  2762. utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
  2763. return;
  2764. }
  2765. rc = sqlite3_open(zNewDb, &newDb);
  2766. if( rc ){
  2767. utf8_printf(stderr, "Cannot create output database: %s\n",
  2768. sqlite3_errmsg(newDb));
  2769. }else{
  2770. sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
  2771. sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
  2772. tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
  2773. tryToCloneSchema(p, newDb, "type!='table'", 0);
  2774. sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
  2775. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  2776. }
  2777. sqlite3_close(newDb);
  2778. }
  2779. /*
  2780. ** Change the output file back to stdout
  2781. */
  2782. static void output_reset(ShellState *p){
  2783. if( p->outfile[0]=='|' ){
  2784. #ifndef SQLITE_OMIT_POPEN
  2785. pclose(p->out);
  2786. #endif
  2787. }else{
  2788. output_file_close(p->out);
  2789. }
  2790. p->outfile[0] = 0;
  2791. p->out = stdout;
  2792. }
  2793. /*
  2794. ** Run an SQL command and return the single integer result.
  2795. */
  2796. static int db_int(ShellState *p, const char *zSql){
  2797. sqlite3_stmt *pStmt;
  2798. int res = 0;
  2799. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  2800. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  2801. res = sqlite3_column_int(pStmt,0);
  2802. }
  2803. sqlite3_finalize(pStmt);
  2804. return res;
  2805. }
  2806. /*
  2807. ** Convert a 2-byte or 4-byte big-endian integer into a native integer
  2808. */
  2809. static unsigned int get2byteInt(unsigned char *a){
  2810. return (a[0]<<8) + a[1];
  2811. }
  2812. static unsigned int get4byteInt(unsigned char *a){
  2813. return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
  2814. }
  2815. /*
  2816. ** Implementation of the ".info" command.
  2817. **
  2818. ** Return 1 on error, 2 to exit, and 0 otherwise.
  2819. */
  2820. static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
  2821. static const struct { const char *zName; int ofst; } aField[] = {
  2822. { "file change counter:", 24 },
  2823. { "database page count:", 28 },
  2824. { "freelist page count:", 36 },
  2825. { "schema cookie:", 40 },
  2826. { "schema format:", 44 },
  2827. { "default cache size:", 48 },
  2828. { "autovacuum top root:", 52 },
  2829. { "incremental vacuum:", 64 },
  2830. { "text encoding:", 56 },
  2831. { "user version:", 60 },
  2832. { "application id:", 68 },
  2833. { "software version:", 96 },
  2834. };
  2835. static const struct { const char *zName; const char *zSql; } aQuery[] = {
  2836. { "number of tables:",
  2837. "SELECT count(*) FROM %s WHERE type='table'" },
  2838. { "number of indexes:",
  2839. "SELECT count(*) FROM %s WHERE type='index'" },
  2840. { "number of triggers:",
  2841. "SELECT count(*) FROM %s WHERE type='trigger'" },
  2842. { "number of views:",
  2843. "SELECT count(*) FROM %s WHERE type='view'" },
  2844. { "schema size:",
  2845. "SELECT total(length(sql)) FROM %s" },
  2846. };
  2847. sqlite3_file *pFile = 0;
  2848. int i;
  2849. char *zSchemaTab;
  2850. char *zDb = nArg>=2 ? azArg[1] : "main";
  2851. unsigned char aHdr[100];
  2852. open_db(p, 0);
  2853. if( p->db==0 ) return 1;
  2854. sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
  2855. if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
  2856. return 1;
  2857. }
  2858. i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
  2859. if( i!=SQLITE_OK ){
  2860. raw_printf(stderr, "unable to read database header\n");
  2861. return 1;
  2862. }
  2863. i = get2byteInt(aHdr+16);
  2864. if( i==1 ) i = 65536;
  2865. utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
  2866. utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
  2867. utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
  2868. utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
  2869. for(i=0; i<ArraySize(aField); i++){
  2870. int ofst = aField[i].ofst;
  2871. unsigned int val = get4byteInt(aHdr + ofst);
  2872. utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
  2873. switch( ofst ){
  2874. case 56: {
  2875. if( val==1 ) raw_printf(p->out, " (utf8)");
  2876. if( val==2 ) raw_printf(p->out, " (utf16le)");
  2877. if( val==3 ) raw_printf(p->out, " (utf16be)");
  2878. }
  2879. }
  2880. raw_printf(p->out, "\n");
  2881. }
  2882. if( zDb==0 ){
  2883. zSchemaTab = sqlite3_mprintf("main.sqlite_master");
  2884. }else if( strcmp(zDb,"temp")==0 ){
  2885. zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
  2886. }else{
  2887. zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
  2888. }
  2889. for(i=0; i<ArraySize(aQuery); i++){
  2890. char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
  2891. int val = db_int(p, zSql);
  2892. sqlite3_free(zSql);
  2893. utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
  2894. }
  2895. sqlite3_free(zSchemaTab);
  2896. return 0;
  2897. }
  2898. /*
  2899. ** Print the current sqlite3_errmsg() value to stderr and return 1.
  2900. */
  2901. static int shellDatabaseError(sqlite3 *db){
  2902. const char *zErr = sqlite3_errmsg(db);
  2903. utf8_printf(stderr, "Error: %s\n", zErr);
  2904. return 1;
  2905. }
  2906. /*
  2907. ** Print an out-of-memory message to stderr and return 1.
  2908. */
  2909. static int shellNomemError(void){
  2910. raw_printf(stderr, "Error: out of memory\n");
  2911. return 1;
  2912. }
  2913. /*
  2914. ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
  2915. ** if they match and FALSE (0) if they do not match.
  2916. **
  2917. ** Globbing rules:
  2918. **
  2919. ** '*' Matches any sequence of zero or more characters.
  2920. **
  2921. ** '?' Matches exactly one character.
  2922. **
  2923. ** [...] Matches one character from the enclosed list of
  2924. ** characters.
  2925. **
  2926. ** [^...] Matches one character not in the enclosed list.
  2927. **
  2928. ** '#' Matches any sequence of one or more digits with an
  2929. ** optional + or - sign in front
  2930. **
  2931. ** ' ' Any span of whitespace matches any other span of
  2932. ** whitespace.
  2933. **
  2934. ** Extra whitespace at the end of z[] is ignored.
  2935. */
  2936. static int testcase_glob(const char *zGlob, const char *z){
  2937. int c, c2;
  2938. int invert;
  2939. int seen;
  2940. while( (c = (*(zGlob++)))!=0 ){
  2941. if( IsSpace(c) ){
  2942. if( !IsSpace(*z) ) return 0;
  2943. while( IsSpace(*zGlob) ) zGlob++;
  2944. while( IsSpace(*z) ) z++;
  2945. }else if( c=='*' ){
  2946. while( (c=(*(zGlob++))) == '*' || c=='?' ){
  2947. if( c=='?' && (*(z++))==0 ) return 0;
  2948. }
  2949. if( c==0 ){
  2950. return 1;
  2951. }else if( c=='[' ){
  2952. while( *z && testcase_glob(zGlob-1,z)==0 ){
  2953. z++;
  2954. }
  2955. return (*z)!=0;
  2956. }
  2957. while( (c2 = (*(z++)))!=0 ){
  2958. while( c2!=c ){
  2959. c2 = *(z++);
  2960. if( c2==0 ) return 0;
  2961. }
  2962. if( testcase_glob(zGlob,z) ) return 1;
  2963. }
  2964. return 0;
  2965. }else if( c=='?' ){
  2966. if( (*(z++))==0 ) return 0;
  2967. }else if( c=='[' ){
  2968. int prior_c = 0;
  2969. seen = 0;
  2970. invert = 0;
  2971. c = *(z++);
  2972. if( c==0 ) return 0;
  2973. c2 = *(zGlob++);
  2974. if( c2=='^' ){
  2975. invert = 1;
  2976. c2 = *(zGlob++);
  2977. }
  2978. if( c2==']' ){
  2979. if( c==']' ) seen = 1;
  2980. c2 = *(zGlob++);
  2981. }
  2982. while( c2 && c2!=']' ){
  2983. if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
  2984. c2 = *(zGlob++);
  2985. if( c>=prior_c && c<=c2 ) seen = 1;
  2986. prior_c = 0;
  2987. }else{
  2988. if( c==c2 ){
  2989. seen = 1;
  2990. }
  2991. prior_c = c2;
  2992. }
  2993. c2 = *(zGlob++);
  2994. }
  2995. if( c2==0 || (seen ^ invert)==0 ) return 0;
  2996. }else if( c=='#' ){
  2997. if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
  2998. if( !IsDigit(z[0]) ) return 0;
  2999. z++;
  3000. while( IsDigit(z[0]) ){ z++; }
  3001. }else{
  3002. if( c!=(*(z++)) ) return 0;
  3003. }
  3004. }
  3005. while( IsSpace(*z) ){ z++; }
  3006. return *z==0;
  3007. }
  3008. /*
  3009. ** Compare the string as a command-line option with either one or two
  3010. ** initial "-" characters.
  3011. */
  3012. static int optionMatch(const char *zStr, const char *zOpt){
  3013. if( zStr[0]!='-' ) return 0;
  3014. zStr++;
  3015. if( zStr[0]=='-' ) zStr++;
  3016. return strcmp(zStr, zOpt)==0;
  3017. }
  3018. /*
  3019. ** Delete a file.
  3020. */
  3021. int shellDeleteFile(const char *zFilename){
  3022. int rc;
  3023. #ifdef _WIN32
  3024. wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
  3025. rc = _wunlink(z);
  3026. sqlite3_free(z);
  3027. #else
  3028. rc = unlink(zFilename);
  3029. #endif
  3030. return rc;
  3031. }
  3032. /*
  3033. ** If an input line begins with "." then invoke this routine to
  3034. ** process that line.
  3035. **
  3036. ** Return 1 on error, 2 to exit, and 0 otherwise.
  3037. */
  3038. static int do_meta_command(char *zLine, ShellState *p){
  3039. int h = 1;
  3040. int nArg = 0;
  3041. int n, c;
  3042. int rc = 0;
  3043. char *azArg[50];
  3044. /* Parse the input line into tokens.
  3045. */
  3046. while( zLine[h] && nArg<ArraySize(azArg) ){
  3047. while( IsSpace(zLine[h]) ){ h++; }
  3048. if( zLine[h]==0 ) break;
  3049. if( zLine[h]=='\'' || zLine[h]=='"' ){
  3050. int delim = zLine[h++];
  3051. azArg[nArg++] = &zLine[h];
  3052. while( zLine[h] && zLine[h]!=delim ){
  3053. if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
  3054. h++;
  3055. }
  3056. if( zLine[h]==delim ){
  3057. zLine[h++] = 0;
  3058. }
  3059. if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  3060. }else{
  3061. azArg[nArg++] = &zLine[h];
  3062. while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
  3063. if( zLine[h] ) zLine[h++] = 0;
  3064. resolve_backslashes(azArg[nArg-1]);
  3065. }
  3066. }
  3067. /* Process the input line.
  3068. */
  3069. if( nArg==0 ) return 0; /* no tokens, no error */
  3070. n = strlen30(azArg[0]);
  3071. c = azArg[0][0];
  3072. #ifndef SQLITE_OMIT_AUTHORIZATION
  3073. if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
  3074. if( nArg!=2 ){
  3075. raw_printf(stderr, "Usage: .auth ON|OFF\n");
  3076. rc = 1;
  3077. goto meta_command_exit;
  3078. }
  3079. open_db(p, 0);
  3080. if( booleanValue(azArg[1]) ){
  3081. sqlite3_set_authorizer(p->db, shellAuth, p);
  3082. }else{
  3083. sqlite3_set_authorizer(p->db, 0, 0);
  3084. }
  3085. }else
  3086. #endif
  3087. if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
  3088. || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
  3089. ){
  3090. const char *zDestFile = 0;
  3091. const char *zDb = 0;
  3092. sqlite3 *pDest;
  3093. sqlite3_backup *pBackup;
  3094. int j;
  3095. for(j=1; j<nArg; j++){
  3096. const char *z = azArg[j];
  3097. if( z[0]=='-' ){
  3098. while( z[0]=='-' ) z++;
  3099. /* No options to process at this time */
  3100. {
  3101. utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
  3102. return 1;
  3103. }
  3104. }else if( zDestFile==0 ){
  3105. zDestFile = azArg[j];
  3106. }else if( zDb==0 ){
  3107. zDb = zDestFile;
  3108. zDestFile = azArg[j];
  3109. }else{
  3110. raw_printf(stderr, "too many arguments to .backup\n");
  3111. return 1;
  3112. }
  3113. }
  3114. if( zDestFile==0 ){
  3115. raw_printf(stderr, "missing FILENAME argument on .backup\n");
  3116. return 1;
  3117. }
  3118. if( zDb==0 ) zDb = "main";
  3119. rc = sqlite3_open(zDestFile, &pDest);
  3120. if( rc!=SQLITE_OK ){
  3121. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  3122. sqlite3_close(pDest);
  3123. return 1;
  3124. }
  3125. open_db(p, 0);
  3126. pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  3127. if( pBackup==0 ){
  3128. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  3129. sqlite3_close(pDest);
  3130. return 1;
  3131. }
  3132. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  3133. sqlite3_backup_finish(pBackup);
  3134. if( rc==SQLITE_DONE ){
  3135. rc = 0;
  3136. }else{
  3137. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  3138. rc = 1;
  3139. }
  3140. sqlite3_close(pDest);
  3141. }else
  3142. if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
  3143. if( nArg==2 ){
  3144. bail_on_error = booleanValue(azArg[1]);
  3145. }else{
  3146. raw_printf(stderr, "Usage: .bail on|off\n");
  3147. rc = 1;
  3148. }
  3149. }else
  3150. if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
  3151. if( nArg==2 ){
  3152. if( booleanValue(azArg[1]) ){
  3153. setBinaryMode(p->out, 1);
  3154. }else{
  3155. setTextMode(p->out, 1);
  3156. }
  3157. }else{
  3158. raw_printf(stderr, "Usage: .binary on|off\n");
  3159. rc = 1;
  3160. }
  3161. }else
  3162. /* The undocumented ".breakpoint" command causes a call to the no-op
  3163. ** routine named test_breakpoint().
  3164. */
  3165. if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
  3166. test_breakpoint();
  3167. }else
  3168. if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
  3169. if( nArg==2 ){
  3170. p->countChanges = booleanValue(azArg[1]);
  3171. }else{
  3172. raw_printf(stderr, "Usage: .changes on|off\n");
  3173. rc = 1;
  3174. }
  3175. }else
  3176. /* Cancel output redirection, if it is currently set (by .testcase)
  3177. ** Then read the content of the testcase-out.txt file and compare against
  3178. ** azArg[1]. If there are differences, report an error and exit.
  3179. */
  3180. if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
  3181. char *zRes = 0;
  3182. output_reset(p);
  3183. if( nArg!=2 ){
  3184. raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
  3185. rc = 2;
  3186. }else if( (zRes = readFile("testcase-out.txt"))==0 ){
  3187. raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
  3188. rc = 2;
  3189. }else if( testcase_glob(azArg[1],zRes)==0 ){
  3190. utf8_printf(stderr,
  3191. "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
  3192. p->zTestcase, azArg[1], zRes);
  3193. rc = 2;
  3194. }else{
  3195. utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
  3196. p->nCheck++;
  3197. }
  3198. sqlite3_free(zRes);
  3199. }else
  3200. if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
  3201. if( nArg==2 ){
  3202. tryToClone(p, azArg[1]);
  3203. }else{
  3204. raw_printf(stderr, "Usage: .clone FILENAME\n");
  3205. rc = 1;
  3206. }
  3207. }else
  3208. if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
  3209. ShellState data;
  3210. char *zErrMsg = 0;
  3211. open_db(p, 0);
  3212. memcpy(&data, p, sizeof(data));
  3213. data.showHeader = 1;
  3214. data.cMode = data.mode = MODE_Column;
  3215. data.colWidth[0] = 3;
  3216. data.colWidth[1] = 15;
  3217. data.colWidth[2] = 58;
  3218. data.cnt = 0;
  3219. sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
  3220. if( zErrMsg ){
  3221. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  3222. sqlite3_free(zErrMsg);
  3223. rc = 1;
  3224. }
  3225. }else
  3226. if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
  3227. rc = shell_dbinfo_command(p, nArg, azArg);
  3228. }else
  3229. if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
  3230. open_db(p, 0);
  3231. /* When playing back a "dump", the content might appear in an order
  3232. ** which causes immediate foreign key constraints to be violated.
  3233. ** So disable foreign-key constraint enforcement to prevent problems. */
  3234. if( nArg!=1 && nArg!=2 ){
  3235. raw_printf(stderr, "Usage: .dump ?LIKE-PATTERN?\n");
  3236. rc = 1;
  3237. goto meta_command_exit;
  3238. }
  3239. raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
  3240. raw_printf(p->out, "BEGIN TRANSACTION;\n");
  3241. p->writableSchema = 0;
  3242. sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
  3243. p->nErr = 0;
  3244. if( nArg==1 ){
  3245. run_schema_dump_query(p,
  3246. "SELECT name, type, sql FROM sqlite_master "
  3247. "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
  3248. );
  3249. run_schema_dump_query(p,
  3250. "SELECT name, type, sql FROM sqlite_master "
  3251. "WHERE name=='sqlite_sequence'"
  3252. );
  3253. run_table_dump_query(p,
  3254. "SELECT sql FROM sqlite_master "
  3255. "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
  3256. );
  3257. }else{
  3258. int i;
  3259. for(i=1; i<nArg; i++){
  3260. zShellStatic = azArg[i];
  3261. run_schema_dump_query(p,
  3262. "SELECT name, type, sql FROM sqlite_master "
  3263. "WHERE tbl_name LIKE shellstatic() AND type=='table'"
  3264. " AND sql NOT NULL");
  3265. run_table_dump_query(p,
  3266. "SELECT sql FROM sqlite_master "
  3267. "WHERE sql NOT NULL"
  3268. " AND type IN ('index','trigger','view')"
  3269. " AND tbl_name LIKE shellstatic()", 0
  3270. );
  3271. zShellStatic = 0;
  3272. }
  3273. }
  3274. if( p->writableSchema ){
  3275. raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
  3276. p->writableSchema = 0;
  3277. }
  3278. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  3279. sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
  3280. raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
  3281. }else
  3282. if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
  3283. if( nArg==2 ){
  3284. p->echoOn = booleanValue(azArg[1]);
  3285. }else{
  3286. raw_printf(stderr, "Usage: .echo on|off\n");
  3287. rc = 1;
  3288. }
  3289. }else
  3290. if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
  3291. if( nArg==2 ){
  3292. if( strcmp(azArg[1],"full")==0 ){
  3293. p->autoEQP = 2;
  3294. }else{
  3295. p->autoEQP = booleanValue(azArg[1]);
  3296. }
  3297. }else{
  3298. raw_printf(stderr, "Usage: .eqp on|off|full\n");
  3299. rc = 1;
  3300. }
  3301. }else
  3302. if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
  3303. if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
  3304. rc = 2;
  3305. }else
  3306. if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
  3307. int val = 1;
  3308. if( nArg>=2 ){
  3309. if( strcmp(azArg[1],"auto")==0 ){
  3310. val = 99;
  3311. }else{
  3312. val = booleanValue(azArg[1]);
  3313. }
  3314. }
  3315. if( val==1 && p->mode!=MODE_Explain ){
  3316. p->normalMode = p->mode;
  3317. p->mode = MODE_Explain;
  3318. p->autoExplain = 0;
  3319. }else if( val==0 ){
  3320. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  3321. p->autoExplain = 0;
  3322. }else if( val==99 ){
  3323. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  3324. p->autoExplain = 1;
  3325. }
  3326. }else
  3327. if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
  3328. ShellState data;
  3329. char *zErrMsg = 0;
  3330. int doStats = 0;
  3331. memcpy(&data, p, sizeof(data));
  3332. data.showHeader = 0;
  3333. data.cMode = data.mode = MODE_Semi;
  3334. if( nArg==2 && optionMatch(azArg[1], "indent") ){
  3335. data.cMode = data.mode = MODE_Pretty;
  3336. nArg = 1;
  3337. }
  3338. if( nArg!=1 ){
  3339. raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
  3340. rc = 1;
  3341. goto meta_command_exit;
  3342. }
  3343. open_db(p, 0);
  3344. rc = sqlite3_exec(p->db,
  3345. "SELECT sql FROM"
  3346. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  3347. " FROM sqlite_master UNION ALL"
  3348. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  3349. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  3350. "ORDER BY rowid",
  3351. callback, &data, &zErrMsg
  3352. );
  3353. if( rc==SQLITE_OK ){
  3354. sqlite3_stmt *pStmt;
  3355. rc = sqlite3_prepare_v2(p->db,
  3356. "SELECT rowid FROM sqlite_master"
  3357. " WHERE name GLOB 'sqlite_stat[134]'",
  3358. -1, &pStmt, 0);
  3359. doStats = sqlite3_step(pStmt)==SQLITE_ROW;
  3360. sqlite3_finalize(pStmt);
  3361. }
  3362. if( doStats==0 ){
  3363. raw_printf(p->out, "/* No STAT tables available */\n");
  3364. }else{
  3365. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  3366. sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
  3367. callback, &data, &zErrMsg);
  3368. data.cMode = data.mode = MODE_Insert;
  3369. data.zDestTable = "sqlite_stat1";
  3370. shell_exec(p->db, "SELECT * FROM sqlite_stat1",
  3371. shell_callback, &data,&zErrMsg);
  3372. data.zDestTable = "sqlite_stat3";
  3373. shell_exec(p->db, "SELECT * FROM sqlite_stat3",
  3374. shell_callback, &data,&zErrMsg);
  3375. data.zDestTable = "sqlite_stat4";
  3376. shell_exec(p->db, "SELECT * FROM sqlite_stat4",
  3377. shell_callback, &data, &zErrMsg);
  3378. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  3379. }
  3380. }else
  3381. if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
  3382. if( nArg==2 ){
  3383. p->showHeader = booleanValue(azArg[1]);
  3384. }else{
  3385. raw_printf(stderr, "Usage: .headers on|off\n");
  3386. rc = 1;
  3387. }
  3388. }else
  3389. if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  3390. utf8_printf(p->out, "%s", zHelp);
  3391. }else
  3392. if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
  3393. char *zTable; /* Insert data into this table */
  3394. char *zFile; /* Name of file to extra content from */
  3395. sqlite3_stmt *pStmt = NULL; /* A statement */
  3396. int nCol; /* Number of columns in the table */
  3397. int nByte; /* Number of bytes in an SQL string */
  3398. int i, j; /* Loop counters */
  3399. int needCommit; /* True to COMMIT or ROLLBACK at end */
  3400. int nSep; /* Number of bytes in p->colSeparator[] */
  3401. char *zSql; /* An SQL statement */
  3402. ImportCtx sCtx; /* Reader context */
  3403. char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
  3404. int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
  3405. if( nArg!=3 ){
  3406. raw_printf(stderr, "Usage: .import FILE TABLE\n");
  3407. goto meta_command_exit;
  3408. }
  3409. zFile = azArg[1];
  3410. zTable = azArg[2];
  3411. seenInterrupt = 0;
  3412. memset(&sCtx, 0, sizeof(sCtx));
  3413. open_db(p, 0);
  3414. nSep = strlen30(p->colSeparator);
  3415. if( nSep==0 ){
  3416. raw_printf(stderr,
  3417. "Error: non-null column separator required for import\n");
  3418. return 1;
  3419. }
  3420. if( nSep>1 ){
  3421. raw_printf(stderr, "Error: multi-character column separators not allowed"
  3422. " for import\n");
  3423. return 1;
  3424. }
  3425. nSep = strlen30(p->rowSeparator);
  3426. if( nSep==0 ){
  3427. raw_printf(stderr, "Error: non-null row separator required for import\n");
  3428. return 1;
  3429. }
  3430. if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
  3431. /* When importing CSV (only), if the row separator is set to the
  3432. ** default output row separator, change it to the default input
  3433. ** row separator. This avoids having to maintain different input
  3434. ** and output row separators. */
  3435. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  3436. nSep = strlen30(p->rowSeparator);
  3437. }
  3438. if( nSep>1 ){
  3439. raw_printf(stderr, "Error: multi-character row separators not allowed"
  3440. " for import\n");
  3441. return 1;
  3442. }
  3443. sCtx.zFile = zFile;
  3444. sCtx.nLine = 1;
  3445. if( sCtx.zFile[0]=='|' ){
  3446. #ifdef SQLITE_OMIT_POPEN
  3447. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  3448. return 1;
  3449. #else
  3450. sCtx.in = popen(sCtx.zFile+1, "r");
  3451. sCtx.zFile = "<pipe>";
  3452. xCloser = pclose;
  3453. #endif
  3454. }else{
  3455. sCtx.in = fopen(sCtx.zFile, "rb");
  3456. xCloser = fclose;
  3457. }
  3458. if( p->mode==MODE_Ascii ){
  3459. xRead = ascii_read_one_field;
  3460. }else{
  3461. xRead = csv_read_one_field;
  3462. }
  3463. if( sCtx.in==0 ){
  3464. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  3465. return 1;
  3466. }
  3467. sCtx.cColSep = p->colSeparator[0];
  3468. sCtx.cRowSep = p->rowSeparator[0];
  3469. zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
  3470. if( zSql==0 ){
  3471. raw_printf(stderr, "Error: out of memory\n");
  3472. xCloser(sCtx.in);
  3473. return 1;
  3474. }
  3475. nByte = strlen30(zSql);
  3476. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3477. import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
  3478. if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
  3479. char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
  3480. char cSep = '(';
  3481. while( xRead(&sCtx) ){
  3482. zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
  3483. cSep = ',';
  3484. if( sCtx.cTerm!=sCtx.cColSep ) break;
  3485. }
  3486. if( cSep=='(' ){
  3487. sqlite3_free(zCreate);
  3488. sqlite3_free(sCtx.z);
  3489. xCloser(sCtx.in);
  3490. utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
  3491. return 1;
  3492. }
  3493. zCreate = sqlite3_mprintf("%z\n)", zCreate);
  3494. rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
  3495. sqlite3_free(zCreate);
  3496. if( rc ){
  3497. utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
  3498. sqlite3_errmsg(p->db));
  3499. sqlite3_free(sCtx.z);
  3500. xCloser(sCtx.in);
  3501. return 1;
  3502. }
  3503. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3504. }
  3505. sqlite3_free(zSql);
  3506. if( rc ){
  3507. if (pStmt) sqlite3_finalize(pStmt);
  3508. utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
  3509. xCloser(sCtx.in);
  3510. return 1;
  3511. }
  3512. nCol = sqlite3_column_count(pStmt);
  3513. sqlite3_finalize(pStmt);
  3514. pStmt = 0;
  3515. if( nCol==0 ) return 0; /* no columns, no error */
  3516. zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
  3517. if( zSql==0 ){
  3518. raw_printf(stderr, "Error: out of memory\n");
  3519. xCloser(sCtx.in);
  3520. return 1;
  3521. }
  3522. sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
  3523. j = strlen30(zSql);
  3524. for(i=1; i<nCol; i++){
  3525. zSql[j++] = ',';
  3526. zSql[j++] = '?';
  3527. }
  3528. zSql[j++] = ')';
  3529. zSql[j] = 0;
  3530. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3531. sqlite3_free(zSql);
  3532. if( rc ){
  3533. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  3534. if (pStmt) sqlite3_finalize(pStmt);
  3535. xCloser(sCtx.in);
  3536. return 1;
  3537. }
  3538. needCommit = sqlite3_get_autocommit(p->db);
  3539. if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
  3540. do{
  3541. int startLine = sCtx.nLine;
  3542. for(i=0; i<nCol; i++){
  3543. char *z = xRead(&sCtx);
  3544. /*
  3545. ** Did we reach end-of-file before finding any columns?
  3546. ** If so, stop instead of NULL filling the remaining columns.
  3547. */
  3548. if( z==0 && i==0 ) break;
  3549. /*
  3550. ** Did we reach end-of-file OR end-of-line before finding any
  3551. ** columns in ASCII mode? If so, stop instead of NULL filling
  3552. ** the remaining columns.
  3553. */
  3554. if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
  3555. sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
  3556. if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
  3557. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  3558. "filling the rest with NULL\n",
  3559. sCtx.zFile, startLine, nCol, i+1);
  3560. i += 2;
  3561. while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
  3562. }
  3563. }
  3564. if( sCtx.cTerm==sCtx.cColSep ){
  3565. do{
  3566. xRead(&sCtx);
  3567. i++;
  3568. }while( sCtx.cTerm==sCtx.cColSep );
  3569. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  3570. "extras ignored\n",
  3571. sCtx.zFile, startLine, nCol, i);
  3572. }
  3573. if( i>=nCol ){
  3574. sqlite3_step(pStmt);
  3575. rc = sqlite3_reset(pStmt);
  3576. if( rc!=SQLITE_OK ){
  3577. utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
  3578. startLine, sqlite3_errmsg(p->db));
  3579. }
  3580. }
  3581. }while( sCtx.cTerm!=EOF );
  3582. xCloser(sCtx.in);
  3583. sqlite3_free(sCtx.z);
  3584. sqlite3_finalize(pStmt);
  3585. if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
  3586. }else
  3587. if( c=='i' && (strncmp(azArg[0], "indices", n)==0
  3588. || strncmp(azArg[0], "indexes", n)==0) ){
  3589. ShellState data;
  3590. char *zErrMsg = 0;
  3591. open_db(p, 0);
  3592. memcpy(&data, p, sizeof(data));
  3593. data.showHeader = 0;
  3594. data.cMode = data.mode = MODE_List;
  3595. if( nArg==1 ){
  3596. rc = sqlite3_exec(p->db,
  3597. "SELECT name FROM sqlite_master "
  3598. "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
  3599. "UNION ALL "
  3600. "SELECT name FROM sqlite_temp_master "
  3601. "WHERE type='index' "
  3602. "ORDER BY 1",
  3603. callback, &data, &zErrMsg
  3604. );
  3605. }else if( nArg==2 ){
  3606. zShellStatic = azArg[1];
  3607. rc = sqlite3_exec(p->db,
  3608. "SELECT name FROM sqlite_master "
  3609. "WHERE type='index' AND tbl_name LIKE shellstatic() "
  3610. "UNION ALL "
  3611. "SELECT name FROM sqlite_temp_master "
  3612. "WHERE type='index' AND tbl_name LIKE shellstatic() "
  3613. "ORDER BY 1",
  3614. callback, &data, &zErrMsg
  3615. );
  3616. zShellStatic = 0;
  3617. }else{
  3618. raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
  3619. rc = 1;
  3620. goto meta_command_exit;
  3621. }
  3622. if( zErrMsg ){
  3623. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  3624. sqlite3_free(zErrMsg);
  3625. rc = 1;
  3626. }else if( rc != SQLITE_OK ){
  3627. raw_printf(stderr,
  3628. "Error: querying sqlite_master and sqlite_temp_master\n");
  3629. rc = 1;
  3630. }
  3631. }else
  3632. #ifdef SQLITE_ENABLE_IOTRACE
  3633. if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
  3634. SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
  3635. if( iotrace && iotrace!=stdout ) fclose(iotrace);
  3636. iotrace = 0;
  3637. if( nArg<2 ){
  3638. sqlite3IoTrace = 0;
  3639. }else if( strcmp(azArg[1], "-")==0 ){
  3640. sqlite3IoTrace = iotracePrintf;
  3641. iotrace = stdout;
  3642. }else{
  3643. iotrace = fopen(azArg[1], "w");
  3644. if( iotrace==0 ){
  3645. utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  3646. sqlite3IoTrace = 0;
  3647. rc = 1;
  3648. }else{
  3649. sqlite3IoTrace = iotracePrintf;
  3650. }
  3651. }
  3652. }else
  3653. #endif
  3654. if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
  3655. static const struct {
  3656. const char *zLimitName; /* Name of a limit */
  3657. int limitCode; /* Integer code for that limit */
  3658. } aLimit[] = {
  3659. { "length", SQLITE_LIMIT_LENGTH },
  3660. { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
  3661. { "column", SQLITE_LIMIT_COLUMN },
  3662. { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
  3663. { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
  3664. { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
  3665. { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
  3666. { "attached", SQLITE_LIMIT_ATTACHED },
  3667. { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
  3668. { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
  3669. { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
  3670. { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
  3671. };
  3672. int i, n2;
  3673. open_db(p, 0);
  3674. if( nArg==1 ){
  3675. for(i=0; i<ArraySize(aLimit); i++){
  3676. printf("%20s %d\n", aLimit[i].zLimitName,
  3677. sqlite3_limit(p->db, aLimit[i].limitCode, -1));
  3678. }
  3679. }else if( nArg>3 ){
  3680. raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
  3681. rc = 1;
  3682. goto meta_command_exit;
  3683. }else{
  3684. int iLimit = -1;
  3685. n2 = strlen30(azArg[1]);
  3686. for(i=0; i<ArraySize(aLimit); i++){
  3687. if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
  3688. if( iLimit<0 ){
  3689. iLimit = i;
  3690. }else{
  3691. utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
  3692. rc = 1;
  3693. goto meta_command_exit;
  3694. }
  3695. }
  3696. }
  3697. if( iLimit<0 ){
  3698. utf8_printf(stderr, "unknown limit: \"%s\"\n"
  3699. "enter \".limits\" with no arguments for a list.\n",
  3700. azArg[1]);
  3701. rc = 1;
  3702. goto meta_command_exit;
  3703. }
  3704. if( nArg==3 ){
  3705. sqlite3_limit(p->db, aLimit[iLimit].limitCode,
  3706. (int)integerValue(azArg[2]));
  3707. }
  3708. printf("%20s %d\n", aLimit[iLimit].zLimitName,
  3709. sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
  3710. }
  3711. }else
  3712. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  3713. if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
  3714. const char *zFile, *zProc;
  3715. char *zErrMsg = 0;
  3716. if( nArg<2 ){
  3717. raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
  3718. rc = 1;
  3719. goto meta_command_exit;
  3720. }
  3721. zFile = azArg[1];
  3722. zProc = nArg>=3 ? azArg[2] : 0;
  3723. open_db(p, 0);
  3724. rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  3725. if( rc!=SQLITE_OK ){
  3726. utf8_printf(stderr, "Error: %s\n", zErrMsg);
  3727. sqlite3_free(zErrMsg);
  3728. rc = 1;
  3729. }
  3730. }else
  3731. #endif
  3732. if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
  3733. if( nArg!=2 ){
  3734. raw_printf(stderr, "Usage: .log FILENAME\n");
  3735. rc = 1;
  3736. }else{
  3737. const char *zFile = azArg[1];
  3738. output_file_close(p->pLog);
  3739. p->pLog = output_file_open(zFile);
  3740. }
  3741. }else
  3742. if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
  3743. const char *zMode = nArg>=2 ? azArg[1] : "";
  3744. int n2 = (int)strlen(zMode);
  3745. int c2 = zMode[0];
  3746. if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
  3747. p->mode = MODE_Line;
  3748. }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
  3749. p->mode = MODE_Column;
  3750. }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
  3751. p->mode = MODE_List;
  3752. }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
  3753. p->mode = MODE_Html;
  3754. }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
  3755. p->mode = MODE_Tcl;
  3756. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
  3757. }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
  3758. p->mode = MODE_Csv;
  3759. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  3760. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  3761. }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
  3762. p->mode = MODE_List;
  3763. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
  3764. }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
  3765. p->mode = MODE_Insert;
  3766. set_table_name(p, nArg>=3 ? azArg[2] : "table");
  3767. }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
  3768. p->mode = MODE_Ascii;
  3769. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
  3770. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
  3771. }else {
  3772. raw_printf(stderr, "Error: mode should be one of: "
  3773. "ascii column csv html insert line list tabs tcl\n");
  3774. rc = 1;
  3775. }
  3776. p->cMode = p->mode;
  3777. }else
  3778. if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
  3779. if( nArg==2 ){
  3780. sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
  3781. "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
  3782. }else{
  3783. raw_printf(stderr, "Usage: .nullvalue STRING\n");
  3784. rc = 1;
  3785. }
  3786. }else
  3787. if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
  3788. char *zNewFilename; /* Name of the database file to open */
  3789. int iName = 1; /* Index in azArg[] of the filename */
  3790. int newFlag = 0; /* True to delete file before opening */
  3791. /* Close the existing database */
  3792. session_close_all(p);
  3793. sqlite3_close(p->db);
  3794. p->db = 0;
  3795. sqlite3_free(p->zFreeOnClose);
  3796. p->zFreeOnClose = 0;
  3797. /* Check for command-line arguments */
  3798. for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
  3799. const char *z = azArg[iName];
  3800. if( optionMatch(z,"new") ){
  3801. newFlag = 1;
  3802. }else if( z[0]=='-' ){
  3803. utf8_printf(stderr, "unknown option: %s\n", z);
  3804. rc = 1;
  3805. goto meta_command_exit;
  3806. }
  3807. }
  3808. /* If a filename is specified, try to open it first */
  3809. zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
  3810. if( zNewFilename ){
  3811. if( newFlag ) shellDeleteFile(zNewFilename);
  3812. p->zDbFilename = zNewFilename;
  3813. open_db(p, 1);
  3814. if( p->db==0 ){
  3815. utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
  3816. sqlite3_free(zNewFilename);
  3817. }else{
  3818. p->zFreeOnClose = zNewFilename;
  3819. }
  3820. }
  3821. if( p->db==0 ){
  3822. /* As a fall-back open a TEMP database */
  3823. p->zDbFilename = 0;
  3824. open_db(p, 0);
  3825. }
  3826. }else
  3827. if( c=='o'
  3828. && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
  3829. ){
  3830. const char *zFile = nArg>=2 ? azArg[1] : "stdout";
  3831. if( nArg>2 ){
  3832. utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
  3833. rc = 1;
  3834. goto meta_command_exit;
  3835. }
  3836. if( n>1 && strncmp(azArg[0], "once", n)==0 ){
  3837. if( nArg<2 ){
  3838. raw_printf(stderr, "Usage: .once FILE\n");
  3839. rc = 1;
  3840. goto meta_command_exit;
  3841. }
  3842. p->outCount = 2;
  3843. }else{
  3844. p->outCount = 0;
  3845. }
  3846. output_reset(p);
  3847. if( zFile[0]=='|' ){
  3848. #ifdef SQLITE_OMIT_POPEN
  3849. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  3850. rc = 1;
  3851. p->out = stdout;
  3852. #else
  3853. p->out = popen(zFile + 1, "w");
  3854. if( p->out==0 ){
  3855. utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
  3856. p->out = stdout;
  3857. rc = 1;
  3858. }else{
  3859. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  3860. }
  3861. #endif
  3862. }else{
  3863. p->out = output_file_open(zFile);
  3864. if( p->out==0 ){
  3865. if( strcmp(zFile,"off")!=0 ){
  3866. utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
  3867. }
  3868. p->out = stdout;
  3869. rc = 1;
  3870. } else {
  3871. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  3872. }
  3873. }
  3874. }else
  3875. if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
  3876. int i;
  3877. for(i=1; i<nArg; i++){
  3878. if( i>1 ) raw_printf(p->out, " ");
  3879. utf8_printf(p->out, "%s", azArg[i]);
  3880. }
  3881. raw_printf(p->out, "\n");
  3882. }else
  3883. if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
  3884. if( nArg >= 2) {
  3885. strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  3886. }
  3887. if( nArg >= 3) {
  3888. strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  3889. }
  3890. }else
  3891. if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
  3892. rc = 2;
  3893. }else
  3894. if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
  3895. FILE *alt;
  3896. if( nArg!=2 ){
  3897. raw_printf(stderr, "Usage: .read FILE\n");
  3898. rc = 1;
  3899. goto meta_command_exit;
  3900. }
  3901. alt = fopen(azArg[1], "rb");
  3902. if( alt==0 ){
  3903. utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
  3904. rc = 1;
  3905. }else{
  3906. rc = process_input(p, alt);
  3907. fclose(alt);
  3908. }
  3909. }else
  3910. if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
  3911. const char *zSrcFile;
  3912. const char *zDb;
  3913. sqlite3 *pSrc;
  3914. sqlite3_backup *pBackup;
  3915. int nTimeout = 0;
  3916. if( nArg==2 ){
  3917. zSrcFile = azArg[1];
  3918. zDb = "main";
  3919. }else if( nArg==3 ){
  3920. zSrcFile = azArg[2];
  3921. zDb = azArg[1];
  3922. }else{
  3923. raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
  3924. rc = 1;
  3925. goto meta_command_exit;
  3926. }
  3927. rc = sqlite3_open(zSrcFile, &pSrc);
  3928. if( rc!=SQLITE_OK ){
  3929. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  3930. sqlite3_close(pSrc);
  3931. return 1;
  3932. }
  3933. open_db(p, 0);
  3934. pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  3935. if( pBackup==0 ){
  3936. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  3937. sqlite3_close(pSrc);
  3938. return 1;
  3939. }
  3940. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  3941. || rc==SQLITE_BUSY ){
  3942. if( rc==SQLITE_BUSY ){
  3943. if( nTimeout++ >= 3 ) break;
  3944. sqlite3_sleep(100);
  3945. }
  3946. }
  3947. sqlite3_backup_finish(pBackup);
  3948. if( rc==SQLITE_DONE ){
  3949. rc = 0;
  3950. }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  3951. raw_printf(stderr, "Error: source database is busy\n");
  3952. rc = 1;
  3953. }else{
  3954. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  3955. rc = 1;
  3956. }
  3957. sqlite3_close(pSrc);
  3958. }else
  3959. if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
  3960. if( nArg==2 ){
  3961. p->scanstatsOn = booleanValue(azArg[1]);
  3962. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  3963. raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
  3964. #endif
  3965. }else{
  3966. raw_printf(stderr, "Usage: .scanstats on|off\n");
  3967. rc = 1;
  3968. }
  3969. }else
  3970. if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
  3971. ShellState data;
  3972. char *zErrMsg = 0;
  3973. open_db(p, 0);
  3974. memcpy(&data, p, sizeof(data));
  3975. data.showHeader = 0;
  3976. data.cMode = data.mode = MODE_Semi;
  3977. if( nArg>=2 && optionMatch(azArg[1], "indent") ){
  3978. data.cMode = data.mode = MODE_Pretty;
  3979. nArg--;
  3980. if( nArg==2 ) azArg[1] = azArg[2];
  3981. }
  3982. if( nArg==2 && azArg[1][0]!='-' ){
  3983. int i;
  3984. for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
  3985. if( strcmp(azArg[1],"sqlite_master")==0 ){
  3986. char *new_argv[2], *new_colv[2];
  3987. new_argv[0] = "CREATE TABLE sqlite_master (\n"
  3988. " type text,\n"
  3989. " name text,\n"
  3990. " tbl_name text,\n"
  3991. " rootpage integer,\n"
  3992. " sql text\n"
  3993. ")";
  3994. new_argv[1] = 0;
  3995. new_colv[0] = "sql";
  3996. new_colv[1] = 0;
  3997. callback(&data, 1, new_argv, new_colv);
  3998. rc = SQLITE_OK;
  3999. }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
  4000. char *new_argv[2], *new_colv[2];
  4001. new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
  4002. " type text,\n"
  4003. " name text,\n"
  4004. " tbl_name text,\n"
  4005. " rootpage integer,\n"
  4006. " sql text\n"
  4007. ")";
  4008. new_argv[1] = 0;
  4009. new_colv[0] = "sql";
  4010. new_colv[1] = 0;
  4011. callback(&data, 1, new_argv, new_colv);
  4012. rc = SQLITE_OK;
  4013. }else{
  4014. zShellStatic = azArg[1];
  4015. rc = sqlite3_exec(p->db,
  4016. "SELECT sql FROM "
  4017. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  4018. " FROM sqlite_master UNION ALL"
  4019. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  4020. "WHERE lower(tbl_name) LIKE shellstatic()"
  4021. " AND type!='meta' AND sql NOTNULL "
  4022. "ORDER BY rowid",
  4023. callback, &data, &zErrMsg);
  4024. zShellStatic = 0;
  4025. }
  4026. }else if( nArg==1 ){
  4027. rc = sqlite3_exec(p->db,
  4028. "SELECT sql FROM "
  4029. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  4030. " FROM sqlite_master UNION ALL"
  4031. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  4032. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  4033. "ORDER BY rowid",
  4034. callback, &data, &zErrMsg
  4035. );
  4036. }else{
  4037. raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
  4038. rc = 1;
  4039. goto meta_command_exit;
  4040. }
  4041. if( zErrMsg ){
  4042. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  4043. sqlite3_free(zErrMsg);
  4044. rc = 1;
  4045. }else if( rc != SQLITE_OK ){
  4046. raw_printf(stderr,"Error: querying schema information\n");
  4047. rc = 1;
  4048. }else{
  4049. rc = 0;
  4050. }
  4051. }else
  4052. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  4053. if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
  4054. sqlite3SelectTrace = integerValue(azArg[1]);
  4055. }else
  4056. #endif
  4057. #if defined(SQLITE_ENABLE_SESSION)
  4058. if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
  4059. OpenSession *pSession = &p->aSession[0];
  4060. char **azCmd = &azArg[1];
  4061. int iSes = 0;
  4062. int nCmd = nArg - 1;
  4063. int i;
  4064. if( nArg<=1 ) goto session_syntax_error;
  4065. open_db(p, 0);
  4066. if( nArg>=3 ){
  4067. for(iSes=0; iSes<p->nSession; iSes++){
  4068. if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
  4069. }
  4070. if( iSes<p->nSession ){
  4071. pSession = &p->aSession[iSes];
  4072. azCmd++;
  4073. nCmd--;
  4074. }else{
  4075. pSession = &p->aSession[0];
  4076. iSes = 0;
  4077. }
  4078. }
  4079. /* .session attach TABLE
  4080. ** Invoke the sqlite3session_attach() interface to attach a particular
  4081. ** table so that it is never filtered.
  4082. */
  4083. if( strcmp(azCmd[0],"attach")==0 ){
  4084. if( nCmd!=2 ) goto session_syntax_error;
  4085. if( pSession->p==0 ){
  4086. session_not_open:
  4087. raw_printf(stderr, "ERROR: No sessions are open\n");
  4088. }else{
  4089. rc = sqlite3session_attach(pSession->p, azCmd[1]);
  4090. if( rc ){
  4091. raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
  4092. rc = 0;
  4093. }
  4094. }
  4095. }else
  4096. /* .session changeset FILE
  4097. ** .session patchset FILE
  4098. ** Write a changeset or patchset into a file. The file is overwritten.
  4099. */
  4100. if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
  4101. FILE *out = 0;
  4102. if( nCmd!=2 ) goto session_syntax_error;
  4103. if( pSession->p==0 ) goto session_not_open;
  4104. out = fopen(azCmd[1], "wb");
  4105. if( out==0 ){
  4106. utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
  4107. }else{
  4108. int szChng;
  4109. void *pChng;
  4110. if( azCmd[0][0]=='c' ){
  4111. rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
  4112. }else{
  4113. rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
  4114. }
  4115. if( rc ){
  4116. printf("Error: error code %d\n", rc);
  4117. rc = 0;
  4118. }
  4119. if( pChng
  4120. && fwrite(pChng, szChng, 1, out)!=1 ){
  4121. raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
  4122. szChng);
  4123. }
  4124. sqlite3_free(pChng);
  4125. fclose(out);
  4126. }
  4127. }else
  4128. /* .session close
  4129. ** Close the identified session
  4130. */
  4131. if( strcmp(azCmd[0], "close")==0 ){
  4132. if( nCmd!=1 ) goto session_syntax_error;
  4133. if( p->nSession ){
  4134. session_close(pSession);
  4135. p->aSession[iSes] = p->aSession[--p->nSession];
  4136. }
  4137. }else
  4138. /* .session enable ?BOOLEAN?
  4139. ** Query or set the enable flag
  4140. */
  4141. if( strcmp(azCmd[0], "enable")==0 ){
  4142. int ii;
  4143. if( nCmd>2 ) goto session_syntax_error;
  4144. ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  4145. if( p->nSession ){
  4146. ii = sqlite3session_enable(pSession->p, ii);
  4147. utf8_printf(p->out, "session %s enable flag = %d\n",
  4148. pSession->zName, ii);
  4149. }
  4150. }else
  4151. /* .session filter GLOB ....
  4152. ** Set a list of GLOB patterns of table names to be excluded.
  4153. */
  4154. if( strcmp(azCmd[0], "filter")==0 ){
  4155. int ii, nByte;
  4156. if( nCmd<2 ) goto session_syntax_error;
  4157. if( p->nSession ){
  4158. for(ii=0; ii<pSession->nFilter; ii++){
  4159. sqlite3_free(pSession->azFilter[ii]);
  4160. }
  4161. sqlite3_free(pSession->azFilter);
  4162. nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
  4163. pSession->azFilter = sqlite3_malloc( nByte );
  4164. if( pSession->azFilter==0 ){
  4165. raw_printf(stderr, "Error: out or memory\n");
  4166. exit(1);
  4167. }
  4168. for(ii=1; ii<nCmd; ii++){
  4169. pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
  4170. }
  4171. pSession->nFilter = ii-1;
  4172. }
  4173. }else
  4174. /* .session indirect ?BOOLEAN?
  4175. ** Query or set the indirect flag
  4176. */
  4177. if( strcmp(azCmd[0], "indirect")==0 ){
  4178. int ii;
  4179. if( nCmd>2 ) goto session_syntax_error;
  4180. ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  4181. if( p->nSession ){
  4182. ii = sqlite3session_indirect(pSession->p, ii);
  4183. utf8_printf(p->out, "session %s indirect flag = %d\n",
  4184. pSession->zName, ii);
  4185. }
  4186. }else
  4187. /* .session isempty
  4188. ** Determine if the session is empty
  4189. */
  4190. if( strcmp(azCmd[0], "isempty")==0 ){
  4191. int ii;
  4192. if( nCmd!=1 ) goto session_syntax_error;
  4193. if( p->nSession ){
  4194. ii = sqlite3session_isempty(pSession->p);
  4195. utf8_printf(p->out, "session %s isempty flag = %d\n",
  4196. pSession->zName, ii);
  4197. }
  4198. }else
  4199. /* .session list
  4200. ** List all currently open sessions
  4201. */
  4202. if( strcmp(azCmd[0],"list")==0 ){
  4203. for(i=0; i<p->nSession; i++){
  4204. utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
  4205. }
  4206. }else
  4207. /* .session open DB NAME
  4208. ** Open a new session called NAME on the attached database DB.
  4209. ** DB is normally "main".
  4210. */
  4211. if( strcmp(azCmd[0],"open")==0 ){
  4212. char *zName;
  4213. if( nCmd!=3 ) goto session_syntax_error;
  4214. zName = azCmd[2];
  4215. if( zName[0]==0 ) goto session_syntax_error;
  4216. for(i=0; i<p->nSession; i++){
  4217. if( strcmp(p->aSession[i].zName,zName)==0 ){
  4218. utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
  4219. goto meta_command_exit;
  4220. }
  4221. }
  4222. if( p->nSession>=ArraySize(p->aSession) ){
  4223. raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
  4224. goto meta_command_exit;
  4225. }
  4226. pSession = &p->aSession[p->nSession];
  4227. rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
  4228. if( rc ){
  4229. raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
  4230. rc = 0;
  4231. goto meta_command_exit;
  4232. }
  4233. pSession->nFilter = 0;
  4234. sqlite3session_table_filter(pSession->p, session_filter, pSession);
  4235. p->nSession++;
  4236. pSession->zName = sqlite3_mprintf("%s", zName);
  4237. }else
  4238. /* If no command name matches, show a syntax error */
  4239. session_syntax_error:
  4240. session_help(p);
  4241. }else
  4242. #endif
  4243. #ifdef SQLITE_DEBUG
  4244. /* Undocumented commands for internal testing. Subject to change
  4245. ** without notice. */
  4246. if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
  4247. if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
  4248. int i, v;
  4249. for(i=1; i<nArg; i++){
  4250. v = booleanValue(azArg[i]);
  4251. utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
  4252. }
  4253. }
  4254. if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
  4255. int i; sqlite3_int64 v;
  4256. for(i=1; i<nArg; i++){
  4257. char zBuf[200];
  4258. v = integerValue(azArg[i]);
  4259. sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
  4260. utf8_printf(p->out, "%s", zBuf);
  4261. }
  4262. }
  4263. }else
  4264. #endif
  4265. if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
  4266. if( nArg<2 || nArg>3 ){
  4267. raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
  4268. rc = 1;
  4269. }
  4270. if( nArg>=2 ){
  4271. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
  4272. "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
  4273. }
  4274. if( nArg>=3 ){
  4275. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
  4276. "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
  4277. }
  4278. }else
  4279. if( c=='s'
  4280. && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
  4281. ){
  4282. char *zCmd;
  4283. int i, x;
  4284. if( nArg<2 ){
  4285. raw_printf(stderr, "Usage: .system COMMAND\n");
  4286. rc = 1;
  4287. goto meta_command_exit;
  4288. }
  4289. zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
  4290. for(i=2; i<nArg; i++){
  4291. zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
  4292. zCmd, azArg[i]);
  4293. }
  4294. x = system(zCmd);
  4295. sqlite3_free(zCmd);
  4296. if( x ) raw_printf(stderr, "System command returns %d\n", x);
  4297. }else
  4298. if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
  4299. static const char *azBool[] = { "off", "on", "full", "unk" };
  4300. int i;
  4301. if( nArg!=1 ){
  4302. raw_printf(stderr, "Usage: .show\n");
  4303. rc = 1;
  4304. goto meta_command_exit;
  4305. }
  4306. utf8_printf(p->out, "%12.12s: %s\n","echo", azBool[p->echoOn!=0]);
  4307. utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
  4308. utf8_printf(p->out, "%12.12s: %s\n","explain",
  4309. p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
  4310. utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
  4311. utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
  4312. utf8_printf(p->out, "%12.12s: ", "nullvalue");
  4313. output_c_string(p->out, p->nullValue);
  4314. raw_printf(p->out, "\n");
  4315. utf8_printf(p->out,"%12.12s: %s\n","output",
  4316. strlen30(p->outfile) ? p->outfile : "stdout");
  4317. utf8_printf(p->out,"%12.12s: ", "colseparator");
  4318. output_c_string(p->out, p->colSeparator);
  4319. raw_printf(p->out, "\n");
  4320. utf8_printf(p->out,"%12.12s: ", "rowseparator");
  4321. output_c_string(p->out, p->rowSeparator);
  4322. raw_printf(p->out, "\n");
  4323. utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
  4324. utf8_printf(p->out, "%12.12s: ", "width");
  4325. for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
  4326. raw_printf(p->out, "%d ", p->colWidth[i]);
  4327. }
  4328. raw_printf(p->out, "\n");
  4329. utf8_printf(p->out, "%12.12s: %s\n", "filename",
  4330. p->zDbFilename ? p->zDbFilename : "");
  4331. }else
  4332. if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
  4333. if( nArg==2 ){
  4334. p->statsOn = booleanValue(azArg[1]);
  4335. }else if( nArg==1 ){
  4336. display_stats(p->db, p, 0);
  4337. }else{
  4338. raw_printf(stderr, "Usage: .stats ?on|off?\n");
  4339. rc = 1;
  4340. }
  4341. }else
  4342. if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){
  4343. sqlite3_stmt *pStmt;
  4344. char **azResult;
  4345. int nRow, nAlloc;
  4346. char *zSql = 0;
  4347. int ii;
  4348. open_db(p, 0);
  4349. rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
  4350. if( rc ) return shellDatabaseError(p->db);
  4351. /* Create an SQL statement to query for the list of tables in the
  4352. ** main and all attached databases where the table name matches the
  4353. ** LIKE pattern bound to variable "?1". */
  4354. zSql = sqlite3_mprintf(
  4355. "SELECT name FROM sqlite_master"
  4356. " WHERE type IN ('table','view')"
  4357. " AND name NOT LIKE 'sqlite_%%'"
  4358. " AND name LIKE ?1");
  4359. while( zSql && sqlite3_step(pStmt)==SQLITE_ROW ){
  4360. const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
  4361. if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue;
  4362. if( strcmp(zDbName,"temp")==0 ){
  4363. zSql = sqlite3_mprintf(
  4364. "%z UNION ALL "
  4365. "SELECT 'temp.' || name FROM sqlite_temp_master"
  4366. " WHERE type IN ('table','view')"
  4367. " AND name NOT LIKE 'sqlite_%%'"
  4368. " AND name LIKE ?1", zSql);
  4369. }else{
  4370. zSql = sqlite3_mprintf(
  4371. "%z UNION ALL "
  4372. "SELECT '%q.' || name FROM \"%w\".sqlite_master"
  4373. " WHERE type IN ('table','view')"
  4374. " AND name NOT LIKE 'sqlite_%%'"
  4375. " AND name LIKE ?1", zSql, zDbName, zDbName);
  4376. }
  4377. }
  4378. rc = sqlite3_finalize(pStmt);
  4379. if( zSql && rc==SQLITE_OK ){
  4380. zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
  4381. if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  4382. }
  4383. sqlite3_free(zSql);
  4384. if( !zSql ) return shellNomemError();
  4385. if( rc ) return shellDatabaseError(p->db);
  4386. /* Run the SQL statement prepared by the above block. Store the results
  4387. ** as an array of nul-terminated strings in azResult[]. */
  4388. nRow = nAlloc = 0;
  4389. azResult = 0;
  4390. if( nArg>1 ){
  4391. sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
  4392. }else{
  4393. sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
  4394. }
  4395. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  4396. if( nRow>=nAlloc ){
  4397. char **azNew;
  4398. int n2 = nAlloc*2 + 10;
  4399. azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
  4400. if( azNew==0 ){
  4401. rc = shellNomemError();
  4402. break;
  4403. }
  4404. nAlloc = n2;
  4405. azResult = azNew;
  4406. }
  4407. azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  4408. if( 0==azResult[nRow] ){
  4409. rc = shellNomemError();
  4410. break;
  4411. }
  4412. nRow++;
  4413. }
  4414. if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
  4415. rc = shellDatabaseError(p->db);
  4416. }
  4417. /* Pretty-print the contents of array azResult[] to the output */
  4418. if( rc==0 && nRow>0 ){
  4419. int len, maxlen = 0;
  4420. int i, j;
  4421. int nPrintCol, nPrintRow;
  4422. for(i=0; i<nRow; i++){
  4423. len = strlen30(azResult[i]);
  4424. if( len>maxlen ) maxlen = len;
  4425. }
  4426. nPrintCol = 80/(maxlen+2);
  4427. if( nPrintCol<1 ) nPrintCol = 1;
  4428. nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  4429. for(i=0; i<nPrintRow; i++){
  4430. for(j=i; j<nRow; j+=nPrintRow){
  4431. char *zSp = j<nPrintRow ? "" : " ";
  4432. utf8_printf(p->out, "%s%-*s", zSp, maxlen,
  4433. azResult[j] ? azResult[j]:"");
  4434. }
  4435. raw_printf(p->out, "\n");
  4436. }
  4437. }
  4438. for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
  4439. sqlite3_free(azResult);
  4440. }else
  4441. /* Begin redirecting output to the file "testcase-out.txt" */
  4442. if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
  4443. output_reset(p);
  4444. p->out = output_file_open("testcase-out.txt");
  4445. if( p->out==0 ){
  4446. utf8_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
  4447. }
  4448. if( nArg>=2 ){
  4449. sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
  4450. }else{
  4451. sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
  4452. }
  4453. }else
  4454. if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
  4455. static const struct {
  4456. const char *zCtrlName; /* Name of a test-control option */
  4457. int ctrlCode; /* Integer code for that option */
  4458. } aCtrl[] = {
  4459. { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
  4460. { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
  4461. { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
  4462. { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
  4463. { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
  4464. { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
  4465. { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
  4466. { "assert", SQLITE_TESTCTRL_ASSERT },
  4467. { "always", SQLITE_TESTCTRL_ALWAYS },
  4468. { "reserve", SQLITE_TESTCTRL_RESERVE },
  4469. { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
  4470. { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
  4471. { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
  4472. { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
  4473. { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
  4474. { "imposter", SQLITE_TESTCTRL_IMPOSTER },
  4475. };
  4476. int testctrl = -1;
  4477. int rc2 = 0;
  4478. int i, n2;
  4479. open_db(p, 0);
  4480. /* convert testctrl text option to value. allow any unique prefix
  4481. ** of the option name, or a numerical value. */
  4482. n2 = strlen30(azArg[1]);
  4483. for(i=0; i<ArraySize(aCtrl); i++){
  4484. if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
  4485. if( testctrl<0 ){
  4486. testctrl = aCtrl[i].ctrlCode;
  4487. }else{
  4488. utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
  4489. testctrl = -1;
  4490. break;
  4491. }
  4492. }
  4493. }
  4494. if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
  4495. if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
  4496. utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
  4497. }else{
  4498. switch(testctrl){
  4499. /* sqlite3_test_control(int, db, int) */
  4500. case SQLITE_TESTCTRL_OPTIMIZATIONS:
  4501. case SQLITE_TESTCTRL_RESERVE:
  4502. if( nArg==3 ){
  4503. int opt = (int)strtol(azArg[2], 0, 0);
  4504. rc2 = sqlite3_test_control(testctrl, p->db, opt);
  4505. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  4506. } else {
  4507. utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
  4508. azArg[1]);
  4509. }
  4510. break;
  4511. /* sqlite3_test_control(int) */
  4512. case SQLITE_TESTCTRL_PRNG_SAVE:
  4513. case SQLITE_TESTCTRL_PRNG_RESTORE:
  4514. case SQLITE_TESTCTRL_PRNG_RESET:
  4515. case SQLITE_TESTCTRL_BYTEORDER:
  4516. if( nArg==2 ){
  4517. rc2 = sqlite3_test_control(testctrl);
  4518. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  4519. } else {
  4520. utf8_printf(stderr,"Error: testctrl %s takes no options\n",
  4521. azArg[1]);
  4522. }
  4523. break;
  4524. /* sqlite3_test_control(int, uint) */
  4525. case SQLITE_TESTCTRL_PENDING_BYTE:
  4526. if( nArg==3 ){
  4527. unsigned int opt = (unsigned int)integerValue(azArg[2]);
  4528. rc2 = sqlite3_test_control(testctrl, opt);
  4529. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  4530. } else {
  4531. utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
  4532. " int option\n", azArg[1]);
  4533. }
  4534. break;
  4535. /* sqlite3_test_control(int, int) */
  4536. case SQLITE_TESTCTRL_ASSERT:
  4537. case SQLITE_TESTCTRL_ALWAYS:
  4538. case SQLITE_TESTCTRL_NEVER_CORRUPT:
  4539. if( nArg==3 ){
  4540. int opt = booleanValue(azArg[2]);
  4541. rc2 = sqlite3_test_control(testctrl, opt);
  4542. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  4543. } else {
  4544. utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
  4545. azArg[1]);
  4546. }
  4547. break;
  4548. /* sqlite3_test_control(int, char *) */
  4549. #ifdef SQLITE_N_KEYWORD
  4550. case SQLITE_TESTCTRL_ISKEYWORD:
  4551. if( nArg==3 ){
  4552. const char *opt = azArg[2];
  4553. rc2 = sqlite3_test_control(testctrl, opt);
  4554. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  4555. } else {
  4556. utf8_printf(stderr,
  4557. "Error: testctrl %s takes a single char * option\n",
  4558. azArg[1]);
  4559. }
  4560. break;
  4561. #endif
  4562. case SQLITE_TESTCTRL_IMPOSTER:
  4563. if( nArg==5 ){
  4564. rc2 = sqlite3_test_control(testctrl, p->db,
  4565. azArg[2],
  4566. integerValue(azArg[3]),
  4567. integerValue(azArg[4]));
  4568. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  4569. }else{
  4570. raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
  4571. }
  4572. break;
  4573. case SQLITE_TESTCTRL_BITVEC_TEST:
  4574. case SQLITE_TESTCTRL_FAULT_INSTALL:
  4575. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
  4576. case SQLITE_TESTCTRL_SCRATCHMALLOC:
  4577. default:
  4578. utf8_printf(stderr,
  4579. "Error: CLI support for testctrl %s not implemented\n",
  4580. azArg[1]);
  4581. break;
  4582. }
  4583. }
  4584. }else
  4585. if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
  4586. open_db(p, 0);
  4587. sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
  4588. }else
  4589. if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
  4590. if( nArg==2 ){
  4591. enableTimer = booleanValue(azArg[1]);
  4592. if( enableTimer && !HAS_TIMER ){
  4593. raw_printf(stderr, "Error: timer not available on this system.\n");
  4594. enableTimer = 0;
  4595. }
  4596. }else{
  4597. raw_printf(stderr, "Usage: .timer on|off\n");
  4598. rc = 1;
  4599. }
  4600. }else
  4601. if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
  4602. open_db(p, 0);
  4603. if( nArg!=2 ){
  4604. raw_printf(stderr, "Usage: .trace FILE|off\n");
  4605. rc = 1;
  4606. goto meta_command_exit;
  4607. }
  4608. output_file_close(p->traceOut);
  4609. p->traceOut = output_file_open(azArg[1]);
  4610. #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
  4611. if( p->traceOut==0 ){
  4612. sqlite3_trace_v2(p->db, 0, 0, 0);
  4613. }else{
  4614. sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
  4615. }
  4616. #endif
  4617. }else
  4618. #if SQLITE_USER_AUTHENTICATION
  4619. if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
  4620. if( nArg<2 ){
  4621. raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
  4622. rc = 1;
  4623. goto meta_command_exit;
  4624. }
  4625. open_db(p, 0);
  4626. if( strcmp(azArg[1],"login")==0 ){
  4627. if( nArg!=4 ){
  4628. raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
  4629. rc = 1;
  4630. goto meta_command_exit;
  4631. }
  4632. rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
  4633. (int)strlen(azArg[3]));
  4634. if( rc ){
  4635. utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
  4636. rc = 1;
  4637. }
  4638. }else if( strcmp(azArg[1],"add")==0 ){
  4639. if( nArg!=5 ){
  4640. raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
  4641. rc = 1;
  4642. goto meta_command_exit;
  4643. }
  4644. rc = sqlite3_user_add(p->db, azArg[2],
  4645. azArg[3], (int)strlen(azArg[3]),
  4646. booleanValue(azArg[4]));
  4647. if( rc ){
  4648. raw_printf(stderr, "User-Add failed: %d\n", rc);
  4649. rc = 1;
  4650. }
  4651. }else if( strcmp(azArg[1],"edit")==0 ){
  4652. if( nArg!=5 ){
  4653. raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
  4654. rc = 1;
  4655. goto meta_command_exit;
  4656. }
  4657. rc = sqlite3_user_change(p->db, azArg[2],
  4658. azArg[3], (int)strlen(azArg[3]),
  4659. booleanValue(azArg[4]));
  4660. if( rc ){
  4661. raw_printf(stderr, "User-Edit failed: %d\n", rc);
  4662. rc = 1;
  4663. }
  4664. }else if( strcmp(azArg[1],"delete")==0 ){
  4665. if( nArg!=3 ){
  4666. raw_printf(stderr, "Usage: .user delete USER\n");
  4667. rc = 1;
  4668. goto meta_command_exit;
  4669. }
  4670. rc = sqlite3_user_delete(p->db, azArg[2]);
  4671. if( rc ){
  4672. raw_printf(stderr, "User-Delete failed: %d\n", rc);
  4673. rc = 1;
  4674. }
  4675. }else{
  4676. raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
  4677. rc = 1;
  4678. goto meta_command_exit;
  4679. }
  4680. }else
  4681. #endif /* SQLITE_USER_AUTHENTICATION */
  4682. if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
  4683. utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
  4684. sqlite3_libversion(), sqlite3_sourceid());
  4685. }else
  4686. if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
  4687. const char *zDbName = nArg==2 ? azArg[1] : "main";
  4688. sqlite3_vfs *pVfs;
  4689. if( p->db ){
  4690. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
  4691. if( pVfs ){
  4692. utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
  4693. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  4694. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  4695. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  4696. }
  4697. }
  4698. }else
  4699. if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
  4700. sqlite3_vfs *pVfs;
  4701. sqlite3_vfs *pCurrent = 0;
  4702. if( p->db ){
  4703. sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
  4704. }
  4705. for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
  4706. utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
  4707. pVfs==pCurrent ? " <--- CURRENT" : "");
  4708. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  4709. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  4710. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  4711. if( pVfs->pNext ){
  4712. raw_printf(p->out, "-----------------------------------\n");
  4713. }
  4714. }
  4715. }else
  4716. if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
  4717. const char *zDbName = nArg==2 ? azArg[1] : "main";
  4718. char *zVfsName = 0;
  4719. if( p->db ){
  4720. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
  4721. if( zVfsName ){
  4722. utf8_printf(p->out, "%s\n", zVfsName);
  4723. sqlite3_free(zVfsName);
  4724. }
  4725. }
  4726. }else
  4727. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  4728. if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
  4729. sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
  4730. }else
  4731. #endif
  4732. if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
  4733. int j;
  4734. assert( nArg<=ArraySize(azArg) );
  4735. for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
  4736. p->colWidth[j-1] = (int)integerValue(azArg[j]);
  4737. }
  4738. }else
  4739. {
  4740. utf8_printf(stderr, "Error: unknown command or invalid arguments: "
  4741. " \"%s\". Enter \".help\" for help\n", azArg[0]);
  4742. rc = 1;
  4743. }
  4744. meta_command_exit:
  4745. if( p->outCount ){
  4746. p->outCount--;
  4747. if( p->outCount==0 ) output_reset(p);
  4748. }
  4749. return rc;
  4750. }
  4751. /*
  4752. ** Return TRUE if a semicolon occurs anywhere in the first N characters
  4753. ** of string z[].
  4754. */
  4755. static int line_contains_semicolon(const char *z, int N){
  4756. int i;
  4757. for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
  4758. return 0;
  4759. }
  4760. /*
  4761. ** Test to see if a line consists entirely of whitespace.
  4762. */
  4763. static int _all_whitespace(const char *z){
  4764. for(; *z; z++){
  4765. if( IsSpace(z[0]) ) continue;
  4766. if( *z=='/' && z[1]=='*' ){
  4767. z += 2;
  4768. while( *z && (*z!='*' || z[1]!='/') ){ z++; }
  4769. if( *z==0 ) return 0;
  4770. z++;
  4771. continue;
  4772. }
  4773. if( *z=='-' && z[1]=='-' ){
  4774. z += 2;
  4775. while( *z && *z!='\n' ){ z++; }
  4776. if( *z==0 ) return 1;
  4777. continue;
  4778. }
  4779. return 0;
  4780. }
  4781. return 1;
  4782. }
  4783. /*
  4784. ** Return TRUE if the line typed in is an SQL command terminator other
  4785. ** than a semi-colon. The SQL Server style "go" command is understood
  4786. ** as is the Oracle "/".
  4787. */
  4788. static int line_is_command_terminator(const char *zLine){
  4789. while( IsSpace(zLine[0]) ){ zLine++; };
  4790. if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
  4791. return 1; /* Oracle */
  4792. }
  4793. if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
  4794. && _all_whitespace(&zLine[2]) ){
  4795. return 1; /* SQL Server */
  4796. }
  4797. return 0;
  4798. }
  4799. /*
  4800. ** Return true if zSql is a complete SQL statement. Return false if it
  4801. ** ends in the middle of a string literal or C-style comment.
  4802. */
  4803. static int line_is_complete(char *zSql, int nSql){
  4804. int rc;
  4805. if( zSql==0 ) return 1;
  4806. zSql[nSql] = ';';
  4807. zSql[nSql+1] = 0;
  4808. rc = sqlite3_complete(zSql);
  4809. zSql[nSql] = 0;
  4810. return rc;
  4811. }
  4812. /*
  4813. ** Read input from *in and process it. If *in==0 then input
  4814. ** is interactive - the user is typing it it. Otherwise, input
  4815. ** is coming from a file or device. A prompt is issued and history
  4816. ** is saved only if input is interactive. An interrupt signal will
  4817. ** cause this routine to exit immediately, unless input is interactive.
  4818. **
  4819. ** Return the number of errors.
  4820. */
  4821. static int process_input(ShellState *p, FILE *in){
  4822. char *zLine = 0; /* A single input line */
  4823. char *zSql = 0; /* Accumulated SQL text */
  4824. int nLine; /* Length of current line */
  4825. int nSql = 0; /* Bytes of zSql[] used */
  4826. int nAlloc = 0; /* Allocated zSql[] space */
  4827. int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
  4828. char *zErrMsg; /* Error message returned */
  4829. int rc; /* Error code */
  4830. int errCnt = 0; /* Number of errors seen */
  4831. int lineno = 0; /* Current line number */
  4832. int startline = 0; /* Line number for start of current input */
  4833. while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
  4834. fflush(p->out);
  4835. zLine = one_input_line(in, zLine, nSql>0);
  4836. if( zLine==0 ){
  4837. /* End of input */
  4838. if( in==0 && stdin_is_interactive ) printf("\n");
  4839. break;
  4840. }
  4841. if( seenInterrupt ){
  4842. if( in!=0 ) break;
  4843. seenInterrupt = 0;
  4844. }
  4845. lineno++;
  4846. if( nSql==0 && _all_whitespace(zLine) ){
  4847. if( p->echoOn ) printf("%s\n", zLine);
  4848. continue;
  4849. }
  4850. if( zLine && zLine[0]=='.' && nSql==0 ){
  4851. if( p->echoOn ) printf("%s\n", zLine);
  4852. rc = do_meta_command(zLine, p);
  4853. if( rc==2 ){ /* exit requested */
  4854. break;
  4855. }else if( rc ){
  4856. errCnt++;
  4857. }
  4858. continue;
  4859. }
  4860. if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
  4861. memcpy(zLine,";",2);
  4862. }
  4863. nLine = strlen30(zLine);
  4864. if( nSql+nLine+2>=nAlloc ){
  4865. nAlloc = nSql+nLine+100;
  4866. zSql = realloc(zSql, nAlloc);
  4867. if( zSql==0 ){
  4868. raw_printf(stderr, "Error: out of memory\n");
  4869. exit(1);
  4870. }
  4871. }
  4872. nSqlPrior = nSql;
  4873. if( nSql==0 ){
  4874. int i;
  4875. for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
  4876. assert( nAlloc>0 && zSql!=0 );
  4877. memcpy(zSql, zLine+i, nLine+1-i);
  4878. startline = lineno;
  4879. nSql = nLine-i;
  4880. }else{
  4881. zSql[nSql++] = '\n';
  4882. memcpy(zSql+nSql, zLine, nLine+1);
  4883. nSql += nLine;
  4884. }
  4885. if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  4886. && sqlite3_complete(zSql) ){
  4887. p->cnt = 0;
  4888. open_db(p, 0);
  4889. if( p->backslashOn ) resolve_backslashes(zSql);
  4890. BEGIN_TIMER;
  4891. rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
  4892. END_TIMER;
  4893. if( rc || zErrMsg ){
  4894. char zPrefix[100];
  4895. if( in!=0 || !stdin_is_interactive ){
  4896. sqlite3_snprintf(sizeof(zPrefix), zPrefix,
  4897. "Error: near line %d:", startline);
  4898. }else{
  4899. sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
  4900. }
  4901. if( zErrMsg!=0 ){
  4902. utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
  4903. sqlite3_free(zErrMsg);
  4904. zErrMsg = 0;
  4905. }else{
  4906. utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
  4907. }
  4908. errCnt++;
  4909. }else if( p->countChanges ){
  4910. raw_printf(p->out, "changes: %3d total_changes: %d\n",
  4911. sqlite3_changes(p->db), sqlite3_total_changes(p->db));
  4912. }
  4913. nSql = 0;
  4914. if( p->outCount ){
  4915. output_reset(p);
  4916. p->outCount = 0;
  4917. }
  4918. }else if( nSql && _all_whitespace(zSql) ){
  4919. if( p->echoOn ) printf("%s\n", zSql);
  4920. nSql = 0;
  4921. }
  4922. }
  4923. if( nSql ){
  4924. if( !_all_whitespace(zSql) ){
  4925. utf8_printf(stderr, "Error: incomplete SQL: %s\n", zSql);
  4926. errCnt++;
  4927. }
  4928. }
  4929. free(zSql);
  4930. free(zLine);
  4931. return errCnt>0;
  4932. }
  4933. /*
  4934. ** Return a pathname which is the user's home directory. A
  4935. ** 0 return indicates an error of some kind.
  4936. */
  4937. static char *find_home_dir(int clearFlag){
  4938. static char *home_dir = NULL;
  4939. if( clearFlag ){
  4940. free(home_dir);
  4941. home_dir = 0;
  4942. return 0;
  4943. }
  4944. if( home_dir ) return home_dir;
  4945. #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
  4946. && !defined(__RTP__) && !defined(_WRS_KERNEL)
  4947. {
  4948. struct passwd *pwent;
  4949. uid_t uid = getuid();
  4950. if( (pwent=getpwuid(uid)) != NULL) {
  4951. home_dir = pwent->pw_dir;
  4952. }
  4953. }
  4954. #endif
  4955. #if defined(_WIN32_WCE)
  4956. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  4957. */
  4958. home_dir = "/";
  4959. #else
  4960. #if defined(_WIN32) || defined(WIN32)
  4961. if (!home_dir) {
  4962. home_dir = getenv("USERPROFILE");
  4963. }
  4964. #endif
  4965. if (!home_dir) {
  4966. home_dir = getenv("HOME");
  4967. }
  4968. #if defined(_WIN32) || defined(WIN32)
  4969. if (!home_dir) {
  4970. char *zDrive, *zPath;
  4971. int n;
  4972. zDrive = getenv("HOMEDRIVE");
  4973. zPath = getenv("HOMEPATH");
  4974. if( zDrive && zPath ){
  4975. n = strlen30(zDrive) + strlen30(zPath) + 1;
  4976. home_dir = malloc( n );
  4977. if( home_dir==0 ) return 0;
  4978. sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  4979. return home_dir;
  4980. }
  4981. home_dir = "c:\\";
  4982. }
  4983. #endif
  4984. #endif /* !_WIN32_WCE */
  4985. if( home_dir ){
  4986. int n = strlen30(home_dir) + 1;
  4987. char *z = malloc( n );
  4988. if( z ) memcpy(z, home_dir, n);
  4989. home_dir = z;
  4990. }
  4991. return home_dir;
  4992. }
  4993. /*
  4994. ** Read input from the file given by sqliterc_override. Or if that
  4995. ** parameter is NULL, take input from ~/.sqliterc
  4996. **
  4997. ** Returns the number of errors.
  4998. */
  4999. static void process_sqliterc(
  5000. ShellState *p, /* Configuration data */
  5001. const char *sqliterc_override /* Name of config file. NULL to use default */
  5002. ){
  5003. char *home_dir = NULL;
  5004. const char *sqliterc = sqliterc_override;
  5005. char *zBuf = 0;
  5006. FILE *in = NULL;
  5007. if (sqliterc == NULL) {
  5008. home_dir = find_home_dir(0);
  5009. if( home_dir==0 ){
  5010. raw_printf(stderr, "-- warning: cannot find home directory;"
  5011. " cannot read ~/.sqliterc\n");
  5012. return;
  5013. }
  5014. sqlite3_initialize();
  5015. zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
  5016. sqliterc = zBuf;
  5017. }
  5018. in = fopen(sqliterc,"rb");
  5019. if( in ){
  5020. if( stdin_is_interactive ){
  5021. utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
  5022. }
  5023. process_input(p,in);
  5024. fclose(in);
  5025. }
  5026. sqlite3_free(zBuf);
  5027. }
  5028. /*
  5029. ** Show available command line options
  5030. */
  5031. static const char zOptions[] =
  5032. " -ascii set output mode to 'ascii'\n"
  5033. " -bail stop after hitting an error\n"
  5034. " -batch force batch I/O\n"
  5035. " -column set output mode to 'column'\n"
  5036. " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
  5037. " -csv set output mode to 'csv'\n"
  5038. " -echo print commands before execution\n"
  5039. " -init FILENAME read/process named file\n"
  5040. " -[no]header turn headers on or off\n"
  5041. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  5042. " -heap SIZE Size of heap for memsys3 or memsys5\n"
  5043. #endif
  5044. " -help show this message\n"
  5045. " -html set output mode to HTML\n"
  5046. " -interactive force interactive I/O\n"
  5047. " -line set output mode to 'line'\n"
  5048. " -list set output mode to 'list'\n"
  5049. " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
  5050. " -mmap N default mmap size set to N\n"
  5051. #ifdef SQLITE_ENABLE_MULTIPLEX
  5052. " -multiplex enable the multiplexor VFS\n"
  5053. #endif
  5054. " -newline SEP set output row separator. Default: '\\n'\n"
  5055. " -nullvalue TEXT set text string for NULL values. Default ''\n"
  5056. " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
  5057. " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
  5058. " -separator SEP set output column separator. Default: '|'\n"
  5059. " -stats print memory stats before each finalize\n"
  5060. " -version show SQLite version\n"
  5061. " -vfs NAME use NAME as the default VFS\n"
  5062. #ifdef SQLITE_ENABLE_VFSTRACE
  5063. " -vfstrace enable tracing of all VFS calls\n"
  5064. #endif
  5065. ;
  5066. static void usage(int showDetail){
  5067. utf8_printf(stderr,
  5068. "Usage: %s [OPTIONS] FILENAME [SQL]\n"
  5069. "FILENAME is the name of an SQLite database. A new database is created\n"
  5070. "if the file does not previously exist.\n", Argv0);
  5071. if( showDetail ){
  5072. utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
  5073. }else{
  5074. raw_printf(stderr, "Use the -help option for additional information\n");
  5075. }
  5076. exit(1);
  5077. }
  5078. /*
  5079. ** Initialize the state information in data
  5080. */
  5081. static void main_init(ShellState *data) {
  5082. memset(data, 0, sizeof(*data));
  5083. data->normalMode = data->cMode = data->mode = MODE_List;
  5084. data->autoExplain = 1;
  5085. memcpy(data->colSeparator,SEP_Column, 2);
  5086. memcpy(data->rowSeparator,SEP_Row, 2);
  5087. data->showHeader = 0;
  5088. data->shellFlgs = SHFLG_Lookaside;
  5089. sqlite3_config(SQLITE_CONFIG_URI, 1);
  5090. sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
  5091. sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
  5092. sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  5093. sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
  5094. }
  5095. /*
  5096. ** Output text to the console in a font that attracts extra attention.
  5097. */
  5098. #ifdef _WIN32
  5099. static void printBold(const char *zText){
  5100. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  5101. CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
  5102. GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
  5103. SetConsoleTextAttribute(out,
  5104. FOREGROUND_RED|FOREGROUND_INTENSITY
  5105. );
  5106. printf("%s", zText);
  5107. SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
  5108. }
  5109. #else
  5110. static void printBold(const char *zText){
  5111. printf("\033[1m%s\033[0m", zText);
  5112. }
  5113. #endif
  5114. /*
  5115. ** Get the argument to an --option. Throw an error and die if no argument
  5116. ** is available.
  5117. */
  5118. static char *cmdline_option_value(int argc, char **argv, int i){
  5119. if( i==argc ){
  5120. utf8_printf(stderr, "%s: Error: missing argument to %s\n",
  5121. argv[0], argv[argc-1]);
  5122. exit(1);
  5123. }
  5124. return argv[i];
  5125. }
  5126. #ifndef SQLITE_SHELL_IS_UTF8
  5127. # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
  5128. # define SQLITE_SHELL_IS_UTF8 (0)
  5129. # else
  5130. # define SQLITE_SHELL_IS_UTF8 (1)
  5131. # endif
  5132. #endif
  5133. #if SQLITE_SHELL_IS_UTF8
  5134. int SQLITE_CDECL main(int argc, char **argv){
  5135. #else
  5136. int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
  5137. char **argv;
  5138. #endif
  5139. char *zErrMsg = 0;
  5140. ShellState data;
  5141. const char *zInitFile = 0;
  5142. int i;
  5143. int rc = 0;
  5144. int warnInmemoryDb = 0;
  5145. int readStdin = 1;
  5146. int nCmd = 0;
  5147. char **azCmd = 0;
  5148. setBinaryMode(stdin, 0);
  5149. setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
  5150. stdin_is_interactive = isatty(0);
  5151. stdout_is_console = isatty(1);
  5152. #if USE_SYSTEM_SQLITE+0!=1
  5153. if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
  5154. utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
  5155. sqlite3_sourceid(), SQLITE_SOURCE_ID);
  5156. exit(1);
  5157. }
  5158. #endif
  5159. main_init(&data);
  5160. #if !SQLITE_SHELL_IS_UTF8
  5161. sqlite3_initialize();
  5162. argv = sqlite3_malloc64(sizeof(argv[0])*argc);
  5163. if( argv==0 ){
  5164. raw_printf(stderr, "out of memory\n");
  5165. exit(1);
  5166. }
  5167. for(i=0; i<argc; i++){
  5168. argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
  5169. if( argv[i]==0 ){
  5170. raw_printf(stderr, "out of memory\n");
  5171. exit(1);
  5172. }
  5173. }
  5174. #endif
  5175. assert( argc>=1 && argv && argv[0] );
  5176. Argv0 = argv[0];
  5177. /* Make sure we have a valid signal handler early, before anything
  5178. ** else is done.
  5179. */
  5180. #ifdef SIGINT
  5181. signal(SIGINT, interrupt_handler);
  5182. #endif
  5183. #ifdef SQLITE_SHELL_DBNAME_PROC
  5184. {
  5185. /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
  5186. ** of a C-function that will provide the name of the database file. Use
  5187. ** this compile-time option to embed this shell program in larger
  5188. ** applications. */
  5189. extern void SQLITE_SHELL_DBNAME_PROC(const char**);
  5190. SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
  5191. warnInmemoryDb = 0;
  5192. }
  5193. #endif
  5194. /* Do an initial pass through the command-line argument to locate
  5195. ** the name of the database file, the name of the initialization file,
  5196. ** the size of the alternative malloc heap,
  5197. ** and the first command to execute.
  5198. */
  5199. for(i=1; i<argc; i++){
  5200. char *z;
  5201. z = argv[i];
  5202. if( z[0]!='-' ){
  5203. if( data.zDbFilename==0 ){
  5204. data.zDbFilename = z;
  5205. }else{
  5206. /* Excesss arguments are interpreted as SQL (or dot-commands) and
  5207. ** mean that nothing is read from stdin */
  5208. readStdin = 0;
  5209. nCmd++;
  5210. azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
  5211. if( azCmd==0 ){
  5212. raw_printf(stderr, "out of memory\n");
  5213. exit(1);
  5214. }
  5215. azCmd[nCmd-1] = z;
  5216. }
  5217. }
  5218. if( z[1]=='-' ) z++;
  5219. if( strcmp(z,"-separator")==0
  5220. || strcmp(z,"-nullvalue")==0
  5221. || strcmp(z,"-newline")==0
  5222. || strcmp(z,"-cmd")==0
  5223. ){
  5224. (void)cmdline_option_value(argc, argv, ++i);
  5225. }else if( strcmp(z,"-init")==0 ){
  5226. zInitFile = cmdline_option_value(argc, argv, ++i);
  5227. }else if( strcmp(z,"-batch")==0 ){
  5228. /* Need to check for batch mode here to so we can avoid printing
  5229. ** informational messages (like from process_sqliterc) before
  5230. ** we do the actual processing of arguments later in a second pass.
  5231. */
  5232. stdin_is_interactive = 0;
  5233. }else if( strcmp(z,"-heap")==0 ){
  5234. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  5235. const char *zSize;
  5236. sqlite3_int64 szHeap;
  5237. zSize = cmdline_option_value(argc, argv, ++i);
  5238. szHeap = integerValue(zSize);
  5239. if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
  5240. sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
  5241. #else
  5242. (void)cmdline_option_value(argc, argv, ++i);
  5243. #endif
  5244. }else if( strcmp(z,"-scratch")==0 ){
  5245. int n, sz;
  5246. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  5247. if( sz>400000 ) sz = 400000;
  5248. if( sz<2500 ) sz = 2500;
  5249. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  5250. if( n>10 ) n = 10;
  5251. if( n<1 ) n = 1;
  5252. sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
  5253. data.shellFlgs |= SHFLG_Scratch;
  5254. }else if( strcmp(z,"-pagecache")==0 ){
  5255. int n, sz;
  5256. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  5257. if( sz>70000 ) sz = 70000;
  5258. if( sz<0 ) sz = 0;
  5259. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  5260. sqlite3_config(SQLITE_CONFIG_PAGECACHE,
  5261. (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
  5262. data.shellFlgs |= SHFLG_Pagecache;
  5263. }else if( strcmp(z,"-lookaside")==0 ){
  5264. int n, sz;
  5265. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  5266. if( sz<0 ) sz = 0;
  5267. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  5268. if( n<0 ) n = 0;
  5269. sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
  5270. if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
  5271. #ifdef SQLITE_ENABLE_VFSTRACE
  5272. }else if( strcmp(z,"-vfstrace")==0 ){
  5273. extern int vfstrace_register(
  5274. const char *zTraceName,
  5275. const char *zOldVfsName,
  5276. int (*xOut)(const char*,void*),
  5277. void *pOutArg,
  5278. int makeDefault
  5279. );
  5280. vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
  5281. #endif
  5282. #ifdef SQLITE_ENABLE_MULTIPLEX
  5283. }else if( strcmp(z,"-multiplex")==0 ){
  5284. extern int sqlite3_multiple_initialize(const char*,int);
  5285. sqlite3_multiplex_initialize(0, 1);
  5286. #endif
  5287. }else if( strcmp(z,"-mmap")==0 ){
  5288. sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  5289. sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
  5290. }else if( strcmp(z,"-vfs")==0 ){
  5291. sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
  5292. if( pVfs ){
  5293. sqlite3_vfs_register(pVfs, 1);
  5294. }else{
  5295. utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
  5296. exit(1);
  5297. }
  5298. }
  5299. }
  5300. if( data.zDbFilename==0 ){
  5301. #ifndef SQLITE_OMIT_MEMORYDB
  5302. data.zDbFilename = ":memory:";
  5303. warnInmemoryDb = argc==1;
  5304. #else
  5305. utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
  5306. return 1;
  5307. #endif
  5308. }
  5309. data.out = stdout;
  5310. /* Go ahead and open the database file if it already exists. If the
  5311. ** file does not exist, delay opening it. This prevents empty database
  5312. ** files from being created if a user mistypes the database name argument
  5313. ** to the sqlite command-line tool.
  5314. */
  5315. if( access(data.zDbFilename, 0)==0 ){
  5316. open_db(&data, 0);
  5317. }
  5318. /* Process the initialization file if there is one. If no -init option
  5319. ** is given on the command line, look for a file named ~/.sqliterc and
  5320. ** try to process it.
  5321. */
  5322. process_sqliterc(&data,zInitFile);
  5323. /* Make a second pass through the command-line argument and set
  5324. ** options. This second pass is delayed until after the initialization
  5325. ** file is processed so that the command-line arguments will override
  5326. ** settings in the initialization file.
  5327. */
  5328. for(i=1; i<argc; i++){
  5329. char *z = argv[i];
  5330. if( z[0]!='-' ) continue;
  5331. if( z[1]=='-' ){ z++; }
  5332. if( strcmp(z,"-init")==0 ){
  5333. i++;
  5334. }else if( strcmp(z,"-html")==0 ){
  5335. data.mode = MODE_Html;
  5336. }else if( strcmp(z,"-list")==0 ){
  5337. data.mode = MODE_List;
  5338. }else if( strcmp(z,"-line")==0 ){
  5339. data.mode = MODE_Line;
  5340. }else if( strcmp(z,"-column")==0 ){
  5341. data.mode = MODE_Column;
  5342. }else if( strcmp(z,"-csv")==0 ){
  5343. data.mode = MODE_Csv;
  5344. memcpy(data.colSeparator,",",2);
  5345. }else if( strcmp(z,"-ascii")==0 ){
  5346. data.mode = MODE_Ascii;
  5347. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  5348. SEP_Unit);
  5349. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  5350. SEP_Record);
  5351. }else if( strcmp(z,"-separator")==0 ){
  5352. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  5353. "%s",cmdline_option_value(argc,argv,++i));
  5354. }else if( strcmp(z,"-newline")==0 ){
  5355. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  5356. "%s",cmdline_option_value(argc,argv,++i));
  5357. }else if( strcmp(z,"-nullvalue")==0 ){
  5358. sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
  5359. "%s",cmdline_option_value(argc,argv,++i));
  5360. }else if( strcmp(z,"-header")==0 ){
  5361. data.showHeader = 1;
  5362. }else if( strcmp(z,"-noheader")==0 ){
  5363. data.showHeader = 0;
  5364. }else if( strcmp(z,"-echo")==0 ){
  5365. data.echoOn = 1;
  5366. }else if( strcmp(z,"-eqp")==0 ){
  5367. data.autoEQP = 1;
  5368. }else if( strcmp(z,"-eqpfull")==0 ){
  5369. data.autoEQP = 2;
  5370. }else if( strcmp(z,"-stats")==0 ){
  5371. data.statsOn = 1;
  5372. }else if( strcmp(z,"-scanstats")==0 ){
  5373. data.scanstatsOn = 1;
  5374. }else if( strcmp(z,"-backslash")==0 ){
  5375. /* Undocumented command-line option: -backslash
  5376. ** Causes C-style backslash escapes to be evaluated in SQL statements
  5377. ** prior to sending the SQL into SQLite. Useful for injecting
  5378. ** crazy bytes in the middle of SQL statements for testing and debugging.
  5379. */
  5380. data.backslashOn = 1;
  5381. }else if( strcmp(z,"-bail")==0 ){
  5382. bail_on_error = 1;
  5383. }else if( strcmp(z,"-version")==0 ){
  5384. printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
  5385. return 0;
  5386. }else if( strcmp(z,"-interactive")==0 ){
  5387. stdin_is_interactive = 1;
  5388. }else if( strcmp(z,"-batch")==0 ){
  5389. stdin_is_interactive = 0;
  5390. }else if( strcmp(z,"-heap")==0 ){
  5391. i++;
  5392. }else if( strcmp(z,"-scratch")==0 ){
  5393. i+=2;
  5394. }else if( strcmp(z,"-pagecache")==0 ){
  5395. i+=2;
  5396. }else if( strcmp(z,"-lookaside")==0 ){
  5397. i+=2;
  5398. }else if( strcmp(z,"-mmap")==0 ){
  5399. i++;
  5400. }else if( strcmp(z,"-vfs")==0 ){
  5401. i++;
  5402. #ifdef SQLITE_ENABLE_VFSTRACE
  5403. }else if( strcmp(z,"-vfstrace")==0 ){
  5404. i++;
  5405. #endif
  5406. #ifdef SQLITE_ENABLE_MULTIPLEX
  5407. }else if( strcmp(z,"-multiplex")==0 ){
  5408. i++;
  5409. #endif
  5410. }else if( strcmp(z,"-help")==0 ){
  5411. usage(1);
  5412. }else if( strcmp(z,"-cmd")==0 ){
  5413. /* Run commands that follow -cmd first and separately from commands
  5414. ** that simply appear on the command-line. This seems goofy. It would
  5415. ** be better if all commands ran in the order that they appear. But
  5416. ** we retain the goofy behavior for historical compatibility. */
  5417. if( i==argc-1 ) break;
  5418. z = cmdline_option_value(argc,argv,++i);
  5419. if( z[0]=='.' ){
  5420. rc = do_meta_command(z, &data);
  5421. if( rc && bail_on_error ) return rc==2 ? 0 : rc;
  5422. }else{
  5423. open_db(&data, 0);
  5424. rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
  5425. if( zErrMsg!=0 ){
  5426. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  5427. if( bail_on_error ) return rc!=0 ? rc : 1;
  5428. }else if( rc!=0 ){
  5429. utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
  5430. if( bail_on_error ) return rc;
  5431. }
  5432. }
  5433. }else{
  5434. utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
  5435. raw_printf(stderr,"Use -help for a list of options.\n");
  5436. return 1;
  5437. }
  5438. data.cMode = data.mode;
  5439. }
  5440. if( !readStdin ){
  5441. /* Run all arguments that do not begin with '-' as if they were separate
  5442. ** command-line inputs, except for the argToSkip argument which contains
  5443. ** the database filename.
  5444. */
  5445. for(i=0; i<nCmd; i++){
  5446. if( azCmd[i][0]=='.' ){
  5447. rc = do_meta_command(azCmd[i], &data);
  5448. if( rc ) return rc==2 ? 0 : rc;
  5449. }else{
  5450. open_db(&data, 0);
  5451. rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
  5452. if( zErrMsg!=0 ){
  5453. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  5454. return rc!=0 ? rc : 1;
  5455. }else if( rc!=0 ){
  5456. utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
  5457. return rc;
  5458. }
  5459. }
  5460. }
  5461. free(azCmd);
  5462. }else{
  5463. /* Run commands received from standard input
  5464. */
  5465. if( stdin_is_interactive ){
  5466. char *zHome;
  5467. char *zHistory = 0;
  5468. int nHistory;
  5469. printf(
  5470. "SQLite version %s %.19s\n" /*extra-version-info*/
  5471. "Enter \".help\" for usage hints.\n",
  5472. sqlite3_libversion(), sqlite3_sourceid()
  5473. );
  5474. if( warnInmemoryDb ){
  5475. printf("Connected to a ");
  5476. printBold("transient in-memory database");
  5477. printf(".\nUse \".open FILENAME\" to reopen on a "
  5478. "persistent database.\n");
  5479. }
  5480. zHome = find_home_dir(0);
  5481. if( zHome ){
  5482. nHistory = strlen30(zHome) + 20;
  5483. if( (zHistory = malloc(nHistory))!=0 ){
  5484. sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  5485. }
  5486. }
  5487. if( zHistory ){ shell_read_history(zHistory); }
  5488. rc = process_input(&data, 0);
  5489. if( zHistory ){
  5490. shell_stifle_history(100);
  5491. shell_write_history(zHistory);
  5492. free(zHistory);
  5493. }
  5494. }else{
  5495. rc = process_input(&data, stdin);
  5496. }
  5497. }
  5498. set_table_name(&data, 0);
  5499. if( data.db ){
  5500. session_close_all(&data);
  5501. sqlite3_close(data.db);
  5502. }
  5503. sqlite3_free(data.zFreeOnClose);
  5504. find_home_dir(1);
  5505. #if !SQLITE_SHELL_IS_UTF8
  5506. for(i=0; i<argc; i++) sqlite3_free(argv[i]);
  5507. sqlite3_free(argv);
  5508. #endif
  5509. return rc;
  5510. }