shell.c 259 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382
  1. /* DO NOT EDIT!
  2. ** This file is automatically generated by the script in the canonical
  3. ** SQLite source tree at tool/mkshellc.tcl. That script combines source
  4. ** code from various constituent source files of SQLite into this single
  5. ** "shell.c" file used to implement the SQLite command-line shell.
  6. **
  7. ** Most of the code found below comes from the "src/shell.c.in" file in
  8. ** the canonical SQLite source tree. That main file contains "INCLUDE"
  9. ** lines that specify other files in the canonical source tree that are
  10. ** inserted to getnerate this complete program source file.
  11. **
  12. ** The code from multiple files is combined into this single "shell.c"
  13. ** source file to help make the command-line program easier to compile.
  14. **
  15. ** To modify this program, get a copy of the canonical SQLite source tree,
  16. ** edit the src/shell.c.in" and/or some of the other files that are included
  17. ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
  18. */
  19. /*
  20. ** 2001 September 15
  21. **
  22. ** The author disclaims copyright to this source code. In place of
  23. ** a legal notice, here is a blessing:
  24. **
  25. ** May you do good and not evil.
  26. ** May you find forgiveness for yourself and forgive others.
  27. ** May you share freely, never taking more than you give.
  28. **
  29. *************************************************************************
  30. ** This file contains code to implement the "sqlite" command line
  31. ** utility for accessing SQLite databases.
  32. */
  33. #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
  34. /* This needs to come before any includes for MSVC compiler */
  35. #define _CRT_SECURE_NO_WARNINGS
  36. #endif
  37. /*
  38. ** Warning pragmas copied from msvc.h in the core.
  39. */
  40. #if defined(_MSC_VER)
  41. #pragma warning(disable : 4054)
  42. #pragma warning(disable : 4055)
  43. #pragma warning(disable : 4100)
  44. #pragma warning(disable : 4127)
  45. #pragma warning(disable : 4130)
  46. #pragma warning(disable : 4152)
  47. #pragma warning(disable : 4189)
  48. #pragma warning(disable : 4206)
  49. #pragma warning(disable : 4210)
  50. #pragma warning(disable : 4232)
  51. #pragma warning(disable : 4244)
  52. #pragma warning(disable : 4305)
  53. #pragma warning(disable : 4306)
  54. #pragma warning(disable : 4702)
  55. #pragma warning(disable : 4706)
  56. #endif /* defined(_MSC_VER) */
  57. /*
  58. ** No support for loadable extensions in VxWorks.
  59. */
  60. #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
  61. # define SQLITE_OMIT_LOAD_EXTENSION 1
  62. #endif
  63. /*
  64. ** Enable large-file support for fopen() and friends on unix.
  65. */
  66. #ifndef SQLITE_DISABLE_LFS
  67. # define _LARGE_FILE 1
  68. # ifndef _FILE_OFFSET_BITS
  69. # define _FILE_OFFSET_BITS 64
  70. # endif
  71. # define _LARGEFILE_SOURCE 1
  72. #endif
  73. #include <stdlib.h>
  74. #include <string.h>
  75. #include <stdio.h>
  76. #include <assert.h>
  77. #include "sqlite3.h"
  78. #if SQLITE_USER_AUTHENTICATION
  79. # include "sqlite3userauth.h"
  80. #endif
  81. #include <ctype.h>
  82. #include <stdarg.h>
  83. #if !defined(_WIN32) && !defined(WIN32)
  84. # include <signal.h>
  85. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  86. # include <pwd.h>
  87. # endif
  88. # include <unistd.h>
  89. # include <sys/types.h>
  90. #endif
  91. #if HAVE_READLINE
  92. # include <readline/readline.h>
  93. # include <readline/history.h>
  94. #endif
  95. #if HAVE_EDITLINE
  96. # include <editline/readline.h>
  97. #endif
  98. #if HAVE_EDITLINE || HAVE_READLINE
  99. # define shell_add_history(X) add_history(X)
  100. # define shell_read_history(X) read_history(X)
  101. # define shell_write_history(X) write_history(X)
  102. # define shell_stifle_history(X) stifle_history(X)
  103. # define shell_readline(X) readline(X)
  104. #elif HAVE_LINENOISE
  105. # include "linenoise.h"
  106. # define shell_add_history(X) linenoiseHistoryAdd(X)
  107. # define shell_read_history(X) linenoiseHistoryLoad(X)
  108. # define shell_write_history(X) linenoiseHistorySave(X)
  109. # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
  110. # define shell_readline(X) linenoise(X)
  111. #else
  112. # define shell_read_history(X)
  113. # define shell_write_history(X)
  114. # define shell_stifle_history(X)
  115. # define SHELL_USE_LOCAL_GETLINE 1
  116. #endif
  117. #if defined(_WIN32) || defined(WIN32)
  118. # include <io.h>
  119. # include <fcntl.h>
  120. # define isatty(h) _isatty(h)
  121. # ifndef access
  122. # define access(f,m) _access((f),(m))
  123. # endif
  124. # undef popen
  125. # define popen _popen
  126. # undef pclose
  127. # define pclose _pclose
  128. #else
  129. /* Make sure isatty() has a prototype. */
  130. extern int isatty(int);
  131. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  132. /* popen and pclose are not C89 functions and so are
  133. ** sometimes omitted from the <stdio.h> header */
  134. extern FILE *popen(const char*,const char*);
  135. extern int pclose(FILE*);
  136. # else
  137. # define SQLITE_OMIT_POPEN 1
  138. # endif
  139. #endif
  140. #if defined(_WIN32_WCE)
  141. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
  142. * thus we always assume that we have a console. That can be
  143. * overridden with the -batch command line option.
  144. */
  145. #define isatty(x) 1
  146. #endif
  147. /* ctype macros that work with signed characters */
  148. #define IsSpace(X) isspace((unsigned char)X)
  149. #define IsDigit(X) isdigit((unsigned char)X)
  150. #define ToLower(X) (char)tolower((unsigned char)X)
  151. #if defined(_WIN32) || defined(WIN32)
  152. #include <windows.h>
  153. /* string conversion routines only needed on Win32 */
  154. extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
  155. extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
  156. extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
  157. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
  158. #endif
  159. /* On Windows, we normally run with output mode of TEXT so that \n characters
  160. ** are automatically translated into \r\n. However, this behavior needs
  161. ** to be disabled in some cases (ex: when generating CSV output and when
  162. ** rendering quoted strings that contain \n characters). The following
  163. ** routines take care of that.
  164. */
  165. #if defined(_WIN32) || defined(WIN32)
  166. static void setBinaryMode(FILE *file, int isOutput){
  167. if( isOutput ) fflush(file);
  168. _setmode(_fileno(file), _O_BINARY);
  169. }
  170. static void setTextMode(FILE *file, int isOutput){
  171. if( isOutput ) fflush(file);
  172. _setmode(_fileno(file), _O_TEXT);
  173. }
  174. #else
  175. # define setBinaryMode(X,Y)
  176. # define setTextMode(X,Y)
  177. #endif
  178. /* True if the timer is enabled */
  179. static int enableTimer = 0;
  180. /* Return the current wall-clock time */
  181. static sqlite3_int64 timeOfDay(void){
  182. static sqlite3_vfs *clockVfs = 0;
  183. sqlite3_int64 t;
  184. if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
  185. if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
  186. clockVfs->xCurrentTimeInt64(clockVfs, &t);
  187. }else{
  188. double r;
  189. clockVfs->xCurrentTime(clockVfs, &r);
  190. t = (sqlite3_int64)(r*86400000.0);
  191. }
  192. return t;
  193. }
  194. #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
  195. #include <sys/time.h>
  196. #include <sys/resource.h>
  197. /* VxWorks does not support getrusage() as far as we can determine */
  198. #if defined(_WRS_KERNEL) || defined(__RTP__)
  199. struct rusage {
  200. struct timeval ru_utime; /* user CPU time used */
  201. struct timeval ru_stime; /* system CPU time used */
  202. };
  203. #define getrusage(A,B) memset(B,0,sizeof(*B))
  204. #endif
  205. /* Saved resource information for the beginning of an operation */
  206. static struct rusage sBegin; /* CPU time at start */
  207. static sqlite3_int64 iBegin; /* Wall-clock time at start */
  208. /*
  209. ** Begin timing an operation
  210. */
  211. static void beginTimer(void){
  212. if( enableTimer ){
  213. getrusage(RUSAGE_SELF, &sBegin);
  214. iBegin = timeOfDay();
  215. }
  216. }
  217. /* Return the difference of two time_structs in seconds */
  218. static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  219. return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
  220. (double)(pEnd->tv_sec - pStart->tv_sec);
  221. }
  222. /*
  223. ** Print the timing results.
  224. */
  225. static void endTimer(void){
  226. if( enableTimer ){
  227. sqlite3_int64 iEnd = timeOfDay();
  228. struct rusage sEnd;
  229. getrusage(RUSAGE_SELF, &sEnd);
  230. printf("Run Time: real %.3f user %f sys %f\n",
  231. (iEnd - iBegin)*0.001,
  232. timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
  233. timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  234. }
  235. }
  236. #define BEGIN_TIMER beginTimer()
  237. #define END_TIMER endTimer()
  238. #define HAS_TIMER 1
  239. #elif (defined(_WIN32) || defined(WIN32))
  240. /* Saved resource information for the beginning of an operation */
  241. static HANDLE hProcess;
  242. static FILETIME ftKernelBegin;
  243. static FILETIME ftUserBegin;
  244. static sqlite3_int64 ftWallBegin;
  245. typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
  246. LPFILETIME, LPFILETIME);
  247. static GETPROCTIMES getProcessTimesAddr = NULL;
  248. /*
  249. ** Check to see if we have timer support. Return 1 if necessary
  250. ** support found (or found previously).
  251. */
  252. static int hasTimer(void){
  253. if( getProcessTimesAddr ){
  254. return 1;
  255. } else {
  256. /* GetProcessTimes() isn't supported in WIN95 and some other Windows
  257. ** versions. See if the version we are running on has it, and if it
  258. ** does, save off a pointer to it and the current process handle.
  259. */
  260. hProcess = GetCurrentProcess();
  261. if( hProcess ){
  262. HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
  263. if( NULL != hinstLib ){
  264. getProcessTimesAddr =
  265. (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
  266. if( NULL != getProcessTimesAddr ){
  267. return 1;
  268. }
  269. FreeLibrary(hinstLib);
  270. }
  271. }
  272. }
  273. return 0;
  274. }
  275. /*
  276. ** Begin timing an operation
  277. */
  278. static void beginTimer(void){
  279. if( enableTimer && getProcessTimesAddr ){
  280. FILETIME ftCreation, ftExit;
  281. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
  282. &ftKernelBegin,&ftUserBegin);
  283. ftWallBegin = timeOfDay();
  284. }
  285. }
  286. /* Return the difference of two FILETIME structs in seconds */
  287. static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
  288. sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
  289. sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
  290. return (double) ((i64End - i64Start) / 10000000.0);
  291. }
  292. /*
  293. ** Print the timing results.
  294. */
  295. static void endTimer(void){
  296. if( enableTimer && getProcessTimesAddr){
  297. FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
  298. sqlite3_int64 ftWallEnd = timeOfDay();
  299. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
  300. printf("Run Time: real %.3f user %f sys %f\n",
  301. (ftWallEnd - ftWallBegin)*0.001,
  302. timeDiff(&ftUserBegin, &ftUserEnd),
  303. timeDiff(&ftKernelBegin, &ftKernelEnd));
  304. }
  305. }
  306. #define BEGIN_TIMER beginTimer()
  307. #define END_TIMER endTimer()
  308. #define HAS_TIMER hasTimer()
  309. #else
  310. #define BEGIN_TIMER
  311. #define END_TIMER
  312. #define HAS_TIMER 0
  313. #endif
  314. /*
  315. ** Used to prevent warnings about unused parameters
  316. */
  317. #define UNUSED_PARAMETER(x) (void)(x)
  318. /*
  319. ** If the following flag is set, then command execution stops
  320. ** at an error if we are not interactive.
  321. */
  322. static int bail_on_error = 0;
  323. /*
  324. ** Threat stdin as an interactive input if the following variable
  325. ** is true. Otherwise, assume stdin is connected to a file or pipe.
  326. */
  327. static int stdin_is_interactive = 1;
  328. /*
  329. ** On Windows systems we have to know if standard output is a console
  330. ** in order to translate UTF-8 into MBCS. The following variable is
  331. ** true if translation is required.
  332. */
  333. static int stdout_is_console = 1;
  334. /*
  335. ** The following is the open SQLite database. We make a pointer
  336. ** to this database a static variable so that it can be accessed
  337. ** by the SIGINT handler to interrupt database processing.
  338. */
  339. static sqlite3 *globalDb = 0;
  340. /*
  341. ** True if an interrupt (Control-C) has been received.
  342. */
  343. static volatile int seenInterrupt = 0;
  344. /*
  345. ** This is the name of our program. It is set in main(), used
  346. ** in a number of other places, mostly for error messages.
  347. */
  348. static char *Argv0;
  349. /*
  350. ** Prompt strings. Initialized in main. Settable with
  351. ** .prompt main continue
  352. */
  353. static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
  354. static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
  355. /*
  356. ** Render output like fprintf(). Except, if the output is going to the
  357. ** console and if this is running on a Windows machine, translate the
  358. ** output from UTF-8 into MBCS.
  359. */
  360. #if defined(_WIN32) || defined(WIN32)
  361. void utf8_printf(FILE *out, const char *zFormat, ...){
  362. va_list ap;
  363. va_start(ap, zFormat);
  364. if( stdout_is_console && (out==stdout || out==stderr) ){
  365. char *z1 = sqlite3_vmprintf(zFormat, ap);
  366. char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
  367. sqlite3_free(z1);
  368. fputs(z2, out);
  369. sqlite3_free(z2);
  370. }else{
  371. vfprintf(out, zFormat, ap);
  372. }
  373. va_end(ap);
  374. }
  375. #elif !defined(utf8_printf)
  376. # define utf8_printf fprintf
  377. #endif
  378. /*
  379. ** Render output like fprintf(). This should not be used on anything that
  380. ** includes string formatting (e.g. "%s").
  381. */
  382. #if !defined(raw_printf)
  383. # define raw_printf fprintf
  384. #endif
  385. /*
  386. ** Write I/O traces to the following stream.
  387. */
  388. #ifdef SQLITE_ENABLE_IOTRACE
  389. static FILE *iotrace = 0;
  390. #endif
  391. /*
  392. ** This routine works like printf in that its first argument is a
  393. ** format string and subsequent arguments are values to be substituted
  394. ** in place of % fields. The result of formatting this string
  395. ** is written to iotrace.
  396. */
  397. #ifdef SQLITE_ENABLE_IOTRACE
  398. static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
  399. va_list ap;
  400. char *z;
  401. if( iotrace==0 ) return;
  402. va_start(ap, zFormat);
  403. z = sqlite3_vmprintf(zFormat, ap);
  404. va_end(ap);
  405. utf8_printf(iotrace, "%s", z);
  406. sqlite3_free(z);
  407. }
  408. #endif
  409. /*
  410. ** Output string zUtf to stream pOut as w characters. If w is negative,
  411. ** then right-justify the text. W is the width in UTF-8 characters, not
  412. ** in bytes. This is different from the %*.*s specification in printf
  413. ** since with %*.*s the width is measured in bytes, not characters.
  414. */
  415. static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
  416. int i;
  417. int n;
  418. int aw = w<0 ? -w : w;
  419. char zBuf[1000];
  420. if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
  421. for(i=n=0; zUtf[i]; i++){
  422. if( (zUtf[i]&0xc0)!=0x80 ){
  423. n++;
  424. if( n==aw ){
  425. do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
  426. break;
  427. }
  428. }
  429. }
  430. if( n>=aw ){
  431. utf8_printf(pOut, "%.*s", i, zUtf);
  432. }else if( w<0 ){
  433. utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
  434. }else{
  435. utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
  436. }
  437. }
  438. /*
  439. ** Determines if a string is a number of not.
  440. */
  441. static int isNumber(const char *z, int *realnum){
  442. if( *z=='-' || *z=='+' ) z++;
  443. if( !IsDigit(*z) ){
  444. return 0;
  445. }
  446. z++;
  447. if( realnum ) *realnum = 0;
  448. while( IsDigit(*z) ){ z++; }
  449. if( *z=='.' ){
  450. z++;
  451. if( !IsDigit(*z) ) return 0;
  452. while( IsDigit(*z) ){ z++; }
  453. if( realnum ) *realnum = 1;
  454. }
  455. if( *z=='e' || *z=='E' ){
  456. z++;
  457. if( *z=='+' || *z=='-' ) z++;
  458. if( !IsDigit(*z) ) return 0;
  459. while( IsDigit(*z) ){ z++; }
  460. if( realnum ) *realnum = 1;
  461. }
  462. return *z==0;
  463. }
  464. /*
  465. ** Compute a string length that is limited to what can be stored in
  466. ** lower 30 bits of a 32-bit signed integer.
  467. */
  468. static int strlen30(const char *z){
  469. const char *z2 = z;
  470. while( *z2 ){ z2++; }
  471. return 0x3fffffff & (int)(z2 - z);
  472. }
  473. /*
  474. ** Return the length of a string in characters. Multibyte UTF8 characters
  475. ** count as a single character.
  476. */
  477. static int strlenChar(const char *z){
  478. int n = 0;
  479. while( *z ){
  480. if( (0xc0&*(z++))!=0x80 ) n++;
  481. }
  482. return n;
  483. }
  484. /*
  485. ** This routine reads a line of text from FILE in, stores
  486. ** the text in memory obtained from malloc() and returns a pointer
  487. ** to the text. NULL is returned at end of file, or if malloc()
  488. ** fails.
  489. **
  490. ** If zLine is not NULL then it is a malloced buffer returned from
  491. ** a previous call to this routine that may be reused.
  492. */
  493. static char *local_getline(char *zLine, FILE *in){
  494. int nLine = zLine==0 ? 0 : 100;
  495. int n = 0;
  496. while( 1 ){
  497. if( n+100>nLine ){
  498. nLine = nLine*2 + 100;
  499. zLine = realloc(zLine, nLine);
  500. if( zLine==0 ) return 0;
  501. }
  502. if( fgets(&zLine[n], nLine - n, in)==0 ){
  503. if( n==0 ){
  504. free(zLine);
  505. return 0;
  506. }
  507. zLine[n] = 0;
  508. break;
  509. }
  510. while( zLine[n] ) n++;
  511. if( n>0 && zLine[n-1]=='\n' ){
  512. n--;
  513. if( n>0 && zLine[n-1]=='\r' ) n--;
  514. zLine[n] = 0;
  515. break;
  516. }
  517. }
  518. #if defined(_WIN32) || defined(WIN32)
  519. /* For interactive input on Windows systems, translate the
  520. ** multi-byte characterset characters into UTF-8. */
  521. if( stdin_is_interactive && in==stdin ){
  522. char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
  523. if( zTrans ){
  524. int nTrans = strlen30(zTrans)+1;
  525. if( nTrans>nLine ){
  526. zLine = realloc(zLine, nTrans);
  527. if( zLine==0 ){
  528. sqlite3_free(zTrans);
  529. return 0;
  530. }
  531. }
  532. memcpy(zLine, zTrans, nTrans);
  533. sqlite3_free(zTrans);
  534. }
  535. }
  536. #endif /* defined(_WIN32) || defined(WIN32) */
  537. return zLine;
  538. }
  539. /*
  540. ** Retrieve a single line of input text.
  541. **
  542. ** If in==0 then read from standard input and prompt before each line.
  543. ** If isContinuation is true, then a continuation prompt is appropriate.
  544. ** If isContinuation is zero, then the main prompt should be used.
  545. **
  546. ** If zPrior is not NULL then it is a buffer from a prior call to this
  547. ** routine that can be reused.
  548. **
  549. ** The result is stored in space obtained from malloc() and must either
  550. ** be freed by the caller or else passed back into this routine via the
  551. ** zPrior argument for reuse.
  552. */
  553. static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
  554. char *zPrompt;
  555. char *zResult;
  556. if( in!=0 ){
  557. zResult = local_getline(zPrior, in);
  558. }else{
  559. zPrompt = isContinuation ? continuePrompt : mainPrompt;
  560. #if SHELL_USE_LOCAL_GETLINE
  561. printf("%s", zPrompt);
  562. fflush(stdout);
  563. zResult = local_getline(zPrior, stdin);
  564. #else
  565. free(zPrior);
  566. zResult = shell_readline(zPrompt);
  567. if( zResult && *zResult ) shell_add_history(zResult);
  568. #endif
  569. }
  570. return zResult;
  571. }
  572. /*
  573. ** A variable length string to which one can append text.
  574. */
  575. typedef struct ShellText ShellText;
  576. struct ShellText {
  577. char *z;
  578. int n;
  579. int nAlloc;
  580. };
  581. /*
  582. ** Initialize and destroy a ShellText object
  583. */
  584. static void initText(ShellText *p){
  585. memset(p, 0, sizeof(*p));
  586. }
  587. static void freeText(ShellText *p){
  588. free(p->z);
  589. initText(p);
  590. }
  591. /* zIn is either a pointer to a NULL-terminated string in memory obtained
  592. ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  593. ** added to zIn, and the result returned in memory obtained from malloc().
  594. ** zIn, if it was not NULL, is freed.
  595. **
  596. ** If the third argument, quote, is not '\0', then it is used as a
  597. ** quote character for zAppend.
  598. */
  599. static void appendText(ShellText *p, char const *zAppend, char quote){
  600. int len;
  601. int i;
  602. int nAppend = strlen30(zAppend);
  603. len = nAppend+p->n+1;
  604. if( quote ){
  605. len += 2;
  606. for(i=0; i<nAppend; i++){
  607. if( zAppend[i]==quote ) len++;
  608. }
  609. }
  610. if( p->n+len>=p->nAlloc ){
  611. p->nAlloc = p->nAlloc*2 + len + 20;
  612. p->z = realloc(p->z, p->nAlloc);
  613. if( p->z==0 ){
  614. memset(p, 0, sizeof(*p));
  615. return;
  616. }
  617. }
  618. if( quote ){
  619. char *zCsr = p->z+p->n;
  620. *zCsr++ = quote;
  621. for(i=0; i<nAppend; i++){
  622. *zCsr++ = zAppend[i];
  623. if( zAppend[i]==quote ) *zCsr++ = quote;
  624. }
  625. *zCsr++ = quote;
  626. p->n = (int)(zCsr - p->z);
  627. *zCsr = '\0';
  628. }else{
  629. memcpy(p->z+p->n, zAppend, nAppend);
  630. p->n += nAppend;
  631. p->z[p->n] = '\0';
  632. }
  633. }
  634. /*
  635. ** Attempt to determine if identifier zName needs to be quoted, either
  636. ** because it contains non-alphanumeric characters, or because it is an
  637. ** SQLite keyword. Be conservative in this estimate: When in doubt assume
  638. ** that quoting is required.
  639. **
  640. ** Return '"' if quoting is required. Return 0 if no quoting is required.
  641. */
  642. static char quoteChar(const char *zName){
  643. /* All SQLite keywords, in alphabetical order */
  644. static const char *azKeywords[] = {
  645. "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
  646. "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
  647. "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
  648. "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
  649. "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
  650. "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
  651. "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
  652. "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
  653. "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
  654. "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
  655. "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
  656. "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
  657. "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
  658. "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
  659. "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
  660. "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
  661. "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
  662. "WITH", "WITHOUT",
  663. };
  664. int i, lwr, upr, mid, c;
  665. if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
  666. for(i=0; zName[i]; i++){
  667. if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
  668. }
  669. lwr = 0;
  670. upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
  671. while( lwr<=upr ){
  672. mid = (lwr+upr)/2;
  673. c = sqlite3_stricmp(azKeywords[mid], zName);
  674. if( c==0 ) return '"';
  675. if( c<0 ){
  676. lwr = mid+1;
  677. }else{
  678. upr = mid-1;
  679. }
  680. }
  681. return 0;
  682. }
  683. /*
  684. ** SQL function: shell_add_schema(S,X)
  685. **
  686. ** Add the schema name X to the CREATE statement in S and return the result.
  687. ** Examples:
  688. **
  689. ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
  690. **
  691. ** Also works on
  692. **
  693. ** CREATE INDEX
  694. ** CREATE UNIQUE INDEX
  695. ** CREATE VIEW
  696. ** CREATE TRIGGER
  697. ** CREATE VIRTUAL TABLE
  698. **
  699. ** This UDF is used by the .schema command to insert the schema name of
  700. ** attached databases into the middle of the sqlite_master.sql field.
  701. */
  702. static void shellAddSchemaName(
  703. sqlite3_context *pCtx,
  704. int nVal,
  705. sqlite3_value **apVal
  706. ){
  707. static const char *aPrefix[] = {
  708. "TABLE",
  709. "INDEX",
  710. "UNIQUE INDEX",
  711. "VIEW",
  712. "TRIGGER",
  713. "VIRTUAL TABLE"
  714. };
  715. int i = 0;
  716. const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
  717. const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
  718. assert( nVal==2 );
  719. if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
  720. for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
  721. int n = strlen30(aPrefix[i]);
  722. if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
  723. char cQuote = quoteChar(zSchema);
  724. char *z;
  725. if( cQuote ){
  726. z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
  727. }else{
  728. z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
  729. }
  730. sqlite3_result_text(pCtx, z, -1, sqlite3_free);
  731. return;
  732. }
  733. }
  734. }
  735. sqlite3_result_value(pCtx, apVal[0]);
  736. }
  737. /*
  738. ** The source code for several run-time loadable extensions is inserted
  739. ** below by the ../tool/mkshellc.tcl script. Before processing that included
  740. ** code, we need to override some macros to make the included program code
  741. ** work here in the middle of this regular program.
  742. */
  743. #define SQLITE_EXTENSION_INIT1
  744. #define SQLITE_EXTENSION_INIT2(X) (void)(X)
  745. /************************* Begin ../ext/misc/shathree.c ******************/
  746. /*
  747. ** 2017-03-08
  748. **
  749. ** The author disclaims copyright to this source code. In place of
  750. ** a legal notice, here is a blessing:
  751. **
  752. ** May you do good and not evil.
  753. ** May you find forgiveness for yourself and forgive others.
  754. ** May you share freely, never taking more than you give.
  755. **
  756. ******************************************************************************
  757. **
  758. ** This SQLite extension implements a functions that compute SHA1 hashes.
  759. ** Two SQL functions are implemented:
  760. **
  761. ** sha3(X,SIZE)
  762. ** sha3_query(Y,SIZE)
  763. **
  764. ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
  765. ** X is NULL.
  766. **
  767. ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
  768. ** and returns a hash of their results.
  769. **
  770. ** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm
  771. ** is used. If SIZE is included it must be one of the integers 224, 256,
  772. ** 384, or 512, to determine SHA3 hash variant that is computed.
  773. */
  774. SQLITE_EXTENSION_INIT1
  775. #include <assert.h>
  776. #include <string.h>
  777. #include <stdarg.h>
  778. typedef sqlite3_uint64 u64;
  779. /******************************************************************************
  780. ** The Hash Engine
  781. */
  782. /*
  783. ** Macros to determine whether the machine is big or little endian,
  784. ** and whether or not that determination is run-time or compile-time.
  785. **
  786. ** For best performance, an attempt is made to guess at the byte-order
  787. ** using C-preprocessor macros. If that is unsuccessful, or if
  788. ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
  789. ** at run-time.
  790. */
  791. #ifndef SHA3_BYTEORDER
  792. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  793. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  794. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  795. defined(__arm__)
  796. # define SHA3_BYTEORDER 1234
  797. # elif defined(sparc) || defined(__ppc__)
  798. # define SHA3_BYTEORDER 4321
  799. # else
  800. # define SHA3_BYTEORDER 0
  801. # endif
  802. #endif
  803. /*
  804. ** State structure for a SHA3 hash in progress
  805. */
  806. typedef struct SHA3Context SHA3Context;
  807. struct SHA3Context {
  808. union {
  809. u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
  810. unsigned char x[1600]; /* ... or 1600 bytes */
  811. } u;
  812. unsigned nRate; /* Bytes of input accepted per Keccak iteration */
  813. unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
  814. unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
  815. };
  816. /*
  817. ** A single step of the Keccak mixing function for a 1600-bit state
  818. */
  819. static void KeccakF1600Step(SHA3Context *p){
  820. int i;
  821. u64 B0, B1, B2, B3, B4;
  822. u64 C0, C1, C2, C3, C4;
  823. u64 D0, D1, D2, D3, D4;
  824. static const u64 RC[] = {
  825. 0x0000000000000001ULL, 0x0000000000008082ULL,
  826. 0x800000000000808aULL, 0x8000000080008000ULL,
  827. 0x000000000000808bULL, 0x0000000080000001ULL,
  828. 0x8000000080008081ULL, 0x8000000000008009ULL,
  829. 0x000000000000008aULL, 0x0000000000000088ULL,
  830. 0x0000000080008009ULL, 0x000000008000000aULL,
  831. 0x000000008000808bULL, 0x800000000000008bULL,
  832. 0x8000000000008089ULL, 0x8000000000008003ULL,
  833. 0x8000000000008002ULL, 0x8000000000000080ULL,
  834. 0x000000000000800aULL, 0x800000008000000aULL,
  835. 0x8000000080008081ULL, 0x8000000000008080ULL,
  836. 0x0000000080000001ULL, 0x8000000080008008ULL
  837. };
  838. # define A00 (p->u.s[0])
  839. # define A01 (p->u.s[1])
  840. # define A02 (p->u.s[2])
  841. # define A03 (p->u.s[3])
  842. # define A04 (p->u.s[4])
  843. # define A10 (p->u.s[5])
  844. # define A11 (p->u.s[6])
  845. # define A12 (p->u.s[7])
  846. # define A13 (p->u.s[8])
  847. # define A14 (p->u.s[9])
  848. # define A20 (p->u.s[10])
  849. # define A21 (p->u.s[11])
  850. # define A22 (p->u.s[12])
  851. # define A23 (p->u.s[13])
  852. # define A24 (p->u.s[14])
  853. # define A30 (p->u.s[15])
  854. # define A31 (p->u.s[16])
  855. # define A32 (p->u.s[17])
  856. # define A33 (p->u.s[18])
  857. # define A34 (p->u.s[19])
  858. # define A40 (p->u.s[20])
  859. # define A41 (p->u.s[21])
  860. # define A42 (p->u.s[22])
  861. # define A43 (p->u.s[23])
  862. # define A44 (p->u.s[24])
  863. # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
  864. for(i=0; i<24; i+=4){
  865. C0 = A00^A10^A20^A30^A40;
  866. C1 = A01^A11^A21^A31^A41;
  867. C2 = A02^A12^A22^A32^A42;
  868. C3 = A03^A13^A23^A33^A43;
  869. C4 = A04^A14^A24^A34^A44;
  870. D0 = C4^ROL64(C1, 1);
  871. D1 = C0^ROL64(C2, 1);
  872. D2 = C1^ROL64(C3, 1);
  873. D3 = C2^ROL64(C4, 1);
  874. D4 = C3^ROL64(C0, 1);
  875. B0 = (A00^D0);
  876. B1 = ROL64((A11^D1), 44);
  877. B2 = ROL64((A22^D2), 43);
  878. B3 = ROL64((A33^D3), 21);
  879. B4 = ROL64((A44^D4), 14);
  880. A00 = B0 ^((~B1)& B2 );
  881. A00 ^= RC[i];
  882. A11 = B1 ^((~B2)& B3 );
  883. A22 = B2 ^((~B3)& B4 );
  884. A33 = B3 ^((~B4)& B0 );
  885. A44 = B4 ^((~B0)& B1 );
  886. B2 = ROL64((A20^D0), 3);
  887. B3 = ROL64((A31^D1), 45);
  888. B4 = ROL64((A42^D2), 61);
  889. B0 = ROL64((A03^D3), 28);
  890. B1 = ROL64((A14^D4), 20);
  891. A20 = B0 ^((~B1)& B2 );
  892. A31 = B1 ^((~B2)& B3 );
  893. A42 = B2 ^((~B3)& B4 );
  894. A03 = B3 ^((~B4)& B0 );
  895. A14 = B4 ^((~B0)& B1 );
  896. B4 = ROL64((A40^D0), 18);
  897. B0 = ROL64((A01^D1), 1);
  898. B1 = ROL64((A12^D2), 6);
  899. B2 = ROL64((A23^D3), 25);
  900. B3 = ROL64((A34^D4), 8);
  901. A40 = B0 ^((~B1)& B2 );
  902. A01 = B1 ^((~B2)& B3 );
  903. A12 = B2 ^((~B3)& B4 );
  904. A23 = B3 ^((~B4)& B0 );
  905. A34 = B4 ^((~B0)& B1 );
  906. B1 = ROL64((A10^D0), 36);
  907. B2 = ROL64((A21^D1), 10);
  908. B3 = ROL64((A32^D2), 15);
  909. B4 = ROL64((A43^D3), 56);
  910. B0 = ROL64((A04^D4), 27);
  911. A10 = B0 ^((~B1)& B2 );
  912. A21 = B1 ^((~B2)& B3 );
  913. A32 = B2 ^((~B3)& B4 );
  914. A43 = B3 ^((~B4)& B0 );
  915. A04 = B4 ^((~B0)& B1 );
  916. B3 = ROL64((A30^D0), 41);
  917. B4 = ROL64((A41^D1), 2);
  918. B0 = ROL64((A02^D2), 62);
  919. B1 = ROL64((A13^D3), 55);
  920. B2 = ROL64((A24^D4), 39);
  921. A30 = B0 ^((~B1)& B2 );
  922. A41 = B1 ^((~B2)& B3 );
  923. A02 = B2 ^((~B3)& B4 );
  924. A13 = B3 ^((~B4)& B0 );
  925. A24 = B4 ^((~B0)& B1 );
  926. C0 = A00^A20^A40^A10^A30;
  927. C1 = A11^A31^A01^A21^A41;
  928. C2 = A22^A42^A12^A32^A02;
  929. C3 = A33^A03^A23^A43^A13;
  930. C4 = A44^A14^A34^A04^A24;
  931. D0 = C4^ROL64(C1, 1);
  932. D1 = C0^ROL64(C2, 1);
  933. D2 = C1^ROL64(C3, 1);
  934. D3 = C2^ROL64(C4, 1);
  935. D4 = C3^ROL64(C0, 1);
  936. B0 = (A00^D0);
  937. B1 = ROL64((A31^D1), 44);
  938. B2 = ROL64((A12^D2), 43);
  939. B3 = ROL64((A43^D3), 21);
  940. B4 = ROL64((A24^D4), 14);
  941. A00 = B0 ^((~B1)& B2 );
  942. A00 ^= RC[i+1];
  943. A31 = B1 ^((~B2)& B3 );
  944. A12 = B2 ^((~B3)& B4 );
  945. A43 = B3 ^((~B4)& B0 );
  946. A24 = B4 ^((~B0)& B1 );
  947. B2 = ROL64((A40^D0), 3);
  948. B3 = ROL64((A21^D1), 45);
  949. B4 = ROL64((A02^D2), 61);
  950. B0 = ROL64((A33^D3), 28);
  951. B1 = ROL64((A14^D4), 20);
  952. A40 = B0 ^((~B1)& B2 );
  953. A21 = B1 ^((~B2)& B3 );
  954. A02 = B2 ^((~B3)& B4 );
  955. A33 = B3 ^((~B4)& B0 );
  956. A14 = B4 ^((~B0)& B1 );
  957. B4 = ROL64((A30^D0), 18);
  958. B0 = ROL64((A11^D1), 1);
  959. B1 = ROL64((A42^D2), 6);
  960. B2 = ROL64((A23^D3), 25);
  961. B3 = ROL64((A04^D4), 8);
  962. A30 = B0 ^((~B1)& B2 );
  963. A11 = B1 ^((~B2)& B3 );
  964. A42 = B2 ^((~B3)& B4 );
  965. A23 = B3 ^((~B4)& B0 );
  966. A04 = B4 ^((~B0)& B1 );
  967. B1 = ROL64((A20^D0), 36);
  968. B2 = ROL64((A01^D1), 10);
  969. B3 = ROL64((A32^D2), 15);
  970. B4 = ROL64((A13^D3), 56);
  971. B0 = ROL64((A44^D4), 27);
  972. A20 = B0 ^((~B1)& B2 );
  973. A01 = B1 ^((~B2)& B3 );
  974. A32 = B2 ^((~B3)& B4 );
  975. A13 = B3 ^((~B4)& B0 );
  976. A44 = B4 ^((~B0)& B1 );
  977. B3 = ROL64((A10^D0), 41);
  978. B4 = ROL64((A41^D1), 2);
  979. B0 = ROL64((A22^D2), 62);
  980. B1 = ROL64((A03^D3), 55);
  981. B2 = ROL64((A34^D4), 39);
  982. A10 = B0 ^((~B1)& B2 );
  983. A41 = B1 ^((~B2)& B3 );
  984. A22 = B2 ^((~B3)& B4 );
  985. A03 = B3 ^((~B4)& B0 );
  986. A34 = B4 ^((~B0)& B1 );
  987. C0 = A00^A40^A30^A20^A10;
  988. C1 = A31^A21^A11^A01^A41;
  989. C2 = A12^A02^A42^A32^A22;
  990. C3 = A43^A33^A23^A13^A03;
  991. C4 = A24^A14^A04^A44^A34;
  992. D0 = C4^ROL64(C1, 1);
  993. D1 = C0^ROL64(C2, 1);
  994. D2 = C1^ROL64(C3, 1);
  995. D3 = C2^ROL64(C4, 1);
  996. D4 = C3^ROL64(C0, 1);
  997. B0 = (A00^D0);
  998. B1 = ROL64((A21^D1), 44);
  999. B2 = ROL64((A42^D2), 43);
  1000. B3 = ROL64((A13^D3), 21);
  1001. B4 = ROL64((A34^D4), 14);
  1002. A00 = B0 ^((~B1)& B2 );
  1003. A00 ^= RC[i+2];
  1004. A21 = B1 ^((~B2)& B3 );
  1005. A42 = B2 ^((~B3)& B4 );
  1006. A13 = B3 ^((~B4)& B0 );
  1007. A34 = B4 ^((~B0)& B1 );
  1008. B2 = ROL64((A30^D0), 3);
  1009. B3 = ROL64((A01^D1), 45);
  1010. B4 = ROL64((A22^D2), 61);
  1011. B0 = ROL64((A43^D3), 28);
  1012. B1 = ROL64((A14^D4), 20);
  1013. A30 = B0 ^((~B1)& B2 );
  1014. A01 = B1 ^((~B2)& B3 );
  1015. A22 = B2 ^((~B3)& B4 );
  1016. A43 = B3 ^((~B4)& B0 );
  1017. A14 = B4 ^((~B0)& B1 );
  1018. B4 = ROL64((A10^D0), 18);
  1019. B0 = ROL64((A31^D1), 1);
  1020. B1 = ROL64((A02^D2), 6);
  1021. B2 = ROL64((A23^D3), 25);
  1022. B3 = ROL64((A44^D4), 8);
  1023. A10 = B0 ^((~B1)& B2 );
  1024. A31 = B1 ^((~B2)& B3 );
  1025. A02 = B2 ^((~B3)& B4 );
  1026. A23 = B3 ^((~B4)& B0 );
  1027. A44 = B4 ^((~B0)& B1 );
  1028. B1 = ROL64((A40^D0), 36);
  1029. B2 = ROL64((A11^D1), 10);
  1030. B3 = ROL64((A32^D2), 15);
  1031. B4 = ROL64((A03^D3), 56);
  1032. B0 = ROL64((A24^D4), 27);
  1033. A40 = B0 ^((~B1)& B2 );
  1034. A11 = B1 ^((~B2)& B3 );
  1035. A32 = B2 ^((~B3)& B4 );
  1036. A03 = B3 ^((~B4)& B0 );
  1037. A24 = B4 ^((~B0)& B1 );
  1038. B3 = ROL64((A20^D0), 41);
  1039. B4 = ROL64((A41^D1), 2);
  1040. B0 = ROL64((A12^D2), 62);
  1041. B1 = ROL64((A33^D3), 55);
  1042. B2 = ROL64((A04^D4), 39);
  1043. A20 = B0 ^((~B1)& B2 );
  1044. A41 = B1 ^((~B2)& B3 );
  1045. A12 = B2 ^((~B3)& B4 );
  1046. A33 = B3 ^((~B4)& B0 );
  1047. A04 = B4 ^((~B0)& B1 );
  1048. C0 = A00^A30^A10^A40^A20;
  1049. C1 = A21^A01^A31^A11^A41;
  1050. C2 = A42^A22^A02^A32^A12;
  1051. C3 = A13^A43^A23^A03^A33;
  1052. C4 = A34^A14^A44^A24^A04;
  1053. D0 = C4^ROL64(C1, 1);
  1054. D1 = C0^ROL64(C2, 1);
  1055. D2 = C1^ROL64(C3, 1);
  1056. D3 = C2^ROL64(C4, 1);
  1057. D4 = C3^ROL64(C0, 1);
  1058. B0 = (A00^D0);
  1059. B1 = ROL64((A01^D1), 44);
  1060. B2 = ROL64((A02^D2), 43);
  1061. B3 = ROL64((A03^D3), 21);
  1062. B4 = ROL64((A04^D4), 14);
  1063. A00 = B0 ^((~B1)& B2 );
  1064. A00 ^= RC[i+3];
  1065. A01 = B1 ^((~B2)& B3 );
  1066. A02 = B2 ^((~B3)& B4 );
  1067. A03 = B3 ^((~B4)& B0 );
  1068. A04 = B4 ^((~B0)& B1 );
  1069. B2 = ROL64((A10^D0), 3);
  1070. B3 = ROL64((A11^D1), 45);
  1071. B4 = ROL64((A12^D2), 61);
  1072. B0 = ROL64((A13^D3), 28);
  1073. B1 = ROL64((A14^D4), 20);
  1074. A10 = B0 ^((~B1)& B2 );
  1075. A11 = B1 ^((~B2)& B3 );
  1076. A12 = B2 ^((~B3)& B4 );
  1077. A13 = B3 ^((~B4)& B0 );
  1078. A14 = B4 ^((~B0)& B1 );
  1079. B4 = ROL64((A20^D0), 18);
  1080. B0 = ROL64((A21^D1), 1);
  1081. B1 = ROL64((A22^D2), 6);
  1082. B2 = ROL64((A23^D3), 25);
  1083. B3 = ROL64((A24^D4), 8);
  1084. A20 = B0 ^((~B1)& B2 );
  1085. A21 = B1 ^((~B2)& B3 );
  1086. A22 = B2 ^((~B3)& B4 );
  1087. A23 = B3 ^((~B4)& B0 );
  1088. A24 = B4 ^((~B0)& B1 );
  1089. B1 = ROL64((A30^D0), 36);
  1090. B2 = ROL64((A31^D1), 10);
  1091. B3 = ROL64((A32^D2), 15);
  1092. B4 = ROL64((A33^D3), 56);
  1093. B0 = ROL64((A34^D4), 27);
  1094. A30 = B0 ^((~B1)& B2 );
  1095. A31 = B1 ^((~B2)& B3 );
  1096. A32 = B2 ^((~B3)& B4 );
  1097. A33 = B3 ^((~B4)& B0 );
  1098. A34 = B4 ^((~B0)& B1 );
  1099. B3 = ROL64((A40^D0), 41);
  1100. B4 = ROL64((A41^D1), 2);
  1101. B0 = ROL64((A42^D2), 62);
  1102. B1 = ROL64((A43^D3), 55);
  1103. B2 = ROL64((A44^D4), 39);
  1104. A40 = B0 ^((~B1)& B2 );
  1105. A41 = B1 ^((~B2)& B3 );
  1106. A42 = B2 ^((~B3)& B4 );
  1107. A43 = B3 ^((~B4)& B0 );
  1108. A44 = B4 ^((~B0)& B1 );
  1109. }
  1110. }
  1111. /*
  1112. ** Initialize a new hash. iSize determines the size of the hash
  1113. ** in bits and should be one of 224, 256, 384, or 512. Or iSize
  1114. ** can be zero to use the default hash size of 256 bits.
  1115. */
  1116. static void SHA3Init(SHA3Context *p, int iSize){
  1117. memset(p, 0, sizeof(*p));
  1118. if( iSize>=128 && iSize<=512 ){
  1119. p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
  1120. }else{
  1121. p->nRate = (1600 - 2*256)/8;
  1122. }
  1123. #if SHA3_BYTEORDER==1234
  1124. /* Known to be little-endian at compile-time. No-op */
  1125. #elif SHA3_BYTEORDER==4321
  1126. p->ixMask = 7; /* Big-endian */
  1127. #else
  1128. {
  1129. static unsigned int one = 1;
  1130. if( 1==*(unsigned char*)&one ){
  1131. /* Little endian. No byte swapping. */
  1132. p->ixMask = 0;
  1133. }else{
  1134. /* Big endian. Byte swap. */
  1135. p->ixMask = 7;
  1136. }
  1137. }
  1138. #endif
  1139. }
  1140. /*
  1141. ** Make consecutive calls to the SHA3Update function to add new content
  1142. ** to the hash
  1143. */
  1144. static void SHA3Update(
  1145. SHA3Context *p,
  1146. const unsigned char *aData,
  1147. unsigned int nData
  1148. ){
  1149. unsigned int i = 0;
  1150. #if SHA3_BYTEORDER==1234
  1151. if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
  1152. for(; i+7<nData; i+=8){
  1153. p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
  1154. p->nLoaded += 8;
  1155. if( p->nLoaded>=p->nRate ){
  1156. KeccakF1600Step(p);
  1157. p->nLoaded = 0;
  1158. }
  1159. }
  1160. }
  1161. #endif
  1162. for(; i<nData; i++){
  1163. #if SHA3_BYTEORDER==1234
  1164. p->u.x[p->nLoaded] ^= aData[i];
  1165. #elif SHA3_BYTEORDER==4321
  1166. p->u.x[p->nLoaded^0x07] ^= aData[i];
  1167. #else
  1168. p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
  1169. #endif
  1170. p->nLoaded++;
  1171. if( p->nLoaded==p->nRate ){
  1172. KeccakF1600Step(p);
  1173. p->nLoaded = 0;
  1174. }
  1175. }
  1176. }
  1177. /*
  1178. ** After all content has been added, invoke SHA3Final() to compute
  1179. ** the final hash. The function returns a pointer to the binary
  1180. ** hash value.
  1181. */
  1182. static unsigned char *SHA3Final(SHA3Context *p){
  1183. unsigned int i;
  1184. if( p->nLoaded==p->nRate-1 ){
  1185. const unsigned char c1 = 0x86;
  1186. SHA3Update(p, &c1, 1);
  1187. }else{
  1188. const unsigned char c2 = 0x06;
  1189. const unsigned char c3 = 0x80;
  1190. SHA3Update(p, &c2, 1);
  1191. p->nLoaded = p->nRate - 1;
  1192. SHA3Update(p, &c3, 1);
  1193. }
  1194. for(i=0; i<p->nRate; i++){
  1195. p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
  1196. }
  1197. return &p->u.x[p->nRate];
  1198. }
  1199. /* End of the hashing logic
  1200. *****************************************************************************/
  1201. /*
  1202. ** Implementation of the sha3(X,SIZE) function.
  1203. **
  1204. ** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
  1205. ** size is 256. If X is a BLOB, it is hashed as is.
  1206. ** For all other non-NULL types of input, X is converted into a UTF-8 string
  1207. ** and the string is hashed without the trailing 0x00 terminator. The hash
  1208. ** of a NULL value is NULL.
  1209. */
  1210. static void sha3Func(
  1211. sqlite3_context *context,
  1212. int argc,
  1213. sqlite3_value **argv
  1214. ){
  1215. SHA3Context cx;
  1216. int eType = sqlite3_value_type(argv[0]);
  1217. int nByte = sqlite3_value_bytes(argv[0]);
  1218. int iSize;
  1219. if( argc==1 ){
  1220. iSize = 256;
  1221. }else{
  1222. iSize = sqlite3_value_int(argv[1]);
  1223. if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
  1224. sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
  1225. "384 512", -1);
  1226. return;
  1227. }
  1228. }
  1229. if( eType==SQLITE_NULL ) return;
  1230. SHA3Init(&cx, iSize);
  1231. if( eType==SQLITE_BLOB ){
  1232. SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
  1233. }else{
  1234. SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
  1235. }
  1236. sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
  1237. }
  1238. /* Compute a string using sqlite3_vsnprintf() with a maximum length
  1239. ** of 50 bytes and add it to the hash.
  1240. */
  1241. static void hash_step_vformat(
  1242. SHA3Context *p, /* Add content to this context */
  1243. const char *zFormat,
  1244. ...
  1245. ){
  1246. va_list ap;
  1247. int n;
  1248. char zBuf[50];
  1249. va_start(ap, zFormat);
  1250. sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
  1251. va_end(ap);
  1252. n = (int)strlen(zBuf);
  1253. SHA3Update(p, (unsigned char*)zBuf, n);
  1254. }
  1255. /*
  1256. ** Implementation of the sha3_query(SQL,SIZE) function.
  1257. **
  1258. ** This function compiles and runs the SQL statement(s) given in the
  1259. ** argument. The results are hashed using a SIZE-bit SHA3. The default
  1260. ** size is 256.
  1261. **
  1262. ** The format of the byte stream that is hashed is summarized as follows:
  1263. **
  1264. ** S<n>:<sql>
  1265. ** R
  1266. ** N
  1267. ** I<int>
  1268. ** F<ieee-float>
  1269. ** B<size>:<bytes>
  1270. ** T<size>:<text>
  1271. **
  1272. ** <sql> is the original SQL text for each statement run and <n> is
  1273. ** the size of that text. The SQL text is UTF-8. A single R character
  1274. ** occurs before the start of each row. N means a NULL value.
  1275. ** I mean an 8-byte little-endian integer <int>. F is a floating point
  1276. ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
  1277. ** B means blobs of <size> bytes. T means text rendered as <size>
  1278. ** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
  1279. ** text integers.
  1280. **
  1281. ** For each SQL statement in the X input, there is one S segment. Each
  1282. ** S segment is followed by zero or more R segments, one for each row in the
  1283. ** result set. After each R, there are one or more N, I, F, B, or T segments,
  1284. ** one for each column in the result set. Segments are concatentated directly
  1285. ** with no delimiters of any kind.
  1286. */
  1287. static void sha3QueryFunc(
  1288. sqlite3_context *context,
  1289. int argc,
  1290. sqlite3_value **argv
  1291. ){
  1292. sqlite3 *db = sqlite3_context_db_handle(context);
  1293. const char *zSql = (const char*)sqlite3_value_text(argv[0]);
  1294. sqlite3_stmt *pStmt = 0;
  1295. int nCol; /* Number of columns in the result set */
  1296. int i; /* Loop counter */
  1297. int rc;
  1298. int n;
  1299. const char *z;
  1300. SHA3Context cx;
  1301. int iSize;
  1302. if( argc==1 ){
  1303. iSize = 256;
  1304. }else{
  1305. iSize = sqlite3_value_int(argv[1]);
  1306. if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
  1307. sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
  1308. "384 512", -1);
  1309. return;
  1310. }
  1311. }
  1312. if( zSql==0 ) return;
  1313. SHA3Init(&cx, iSize);
  1314. while( zSql[0] ){
  1315. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
  1316. if( rc ){
  1317. char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
  1318. zSql, sqlite3_errmsg(db));
  1319. sqlite3_finalize(pStmt);
  1320. sqlite3_result_error(context, zMsg, -1);
  1321. sqlite3_free(zMsg);
  1322. return;
  1323. }
  1324. if( !sqlite3_stmt_readonly(pStmt) ){
  1325. char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
  1326. sqlite3_finalize(pStmt);
  1327. sqlite3_result_error(context, zMsg, -1);
  1328. sqlite3_free(zMsg);
  1329. return;
  1330. }
  1331. nCol = sqlite3_column_count(pStmt);
  1332. z = sqlite3_sql(pStmt);
  1333. n = (int)strlen(z);
  1334. hash_step_vformat(&cx,"S%d:",n);
  1335. SHA3Update(&cx,(unsigned char*)z,n);
  1336. /* Compute a hash over the result of the query */
  1337. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  1338. SHA3Update(&cx,(const unsigned char*)"R",1);
  1339. for(i=0; i<nCol; i++){
  1340. switch( sqlite3_column_type(pStmt,i) ){
  1341. case SQLITE_NULL: {
  1342. SHA3Update(&cx, (const unsigned char*)"N",1);
  1343. break;
  1344. }
  1345. case SQLITE_INTEGER: {
  1346. sqlite3_uint64 u;
  1347. int j;
  1348. unsigned char x[9];
  1349. sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
  1350. memcpy(&u, &v, 8);
  1351. for(j=8; j>=1; j--){
  1352. x[j] = u & 0xff;
  1353. u >>= 8;
  1354. }
  1355. x[0] = 'I';
  1356. SHA3Update(&cx, x, 9);
  1357. break;
  1358. }
  1359. case SQLITE_FLOAT: {
  1360. sqlite3_uint64 u;
  1361. int j;
  1362. unsigned char x[9];
  1363. double r = sqlite3_column_double(pStmt,i);
  1364. memcpy(&u, &r, 8);
  1365. for(j=8; j>=1; j--){
  1366. x[j] = u & 0xff;
  1367. u >>= 8;
  1368. }
  1369. x[0] = 'F';
  1370. SHA3Update(&cx,x,9);
  1371. break;
  1372. }
  1373. case SQLITE_TEXT: {
  1374. int n2 = sqlite3_column_bytes(pStmt, i);
  1375. const unsigned char *z2 = sqlite3_column_text(pStmt, i);
  1376. hash_step_vformat(&cx,"T%d:",n2);
  1377. SHA3Update(&cx, z2, n2);
  1378. break;
  1379. }
  1380. case SQLITE_BLOB: {
  1381. int n2 = sqlite3_column_bytes(pStmt, i);
  1382. const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
  1383. hash_step_vformat(&cx,"B%d:",n2);
  1384. SHA3Update(&cx, z2, n2);
  1385. break;
  1386. }
  1387. }
  1388. }
  1389. }
  1390. sqlite3_finalize(pStmt);
  1391. }
  1392. sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
  1393. }
  1394. #ifdef _WIN32
  1395. #endif
  1396. int sqlite3_shathree_init(
  1397. sqlite3 *db,
  1398. char **pzErrMsg,
  1399. const sqlite3_api_routines *pApi
  1400. ){
  1401. int rc = SQLITE_OK;
  1402. SQLITE_EXTENSION_INIT2(pApi);
  1403. (void)pzErrMsg; /* Unused parameter */
  1404. rc = sqlite3_create_function(db, "sha3", 1, SQLITE_UTF8, 0,
  1405. sha3Func, 0, 0);
  1406. if( rc==SQLITE_OK ){
  1407. rc = sqlite3_create_function(db, "sha3", 2, SQLITE_UTF8, 0,
  1408. sha3Func, 0, 0);
  1409. }
  1410. if( rc==SQLITE_OK ){
  1411. rc = sqlite3_create_function(db, "sha3_query", 1, SQLITE_UTF8, 0,
  1412. sha3QueryFunc, 0, 0);
  1413. }
  1414. if( rc==SQLITE_OK ){
  1415. rc = sqlite3_create_function(db, "sha3_query", 2, SQLITE_UTF8, 0,
  1416. sha3QueryFunc, 0, 0);
  1417. }
  1418. return rc;
  1419. }
  1420. /************************* End ../ext/misc/shathree.c ********************/
  1421. /************************* Begin ../ext/misc/fileio.c ******************/
  1422. /*
  1423. ** 2014-06-13
  1424. **
  1425. ** The author disclaims copyright to this source code. In place of
  1426. ** a legal notice, here is a blessing:
  1427. **
  1428. ** May you do good and not evil.
  1429. ** May you find forgiveness for yourself and forgive others.
  1430. ** May you share freely, never taking more than you give.
  1431. **
  1432. ******************************************************************************
  1433. **
  1434. ** This SQLite extension implements SQL functions readfile() and
  1435. ** writefile().
  1436. */
  1437. SQLITE_EXTENSION_INIT1
  1438. #include <stdio.h>
  1439. /*
  1440. ** Implementation of the "readfile(X)" SQL function. The entire content
  1441. ** of the file named X is read and returned as a BLOB. NULL is returned
  1442. ** if the file does not exist or is unreadable.
  1443. */
  1444. static void readfileFunc(
  1445. sqlite3_context *context,
  1446. int argc,
  1447. sqlite3_value **argv
  1448. ){
  1449. const char *zName;
  1450. FILE *in;
  1451. long nIn;
  1452. void *pBuf;
  1453. (void)(argc); /* Unused parameter */
  1454. zName = (const char*)sqlite3_value_text(argv[0]);
  1455. if( zName==0 ) return;
  1456. in = fopen(zName, "rb");
  1457. if( in==0 ) return;
  1458. fseek(in, 0, SEEK_END);
  1459. nIn = ftell(in);
  1460. rewind(in);
  1461. pBuf = sqlite3_malloc( nIn );
  1462. if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
  1463. sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
  1464. }else{
  1465. sqlite3_free(pBuf);
  1466. }
  1467. fclose(in);
  1468. }
  1469. /*
  1470. ** Implementation of the "writefile(X,Y)" SQL function. The argument Y
  1471. ** is written into file X. The number of bytes written is returned. Or
  1472. ** NULL is returned if something goes wrong, such as being unable to open
  1473. ** file X for writing.
  1474. */
  1475. static void writefileFunc(
  1476. sqlite3_context *context,
  1477. int argc,
  1478. sqlite3_value **argv
  1479. ){
  1480. FILE *out;
  1481. const char *z;
  1482. sqlite3_int64 rc;
  1483. const char *zFile;
  1484. (void)(argc); /* Unused parameter */
  1485. zFile = (const char*)sqlite3_value_text(argv[0]);
  1486. if( zFile==0 ) return;
  1487. out = fopen(zFile, "wb");
  1488. if( out==0 ) return;
  1489. z = (const char*)sqlite3_value_blob(argv[1]);
  1490. if( z==0 ){
  1491. rc = 0;
  1492. }else{
  1493. rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
  1494. }
  1495. fclose(out);
  1496. sqlite3_result_int64(context, rc);
  1497. }
  1498. #ifdef _WIN32
  1499. #endif
  1500. int sqlite3_fileio_init(
  1501. sqlite3 *db,
  1502. char **pzErrMsg,
  1503. const sqlite3_api_routines *pApi
  1504. ){
  1505. int rc = SQLITE_OK;
  1506. SQLITE_EXTENSION_INIT2(pApi);
  1507. (void)pzErrMsg; /* Unused parameter */
  1508. rc = sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
  1509. readfileFunc, 0, 0);
  1510. if( rc==SQLITE_OK ){
  1511. rc = sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
  1512. writefileFunc, 0, 0);
  1513. }
  1514. return rc;
  1515. }
  1516. /************************* End ../ext/misc/fileio.c ********************/
  1517. /************************* Begin ../ext/misc/completion.c ******************/
  1518. /*
  1519. ** 2017-07-10
  1520. **
  1521. ** The author disclaims copyright to this source code. In place of
  1522. ** a legal notice, here is a blessing:
  1523. **
  1524. ** May you do good and not evil.
  1525. ** May you find forgiveness for yourself and forgive others.
  1526. ** May you share freely, never taking more than you give.
  1527. **
  1528. *************************************************************************
  1529. **
  1530. ** This file implements an eponymous virtual table that returns suggested
  1531. ** completions for a partial SQL input.
  1532. **
  1533. ** Suggested usage:
  1534. **
  1535. ** SELECT DISTINCT candidate COLLATE nocase
  1536. ** FROM completion($prefix,$wholeline)
  1537. ** ORDER BY 1;
  1538. **
  1539. ** The two query parameters are optional. $prefix is the text of the
  1540. ** current word being typed and that is to be completed. $wholeline is
  1541. ** the complete input line, used for context.
  1542. **
  1543. ** The raw completion() table might return the same candidate multiple
  1544. ** times, for example if the same column name is used to two or more
  1545. ** tables. And the candidates are returned in an arbitrary order. Hence,
  1546. ** the DISTINCT and ORDER BY are recommended.
  1547. **
  1548. ** This virtual table operates at the speed of human typing, and so there
  1549. ** is no attempt to make it fast. Even a slow implementation will be much
  1550. ** faster than any human can type.
  1551. **
  1552. */
  1553. SQLITE_EXTENSION_INIT1
  1554. #include <assert.h>
  1555. #include <string.h>
  1556. #include <ctype.h>
  1557. #ifndef SQLITE_OMIT_VIRTUALTABLE
  1558. /* completion_vtab is a subclass of sqlite3_vtab which will
  1559. ** serve as the underlying representation of a completion virtual table
  1560. */
  1561. typedef struct completion_vtab completion_vtab;
  1562. struct completion_vtab {
  1563. sqlite3_vtab base; /* Base class - must be first */
  1564. sqlite3 *db; /* Database connection for this completion vtab */
  1565. };
  1566. /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
  1567. ** serve as the underlying representation of a cursor that scans
  1568. ** over rows of the result
  1569. */
  1570. typedef struct completion_cursor completion_cursor;
  1571. struct completion_cursor {
  1572. sqlite3_vtab_cursor base; /* Base class - must be first */
  1573. sqlite3 *db; /* Database connection for this cursor */
  1574. int nPrefix, nLine; /* Number of bytes in zPrefix and zLine */
  1575. char *zPrefix; /* The prefix for the word we want to complete */
  1576. char *zLine; /* The whole that we want to complete */
  1577. const char *zCurrentRow; /* Current output row */
  1578. sqlite3_stmt *pStmt; /* Current statement */
  1579. sqlite3_int64 iRowid; /* The rowid */
  1580. int ePhase; /* Current phase */
  1581. int j; /* inter-phase counter */
  1582. };
  1583. /* Values for ePhase:
  1584. */
  1585. #define COMPLETION_FIRST_PHASE 1
  1586. #define COMPLETION_KEYWORDS 1
  1587. #define COMPLETION_PRAGMAS 2
  1588. #define COMPLETION_FUNCTIONS 3
  1589. #define COMPLETION_COLLATIONS 4
  1590. #define COMPLETION_INDEXES 5
  1591. #define COMPLETION_TRIGGERS 6
  1592. #define COMPLETION_DATABASES 7
  1593. #define COMPLETION_TABLES 8
  1594. #define COMPLETION_COLUMNS 9
  1595. #define COMPLETION_MODULES 10
  1596. #define COMPLETION_EOF 11
  1597. /*
  1598. ** The completionConnect() method is invoked to create a new
  1599. ** completion_vtab that describes the completion virtual table.
  1600. **
  1601. ** Think of this routine as the constructor for completion_vtab objects.
  1602. **
  1603. ** All this routine needs to do is:
  1604. **
  1605. ** (1) Allocate the completion_vtab object and initialize all fields.
  1606. **
  1607. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  1608. ** result set of queries against completion will look like.
  1609. */
  1610. static int completionConnect(
  1611. sqlite3 *db,
  1612. void *pAux,
  1613. int argc, const char *const*argv,
  1614. sqlite3_vtab **ppVtab,
  1615. char **pzErr
  1616. ){
  1617. completion_vtab *pNew;
  1618. int rc;
  1619. (void)(pAux); /* Unused parameter */
  1620. (void)(argc); /* Unused parameter */
  1621. (void)(argv); /* Unused parameter */
  1622. (void)(pzErr); /* Unused parameter */
  1623. /* Column numbers */
  1624. #define COMPLETION_COLUMN_CANDIDATE 0 /* Suggested completion of the input */
  1625. #define COMPLETION_COLUMN_PREFIX 1 /* Prefix of the word to be completed */
  1626. #define COMPLETION_COLUMN_WHOLELINE 2 /* Entire line seen so far */
  1627. #define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */
  1628. rc = sqlite3_declare_vtab(db,
  1629. "CREATE TABLE x("
  1630. " candidate TEXT,"
  1631. " prefix TEXT HIDDEN,"
  1632. " wholeline TEXT HIDDEN,"
  1633. " phase INT HIDDEN" /* Used for debugging only */
  1634. ")");
  1635. if( rc==SQLITE_OK ){
  1636. pNew = sqlite3_malloc( sizeof(*pNew) );
  1637. *ppVtab = (sqlite3_vtab*)pNew;
  1638. if( pNew==0 ) return SQLITE_NOMEM;
  1639. memset(pNew, 0, sizeof(*pNew));
  1640. pNew->db = db;
  1641. }
  1642. return rc;
  1643. }
  1644. /*
  1645. ** This method is the destructor for completion_cursor objects.
  1646. */
  1647. static int completionDisconnect(sqlite3_vtab *pVtab){
  1648. sqlite3_free(pVtab);
  1649. return SQLITE_OK;
  1650. }
  1651. /*
  1652. ** Constructor for a new completion_cursor object.
  1653. */
  1654. static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  1655. completion_cursor *pCur;
  1656. pCur = sqlite3_malloc( sizeof(*pCur) );
  1657. if( pCur==0 ) return SQLITE_NOMEM;
  1658. memset(pCur, 0, sizeof(*pCur));
  1659. pCur->db = ((completion_vtab*)p)->db;
  1660. *ppCursor = &pCur->base;
  1661. return SQLITE_OK;
  1662. }
  1663. /*
  1664. ** Reset the completion_cursor.
  1665. */
  1666. static void completionCursorReset(completion_cursor *pCur){
  1667. sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0;
  1668. sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0;
  1669. sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
  1670. pCur->j = 0;
  1671. }
  1672. /*
  1673. ** Destructor for a completion_cursor.
  1674. */
  1675. static int completionClose(sqlite3_vtab_cursor *cur){
  1676. completionCursorReset((completion_cursor*)cur);
  1677. sqlite3_free(cur);
  1678. return SQLITE_OK;
  1679. }
  1680. /*
  1681. ** All SQL keywords understood by SQLite
  1682. */
  1683. static const char *completionKwrds[] = {
  1684. "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
  1685. "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
  1686. "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
  1687. "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
  1688. "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
  1689. "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
  1690. "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
  1691. "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
  1692. "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
  1693. "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
  1694. "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
  1695. "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
  1696. "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
  1697. "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
  1698. "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
  1699. "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
  1700. "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
  1701. "WITH", "WITHOUT",
  1702. };
  1703. #define completionKwCount \
  1704. (int)(sizeof(completionKwrds)/sizeof(completionKwrds[0]))
  1705. /*
  1706. ** Advance a completion_cursor to its next row of output.
  1707. **
  1708. ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
  1709. ** record the current state of the scan. This routine sets ->zCurrentRow
  1710. ** to the current row of output and then returns. If no more rows remain,
  1711. ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
  1712. ** table that has reached the end of its scan.
  1713. **
  1714. ** The current implementation just lists potential identifiers and
  1715. ** keywords and filters them by zPrefix. Future enhancements should
  1716. ** take zLine into account to try to restrict the set of identifiers and
  1717. ** keywords based on what would be legal at the current point of input.
  1718. */
  1719. static int completionNext(sqlite3_vtab_cursor *cur){
  1720. completion_cursor *pCur = (completion_cursor*)cur;
  1721. int eNextPhase = 0; /* Next phase to try if current phase reaches end */
  1722. int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */
  1723. pCur->iRowid++;
  1724. while( pCur->ePhase!=COMPLETION_EOF ){
  1725. switch( pCur->ePhase ){
  1726. case COMPLETION_KEYWORDS: {
  1727. if( pCur->j >= completionKwCount ){
  1728. pCur->zCurrentRow = 0;
  1729. pCur->ePhase = COMPLETION_DATABASES;
  1730. }else{
  1731. pCur->zCurrentRow = completionKwrds[pCur->j++];
  1732. }
  1733. iCol = -1;
  1734. break;
  1735. }
  1736. case COMPLETION_DATABASES: {
  1737. if( pCur->pStmt==0 ){
  1738. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
  1739. &pCur->pStmt, 0);
  1740. }
  1741. iCol = 1;
  1742. eNextPhase = COMPLETION_TABLES;
  1743. break;
  1744. }
  1745. case COMPLETION_TABLES: {
  1746. if( pCur->pStmt==0 ){
  1747. sqlite3_stmt *pS2;
  1748. char *zSql = 0;
  1749. const char *zSep = "";
  1750. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
  1751. while( sqlite3_step(pS2)==SQLITE_ROW ){
  1752. const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
  1753. zSql = sqlite3_mprintf(
  1754. "%z%s"
  1755. "SELECT name FROM \"%w\".sqlite_master"
  1756. " WHERE type='table'",
  1757. zSql, zSep, zDb
  1758. );
  1759. if( zSql==0 ) return SQLITE_NOMEM;
  1760. zSep = " UNION ";
  1761. }
  1762. sqlite3_finalize(pS2);
  1763. sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
  1764. sqlite3_free(zSql);
  1765. }
  1766. iCol = 0;
  1767. eNextPhase = COMPLETION_COLUMNS;
  1768. break;
  1769. }
  1770. case COMPLETION_COLUMNS: {
  1771. if( pCur->pStmt==0 ){
  1772. sqlite3_stmt *pS2;
  1773. char *zSql = 0;
  1774. const char *zSep = "";
  1775. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
  1776. while( sqlite3_step(pS2)==SQLITE_ROW ){
  1777. const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
  1778. zSql = sqlite3_mprintf(
  1779. "%z%s"
  1780. "SELECT pti.name FROM \"%w\".sqlite_master AS sm"
  1781. " JOIN pragma_table_info(sm.name,%Q) AS pti"
  1782. " WHERE sm.type='table'",
  1783. zSql, zSep, zDb, zDb
  1784. );
  1785. if( zSql==0 ) return SQLITE_NOMEM;
  1786. zSep = " UNION ";
  1787. }
  1788. sqlite3_finalize(pS2);
  1789. sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
  1790. sqlite3_free(zSql);
  1791. }
  1792. iCol = 0;
  1793. eNextPhase = COMPLETION_EOF;
  1794. break;
  1795. }
  1796. }
  1797. if( iCol<0 ){
  1798. /* This case is when the phase presets zCurrentRow */
  1799. if( pCur->zCurrentRow==0 ) continue;
  1800. }else{
  1801. if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
  1802. /* Extract the next row of content */
  1803. pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
  1804. }else{
  1805. /* When all rows are finished, advance to the next phase */
  1806. sqlite3_finalize(pCur->pStmt);
  1807. pCur->pStmt = 0;
  1808. pCur->ePhase = eNextPhase;
  1809. continue;
  1810. }
  1811. }
  1812. if( pCur->nPrefix==0 ) break;
  1813. if( sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0 ){
  1814. break;
  1815. }
  1816. }
  1817. return SQLITE_OK;
  1818. }
  1819. /*
  1820. ** Return values of columns for the row at which the completion_cursor
  1821. ** is currently pointing.
  1822. */
  1823. static int completionColumn(
  1824. sqlite3_vtab_cursor *cur, /* The cursor */
  1825. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  1826. int i /* Which column to return */
  1827. ){
  1828. completion_cursor *pCur = (completion_cursor*)cur;
  1829. switch( i ){
  1830. case COMPLETION_COLUMN_CANDIDATE: {
  1831. sqlite3_result_text(ctx, pCur->zCurrentRow, -1, SQLITE_TRANSIENT);
  1832. break;
  1833. }
  1834. case COMPLETION_COLUMN_PREFIX: {
  1835. sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
  1836. break;
  1837. }
  1838. case COMPLETION_COLUMN_WHOLELINE: {
  1839. sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
  1840. break;
  1841. }
  1842. case COMPLETION_COLUMN_PHASE: {
  1843. sqlite3_result_int(ctx, pCur->ePhase);
  1844. break;
  1845. }
  1846. }
  1847. return SQLITE_OK;
  1848. }
  1849. /*
  1850. ** Return the rowid for the current row. In this implementation, the
  1851. ** rowid is the same as the output value.
  1852. */
  1853. static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  1854. completion_cursor *pCur = (completion_cursor*)cur;
  1855. *pRowid = pCur->iRowid;
  1856. return SQLITE_OK;
  1857. }
  1858. /*
  1859. ** Return TRUE if the cursor has been moved off of the last
  1860. ** row of output.
  1861. */
  1862. static int completionEof(sqlite3_vtab_cursor *cur){
  1863. completion_cursor *pCur = (completion_cursor*)cur;
  1864. return pCur->ePhase >= COMPLETION_EOF;
  1865. }
  1866. /*
  1867. ** This method is called to "rewind" the completion_cursor object back
  1868. ** to the first row of output. This method is always called at least
  1869. ** once prior to any call to completionColumn() or completionRowid() or
  1870. ** completionEof().
  1871. */
  1872. static int completionFilter(
  1873. sqlite3_vtab_cursor *pVtabCursor,
  1874. int idxNum, const char *idxStr,
  1875. int argc, sqlite3_value **argv
  1876. ){
  1877. completion_cursor *pCur = (completion_cursor *)pVtabCursor;
  1878. int iArg = 0;
  1879. (void)(idxStr); /* Unused parameter */
  1880. (void)(argc); /* Unused parameter */
  1881. completionCursorReset(pCur);
  1882. if( idxNum & 1 ){
  1883. pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
  1884. if( pCur->nPrefix>0 ){
  1885. pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
  1886. if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
  1887. }
  1888. iArg++;
  1889. }
  1890. if( idxNum & 2 ){
  1891. pCur->nLine = sqlite3_value_bytes(argv[iArg]);
  1892. if( pCur->nLine>0 ){
  1893. pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
  1894. if( pCur->zLine==0 ) return SQLITE_NOMEM;
  1895. }
  1896. iArg++;
  1897. }
  1898. if( pCur->zLine!=0 && pCur->zPrefix==0 ){
  1899. int i = pCur->nLine;
  1900. while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
  1901. i--;
  1902. }
  1903. pCur->nPrefix = pCur->nLine - i;
  1904. if( pCur->nPrefix>0 ){
  1905. pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
  1906. if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
  1907. }
  1908. }
  1909. pCur->iRowid = 0;
  1910. pCur->ePhase = COMPLETION_FIRST_PHASE;
  1911. return completionNext(pVtabCursor);
  1912. }
  1913. /*
  1914. ** SQLite will invoke this method one or more times while planning a query
  1915. ** that uses the completion virtual table. This routine needs to create
  1916. ** a query plan for each invocation and compute an estimated cost for that
  1917. ** plan.
  1918. **
  1919. ** There are two hidden parameters that act as arguments to the table-valued
  1920. ** function: "prefix" and "wholeline". Bit 0 of idxNum is set if "prefix"
  1921. ** is available and bit 1 is set if "wholeline" is available.
  1922. */
  1923. static int completionBestIndex(
  1924. sqlite3_vtab *tab,
  1925. sqlite3_index_info *pIdxInfo
  1926. ){
  1927. int i; /* Loop over constraints */
  1928. int idxNum = 0; /* The query plan bitmask */
  1929. int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */
  1930. int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
  1931. int nArg = 0; /* Number of arguments that completeFilter() expects */
  1932. const struct sqlite3_index_constraint *pConstraint;
  1933. (void)(tab); /* Unused parameter */
  1934. pConstraint = pIdxInfo->aConstraint;
  1935. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  1936. if( pConstraint->usable==0 ) continue;
  1937. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  1938. switch( pConstraint->iColumn ){
  1939. case COMPLETION_COLUMN_PREFIX:
  1940. prefixIdx = i;
  1941. idxNum |= 1;
  1942. break;
  1943. case COMPLETION_COLUMN_WHOLELINE:
  1944. wholelineIdx = i;
  1945. idxNum |= 2;
  1946. break;
  1947. }
  1948. }
  1949. if( prefixIdx>=0 ){
  1950. pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
  1951. pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
  1952. }
  1953. if( wholelineIdx>=0 ){
  1954. pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
  1955. pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
  1956. }
  1957. pIdxInfo->idxNum = idxNum;
  1958. pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
  1959. pIdxInfo->estimatedRows = 500 - 100*nArg;
  1960. return SQLITE_OK;
  1961. }
  1962. /*
  1963. ** This following structure defines all the methods for the
  1964. ** completion virtual table.
  1965. */
  1966. static sqlite3_module completionModule = {
  1967. 0, /* iVersion */
  1968. 0, /* xCreate */
  1969. completionConnect, /* xConnect */
  1970. completionBestIndex, /* xBestIndex */
  1971. completionDisconnect, /* xDisconnect */
  1972. 0, /* xDestroy */
  1973. completionOpen, /* xOpen - open a cursor */
  1974. completionClose, /* xClose - close a cursor */
  1975. completionFilter, /* xFilter - configure scan constraints */
  1976. completionNext, /* xNext - advance a cursor */
  1977. completionEof, /* xEof - check for end of scan */
  1978. completionColumn, /* xColumn - read data */
  1979. completionRowid, /* xRowid - read data */
  1980. 0, /* xUpdate */
  1981. 0, /* xBegin */
  1982. 0, /* xSync */
  1983. 0, /* xCommit */
  1984. 0, /* xRollback */
  1985. 0, /* xFindMethod */
  1986. 0, /* xRename */
  1987. 0, /* xSavepoint */
  1988. 0, /* xRelease */
  1989. 0 /* xRollbackTo */
  1990. };
  1991. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  1992. int sqlite3CompletionVtabInit(sqlite3 *db){
  1993. int rc = SQLITE_OK;
  1994. #ifndef SQLITE_OMIT_VIRTUALTABLE
  1995. rc = sqlite3_create_module(db, "completion", &completionModule, 0);
  1996. #endif
  1997. return rc;
  1998. }
  1999. #ifdef _WIN32
  2000. #endif
  2001. int sqlite3_completion_init(
  2002. sqlite3 *db,
  2003. char **pzErrMsg,
  2004. const sqlite3_api_routines *pApi
  2005. ){
  2006. int rc = SQLITE_OK;
  2007. SQLITE_EXTENSION_INIT2(pApi);
  2008. (void)(pzErrMsg); /* Unused parameter */
  2009. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2010. rc = sqlite3CompletionVtabInit(db);
  2011. #endif
  2012. return rc;
  2013. }
  2014. /************************* End ../ext/misc/completion.c ********************/
  2015. #if defined(SQLITE_ENABLE_SESSION)
  2016. /*
  2017. ** State information for a single open session
  2018. */
  2019. typedef struct OpenSession OpenSession;
  2020. struct OpenSession {
  2021. char *zName; /* Symbolic name for this session */
  2022. int nFilter; /* Number of xFilter rejection GLOB patterns */
  2023. char **azFilter; /* Array of xFilter rejection GLOB patterns */
  2024. sqlite3_session *p; /* The open session */
  2025. };
  2026. #endif
  2027. /*
  2028. ** Shell output mode information from before ".explain on",
  2029. ** saved so that it can be restored by ".explain off"
  2030. */
  2031. typedef struct SavedModeInfo SavedModeInfo;
  2032. struct SavedModeInfo {
  2033. int valid; /* Is there legit data in here? */
  2034. int mode; /* Mode prior to ".explain on" */
  2035. int showHeader; /* The ".header" setting prior to ".explain on" */
  2036. int colWidth[100]; /* Column widths prior to ".explain on" */
  2037. };
  2038. /*
  2039. ** State information about the database connection is contained in an
  2040. ** instance of the following structure.
  2041. */
  2042. typedef struct ShellState ShellState;
  2043. struct ShellState {
  2044. sqlite3 *db; /* The database */
  2045. int autoExplain; /* Automatically turn on .explain mode */
  2046. int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
  2047. int statsOn; /* True to display memory stats before each finalize */
  2048. int scanstatsOn; /* True to display scan stats before each finalize */
  2049. int outCount; /* Revert to stdout when reaching zero */
  2050. int cnt; /* Number of records displayed so far */
  2051. FILE *out; /* Write results here */
  2052. FILE *traceOut; /* Output for sqlite3_trace() */
  2053. int nErr; /* Number of errors seen */
  2054. int mode; /* An output mode setting */
  2055. int cMode; /* temporary output mode for the current query */
  2056. int normalMode; /* Output mode before ".explain on" */
  2057. int writableSchema; /* True if PRAGMA writable_schema=ON */
  2058. int showHeader; /* True to show column names in List or Column mode */
  2059. int nCheck; /* Number of ".check" commands run */
  2060. unsigned shellFlgs; /* Various flags */
  2061. char *zDestTable; /* Name of destination table when MODE_Insert */
  2062. char zTestcase[30]; /* Name of current test case */
  2063. char colSeparator[20]; /* Column separator character for several modes */
  2064. char rowSeparator[20]; /* Row separator character for MODE_Ascii */
  2065. int colWidth[100]; /* Requested width of each column when in column mode*/
  2066. int actualWidth[100]; /* Actual width of each column */
  2067. char nullValue[20]; /* The text to print when a NULL comes back from
  2068. ** the database */
  2069. char outfile[FILENAME_MAX]; /* Filename for *out */
  2070. const char *zDbFilename; /* name of the database file */
  2071. char *zFreeOnClose; /* Filename to free when closing */
  2072. const char *zVfs; /* Name of VFS to use */
  2073. sqlite3_stmt *pStmt; /* Current statement if any. */
  2074. FILE *pLog; /* Write log output here */
  2075. int *aiIndent; /* Array of indents used in MODE_Explain */
  2076. int nIndent; /* Size of array aiIndent[] */
  2077. int iIndent; /* Index of current op in aiIndent[] */
  2078. #if defined(SQLITE_ENABLE_SESSION)
  2079. int nSession; /* Number of active sessions */
  2080. OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
  2081. #endif
  2082. };
  2083. /*
  2084. ** These are the allowed shellFlgs values
  2085. */
  2086. #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
  2087. #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
  2088. #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
  2089. #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
  2090. #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
  2091. #define SHFLG_CountChanges 0x00000020 /* .changes setting */
  2092. #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
  2093. /*
  2094. ** Macros for testing and setting shellFlgs
  2095. */
  2096. #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
  2097. #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
  2098. #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
  2099. /*
  2100. ** These are the allowed modes.
  2101. */
  2102. #define MODE_Line 0 /* One column per line. Blank line between records */
  2103. #define MODE_Column 1 /* One record per line in neat columns */
  2104. #define MODE_List 2 /* One record per line with a separator */
  2105. #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
  2106. #define MODE_Html 4 /* Generate an XHTML table */
  2107. #define MODE_Insert 5 /* Generate SQL "insert" statements */
  2108. #define MODE_Quote 6 /* Quote values as for SQL */
  2109. #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
  2110. #define MODE_Csv 8 /* Quote strings, numbers are plain */
  2111. #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
  2112. #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
  2113. #define MODE_Pretty 11 /* Pretty-print schemas */
  2114. static const char *modeDescr[] = {
  2115. "line",
  2116. "column",
  2117. "list",
  2118. "semi",
  2119. "html",
  2120. "insert",
  2121. "quote",
  2122. "tcl",
  2123. "csv",
  2124. "explain",
  2125. "ascii",
  2126. "prettyprint",
  2127. };
  2128. /*
  2129. ** These are the column/row/line separators used by the various
  2130. ** import/export modes.
  2131. */
  2132. #define SEP_Column "|"
  2133. #define SEP_Row "\n"
  2134. #define SEP_Tab "\t"
  2135. #define SEP_Space " "
  2136. #define SEP_Comma ","
  2137. #define SEP_CrLf "\r\n"
  2138. #define SEP_Unit "\x1F"
  2139. #define SEP_Record "\x1E"
  2140. /*
  2141. ** Number of elements in an array
  2142. */
  2143. #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
  2144. /*
  2145. ** A callback for the sqlite3_log() interface.
  2146. */
  2147. static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  2148. ShellState *p = (ShellState*)pArg;
  2149. if( p->pLog==0 ) return;
  2150. utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  2151. fflush(p->pLog);
  2152. }
  2153. /*
  2154. ** Output the given string as a hex-encoded blob (eg. X'1234' )
  2155. */
  2156. static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  2157. int i;
  2158. char *zBlob = (char *)pBlob;
  2159. raw_printf(out,"X'");
  2160. for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
  2161. raw_printf(out,"'");
  2162. }
  2163. /*
  2164. ** Find a string that is not found anywhere in z[]. Return a pointer
  2165. ** to that string.
  2166. **
  2167. ** Try to use zA and zB first. If both of those are already found in z[]
  2168. ** then make up some string and store it in the buffer zBuf.
  2169. */
  2170. static const char *unused_string(
  2171. const char *z, /* Result must not appear anywhere in z */
  2172. const char *zA, const char *zB, /* Try these first */
  2173. char *zBuf /* Space to store a generated string */
  2174. ){
  2175. unsigned i = 0;
  2176. if( strstr(z, zA)==0 ) return zA;
  2177. if( strstr(z, zB)==0 ) return zB;
  2178. do{
  2179. sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
  2180. }while( strstr(z,zBuf)!=0 );
  2181. return zBuf;
  2182. }
  2183. /*
  2184. ** Output the given string as a quoted string using SQL quoting conventions.
  2185. **
  2186. ** See also: output_quoted_escaped_string()
  2187. */
  2188. static void output_quoted_string(FILE *out, const char *z){
  2189. int i;
  2190. char c;
  2191. setBinaryMode(out, 1);
  2192. for(i=0; (c = z[i])!=0 && c!='\''; i++){}
  2193. if( c==0 ){
  2194. utf8_printf(out,"'%s'",z);
  2195. }else{
  2196. raw_printf(out, "'");
  2197. while( *z ){
  2198. for(i=0; (c = z[i])!=0 && c!='\''; i++){}
  2199. if( c=='\'' ) i++;
  2200. if( i ){
  2201. utf8_printf(out, "%.*s", i, z);
  2202. z += i;
  2203. }
  2204. if( c=='\'' ){
  2205. raw_printf(out, "'");
  2206. continue;
  2207. }
  2208. if( c==0 ){
  2209. break;
  2210. }
  2211. z++;
  2212. }
  2213. raw_printf(out, "'");
  2214. }
  2215. setTextMode(out, 1);
  2216. }
  2217. /*
  2218. ** Output the given string as a quoted string using SQL quoting conventions.
  2219. ** Additionallly , escape the "\n" and "\r" characters so that they do not
  2220. ** get corrupted by end-of-line translation facilities in some operating
  2221. ** systems.
  2222. **
  2223. ** This is like output_quoted_string() but with the addition of the \r\n
  2224. ** escape mechanism.
  2225. */
  2226. static void output_quoted_escaped_string(FILE *out, const char *z){
  2227. int i;
  2228. char c;
  2229. setBinaryMode(out, 1);
  2230. for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
  2231. if( c==0 ){
  2232. utf8_printf(out,"'%s'",z);
  2233. }else{
  2234. const char *zNL = 0;
  2235. const char *zCR = 0;
  2236. int nNL = 0;
  2237. int nCR = 0;
  2238. char zBuf1[20], zBuf2[20];
  2239. for(i=0; z[i]; i++){
  2240. if( z[i]=='\n' ) nNL++;
  2241. if( z[i]=='\r' ) nCR++;
  2242. }
  2243. if( nNL ){
  2244. raw_printf(out, "replace(");
  2245. zNL = unused_string(z, "\\n", "\\012", zBuf1);
  2246. }
  2247. if( nCR ){
  2248. raw_printf(out, "replace(");
  2249. zCR = unused_string(z, "\\r", "\\015", zBuf2);
  2250. }
  2251. raw_printf(out, "'");
  2252. while( *z ){
  2253. for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
  2254. if( c=='\'' ) i++;
  2255. if( i ){
  2256. utf8_printf(out, "%.*s", i, z);
  2257. z += i;
  2258. }
  2259. if( c=='\'' ){
  2260. raw_printf(out, "'");
  2261. continue;
  2262. }
  2263. if( c==0 ){
  2264. break;
  2265. }
  2266. z++;
  2267. if( c=='\n' ){
  2268. raw_printf(out, "%s", zNL);
  2269. continue;
  2270. }
  2271. raw_printf(out, "%s", zCR);
  2272. }
  2273. raw_printf(out, "'");
  2274. if( nCR ){
  2275. raw_printf(out, ",'%s',char(13))", zCR);
  2276. }
  2277. if( nNL ){
  2278. raw_printf(out, ",'%s',char(10))", zNL);
  2279. }
  2280. }
  2281. setTextMode(out, 1);
  2282. }
  2283. /*
  2284. ** Output the given string as a quoted according to C or TCL quoting rules.
  2285. */
  2286. static void output_c_string(FILE *out, const char *z){
  2287. unsigned int c;
  2288. fputc('"', out);
  2289. while( (c = *(z++))!=0 ){
  2290. if( c=='\\' ){
  2291. fputc(c, out);
  2292. fputc(c, out);
  2293. }else if( c=='"' ){
  2294. fputc('\\', out);
  2295. fputc('"', out);
  2296. }else if( c=='\t' ){
  2297. fputc('\\', out);
  2298. fputc('t', out);
  2299. }else if( c=='\n' ){
  2300. fputc('\\', out);
  2301. fputc('n', out);
  2302. }else if( c=='\r' ){
  2303. fputc('\\', out);
  2304. fputc('r', out);
  2305. }else if( !isprint(c&0xff) ){
  2306. raw_printf(out, "\\%03o", c&0xff);
  2307. }else{
  2308. fputc(c, out);
  2309. }
  2310. }
  2311. fputc('"', out);
  2312. }
  2313. /*
  2314. ** Output the given string with characters that are special to
  2315. ** HTML escaped.
  2316. */
  2317. static void output_html_string(FILE *out, const char *z){
  2318. int i;
  2319. if( z==0 ) z = "";
  2320. while( *z ){
  2321. for(i=0; z[i]
  2322. && z[i]!='<'
  2323. && z[i]!='&'
  2324. && z[i]!='>'
  2325. && z[i]!='\"'
  2326. && z[i]!='\'';
  2327. i++){}
  2328. if( i>0 ){
  2329. utf8_printf(out,"%.*s",i,z);
  2330. }
  2331. if( z[i]=='<' ){
  2332. raw_printf(out,"&lt;");
  2333. }else if( z[i]=='&' ){
  2334. raw_printf(out,"&amp;");
  2335. }else if( z[i]=='>' ){
  2336. raw_printf(out,"&gt;");
  2337. }else if( z[i]=='\"' ){
  2338. raw_printf(out,"&quot;");
  2339. }else if( z[i]=='\'' ){
  2340. raw_printf(out,"&#39;");
  2341. }else{
  2342. break;
  2343. }
  2344. z += i + 1;
  2345. }
  2346. }
  2347. /*
  2348. ** If a field contains any character identified by a 1 in the following
  2349. ** array, then the string must be quoted for CSV.
  2350. */
  2351. static const char needCsvQuote[] = {
  2352. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  2353. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  2354. 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  2355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  2360. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  2361. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  2362. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  2363. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  2364. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  2365. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  2366. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  2367. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  2368. };
  2369. /*
  2370. ** Output a single term of CSV. Actually, p->colSeparator is used for
  2371. ** the separator, which may or may not be a comma. p->nullValue is
  2372. ** the null value. Strings are quoted if necessary. The separator
  2373. ** is only issued if bSep is true.
  2374. */
  2375. static void output_csv(ShellState *p, const char *z, int bSep){
  2376. FILE *out = p->out;
  2377. if( z==0 ){
  2378. utf8_printf(out,"%s",p->nullValue);
  2379. }else{
  2380. int i;
  2381. int nSep = strlen30(p->colSeparator);
  2382. for(i=0; z[i]; i++){
  2383. if( needCsvQuote[((unsigned char*)z)[i]]
  2384. || (z[i]==p->colSeparator[0] &&
  2385. (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
  2386. i = 0;
  2387. break;
  2388. }
  2389. }
  2390. if( i==0 ){
  2391. putc('"', out);
  2392. for(i=0; z[i]; i++){
  2393. if( z[i]=='"' ) putc('"', out);
  2394. putc(z[i], out);
  2395. }
  2396. putc('"', out);
  2397. }else{
  2398. utf8_printf(out, "%s", z);
  2399. }
  2400. }
  2401. if( bSep ){
  2402. utf8_printf(p->out, "%s", p->colSeparator);
  2403. }
  2404. }
  2405. #ifdef SIGINT
  2406. /*
  2407. ** This routine runs when the user presses Ctrl-C
  2408. */
  2409. static void interrupt_handler(int NotUsed){
  2410. UNUSED_PARAMETER(NotUsed);
  2411. seenInterrupt++;
  2412. if( seenInterrupt>2 ) exit(1);
  2413. if( globalDb ) sqlite3_interrupt(globalDb);
  2414. }
  2415. #endif
  2416. #ifndef SQLITE_OMIT_AUTHORIZATION
  2417. /*
  2418. ** When the ".auth ON" is set, the following authorizer callback is
  2419. ** invoked. It always returns SQLITE_OK.
  2420. */
  2421. static int shellAuth(
  2422. void *pClientData,
  2423. int op,
  2424. const char *zA1,
  2425. const char *zA2,
  2426. const char *zA3,
  2427. const char *zA4
  2428. ){
  2429. ShellState *p = (ShellState*)pClientData;
  2430. static const char *azAction[] = { 0,
  2431. "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
  2432. "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
  2433. "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
  2434. "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
  2435. "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
  2436. "DROP_TRIGGER", "DROP_VIEW", "INSERT",
  2437. "PRAGMA", "READ", "SELECT",
  2438. "TRANSACTION", "UPDATE", "ATTACH",
  2439. "DETACH", "ALTER_TABLE", "REINDEX",
  2440. "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
  2441. "FUNCTION", "SAVEPOINT", "RECURSIVE"
  2442. };
  2443. int i;
  2444. const char *az[4];
  2445. az[0] = zA1;
  2446. az[1] = zA2;
  2447. az[2] = zA3;
  2448. az[3] = zA4;
  2449. utf8_printf(p->out, "authorizer: %s", azAction[op]);
  2450. for(i=0; i<4; i++){
  2451. raw_printf(p->out, " ");
  2452. if( az[i] ){
  2453. output_c_string(p->out, az[i]);
  2454. }else{
  2455. raw_printf(p->out, "NULL");
  2456. }
  2457. }
  2458. raw_printf(p->out, "\n");
  2459. return SQLITE_OK;
  2460. }
  2461. #endif
  2462. /*
  2463. ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
  2464. **
  2465. ** This routine converts some CREATE TABLE statements for shadow tables
  2466. ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
  2467. */
  2468. static void printSchemaLine(FILE *out, const char *z, const char *zTail){
  2469. if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
  2470. utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
  2471. }else{
  2472. utf8_printf(out, "%s%s", z, zTail);
  2473. }
  2474. }
  2475. static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
  2476. char c = z[n];
  2477. z[n] = 0;
  2478. printSchemaLine(out, z, zTail);
  2479. z[n] = c;
  2480. }
  2481. /*
  2482. ** This is the callback routine that the shell
  2483. ** invokes for each row of a query result.
  2484. */
  2485. static int shell_callback(
  2486. void *pArg,
  2487. int nArg, /* Number of result columns */
  2488. char **azArg, /* Text of each result column */
  2489. char **azCol, /* Column names */
  2490. int *aiType /* Column types */
  2491. ){
  2492. int i;
  2493. ShellState *p = (ShellState*)pArg;
  2494. if( azArg==0 ) return 0;
  2495. switch( p->cMode ){
  2496. case MODE_Line: {
  2497. int w = 5;
  2498. if( azArg==0 ) break;
  2499. for(i=0; i<nArg; i++){
  2500. int len = strlen30(azCol[i] ? azCol[i] : "");
  2501. if( len>w ) w = len;
  2502. }
  2503. if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
  2504. for(i=0; i<nArg; i++){
  2505. utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
  2506. azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
  2507. }
  2508. break;
  2509. }
  2510. case MODE_Explain:
  2511. case MODE_Column: {
  2512. static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
  2513. const int *colWidth;
  2514. int showHdr;
  2515. char *rowSep;
  2516. if( p->cMode==MODE_Column ){
  2517. colWidth = p->colWidth;
  2518. showHdr = p->showHeader;
  2519. rowSep = p->rowSeparator;
  2520. }else{
  2521. colWidth = aExplainWidths;
  2522. showHdr = 1;
  2523. rowSep = SEP_Row;
  2524. }
  2525. if( p->cnt++==0 ){
  2526. for(i=0; i<nArg; i++){
  2527. int w, n;
  2528. if( i<ArraySize(p->colWidth) ){
  2529. w = colWidth[i];
  2530. }else{
  2531. w = 0;
  2532. }
  2533. if( w==0 ){
  2534. w = strlenChar(azCol[i] ? azCol[i] : "");
  2535. if( w<10 ) w = 10;
  2536. n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
  2537. if( w<n ) w = n;
  2538. }
  2539. if( i<ArraySize(p->actualWidth) ){
  2540. p->actualWidth[i] = w;
  2541. }
  2542. if( showHdr ){
  2543. utf8_width_print(p->out, w, azCol[i]);
  2544. utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
  2545. }
  2546. }
  2547. if( showHdr ){
  2548. for(i=0; i<nArg; i++){
  2549. int w;
  2550. if( i<ArraySize(p->actualWidth) ){
  2551. w = p->actualWidth[i];
  2552. if( w<0 ) w = -w;
  2553. }else{
  2554. w = 10;
  2555. }
  2556. utf8_printf(p->out,"%-*.*s%s",w,w,
  2557. "----------------------------------------------------------"
  2558. "----------------------------------------------------------",
  2559. i==nArg-1 ? rowSep : " ");
  2560. }
  2561. }
  2562. }
  2563. if( azArg==0 ) break;
  2564. for(i=0; i<nArg; i++){
  2565. int w;
  2566. if( i<ArraySize(p->actualWidth) ){
  2567. w = p->actualWidth[i];
  2568. }else{
  2569. w = 10;
  2570. }
  2571. if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
  2572. w = strlenChar(azArg[i]);
  2573. }
  2574. if( i==1 && p->aiIndent && p->pStmt ){
  2575. if( p->iIndent<p->nIndent ){
  2576. utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
  2577. }
  2578. p->iIndent++;
  2579. }
  2580. utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
  2581. utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
  2582. }
  2583. break;
  2584. }
  2585. case MODE_Semi: { /* .schema and .fullschema output */
  2586. printSchemaLine(p->out, azArg[0], ";\n");
  2587. break;
  2588. }
  2589. case MODE_Pretty: { /* .schema and .fullschema with --indent */
  2590. char *z;
  2591. int j;
  2592. int nParen = 0;
  2593. char cEnd = 0;
  2594. char c;
  2595. int nLine = 0;
  2596. assert( nArg==1 );
  2597. if( azArg[0]==0 ) break;
  2598. if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
  2599. || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
  2600. ){
  2601. utf8_printf(p->out, "%s;\n", azArg[0]);
  2602. break;
  2603. }
  2604. z = sqlite3_mprintf("%s", azArg[0]);
  2605. j = 0;
  2606. for(i=0; IsSpace(z[i]); i++){}
  2607. for(; (c = z[i])!=0; i++){
  2608. if( IsSpace(c) ){
  2609. if( z[j-1]=='\r' ) z[j-1] = '\n';
  2610. if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
  2611. }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
  2612. j--;
  2613. }
  2614. z[j++] = c;
  2615. }
  2616. while( j>0 && IsSpace(z[j-1]) ){ j--; }
  2617. z[j] = 0;
  2618. if( strlen30(z)>=79 ){
  2619. for(i=j=0; (c = z[i])!=0; i++){
  2620. if( c==cEnd ){
  2621. cEnd = 0;
  2622. }else if( c=='"' || c=='\'' || c=='`' ){
  2623. cEnd = c;
  2624. }else if( c=='[' ){
  2625. cEnd = ']';
  2626. }else if( c=='(' ){
  2627. nParen++;
  2628. }else if( c==')' ){
  2629. nParen--;
  2630. if( nLine>0 && nParen==0 && j>0 ){
  2631. printSchemaLineN(p->out, z, j, "\n");
  2632. j = 0;
  2633. }
  2634. }
  2635. z[j++] = c;
  2636. if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
  2637. if( c=='\n' ) j--;
  2638. printSchemaLineN(p->out, z, j, "\n ");
  2639. j = 0;
  2640. nLine++;
  2641. while( IsSpace(z[i+1]) ){ i++; }
  2642. }
  2643. }
  2644. z[j] = 0;
  2645. }
  2646. printSchemaLine(p->out, z, ";\n");
  2647. sqlite3_free(z);
  2648. break;
  2649. }
  2650. case MODE_List: {
  2651. if( p->cnt++==0 && p->showHeader ){
  2652. for(i=0; i<nArg; i++){
  2653. utf8_printf(p->out,"%s%s",azCol[i],
  2654. i==nArg-1 ? p->rowSeparator : p->colSeparator);
  2655. }
  2656. }
  2657. if( azArg==0 ) break;
  2658. for(i=0; i<nArg; i++){
  2659. char *z = azArg[i];
  2660. if( z==0 ) z = p->nullValue;
  2661. utf8_printf(p->out, "%s", z);
  2662. if( i<nArg-1 ){
  2663. utf8_printf(p->out, "%s", p->colSeparator);
  2664. }else{
  2665. utf8_printf(p->out, "%s", p->rowSeparator);
  2666. }
  2667. }
  2668. break;
  2669. }
  2670. case MODE_Html: {
  2671. if( p->cnt++==0 && p->showHeader ){
  2672. raw_printf(p->out,"<TR>");
  2673. for(i=0; i<nArg; i++){
  2674. raw_printf(p->out,"<TH>");
  2675. output_html_string(p->out, azCol[i]);
  2676. raw_printf(p->out,"</TH>\n");
  2677. }
  2678. raw_printf(p->out,"</TR>\n");
  2679. }
  2680. if( azArg==0 ) break;
  2681. raw_printf(p->out,"<TR>");
  2682. for(i=0; i<nArg; i++){
  2683. raw_printf(p->out,"<TD>");
  2684. output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  2685. raw_printf(p->out,"</TD>\n");
  2686. }
  2687. raw_printf(p->out,"</TR>\n");
  2688. break;
  2689. }
  2690. case MODE_Tcl: {
  2691. if( p->cnt++==0 && p->showHeader ){
  2692. for(i=0; i<nArg; i++){
  2693. output_c_string(p->out,azCol[i] ? azCol[i] : "");
  2694. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  2695. }
  2696. utf8_printf(p->out, "%s", p->rowSeparator);
  2697. }
  2698. if( azArg==0 ) break;
  2699. for(i=0; i<nArg; i++){
  2700. output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  2701. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  2702. }
  2703. utf8_printf(p->out, "%s", p->rowSeparator);
  2704. break;
  2705. }
  2706. case MODE_Csv: {
  2707. setBinaryMode(p->out, 1);
  2708. if( p->cnt++==0 && p->showHeader ){
  2709. for(i=0; i<nArg; i++){
  2710. output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  2711. }
  2712. utf8_printf(p->out, "%s", p->rowSeparator);
  2713. }
  2714. if( nArg>0 ){
  2715. for(i=0; i<nArg; i++){
  2716. output_csv(p, azArg[i], i<nArg-1);
  2717. }
  2718. utf8_printf(p->out, "%s", p->rowSeparator);
  2719. }
  2720. setTextMode(p->out, 1);
  2721. break;
  2722. }
  2723. case MODE_Insert: {
  2724. if( azArg==0 ) break;
  2725. utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
  2726. if( p->showHeader ){
  2727. raw_printf(p->out,"(");
  2728. for(i=0; i<nArg; i++){
  2729. if( i>0 ) raw_printf(p->out, ",");
  2730. if( quoteChar(azCol[i]) ){
  2731. char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
  2732. utf8_printf(p->out, "%s", z);
  2733. sqlite3_free(z);
  2734. }else{
  2735. raw_printf(p->out, "%s", azCol[i]);
  2736. }
  2737. }
  2738. raw_printf(p->out,")");
  2739. }
  2740. p->cnt++;
  2741. for(i=0; i<nArg; i++){
  2742. raw_printf(p->out, i>0 ? "," : " VALUES(");
  2743. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  2744. utf8_printf(p->out,"NULL");
  2745. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  2746. if( ShellHasFlag(p, SHFLG_Newlines) ){
  2747. output_quoted_string(p->out, azArg[i]);
  2748. }else{
  2749. output_quoted_escaped_string(p->out, azArg[i]);
  2750. }
  2751. }else if( aiType && aiType[i]==SQLITE_INTEGER ){
  2752. utf8_printf(p->out,"%s", azArg[i]);
  2753. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  2754. char z[50];
  2755. double r = sqlite3_column_double(p->pStmt, i);
  2756. sqlite3_snprintf(50,z,"%!.20g", r);
  2757. raw_printf(p->out, "%s", z);
  2758. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  2759. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  2760. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  2761. output_hex_blob(p->out, pBlob, nBlob);
  2762. }else if( isNumber(azArg[i], 0) ){
  2763. utf8_printf(p->out,"%s", azArg[i]);
  2764. }else if( ShellHasFlag(p, SHFLG_Newlines) ){
  2765. output_quoted_string(p->out, azArg[i]);
  2766. }else{
  2767. output_quoted_escaped_string(p->out, azArg[i]);
  2768. }
  2769. }
  2770. raw_printf(p->out,");\n");
  2771. break;
  2772. }
  2773. case MODE_Quote: {
  2774. if( azArg==0 ) break;
  2775. if( p->cnt==0 && p->showHeader ){
  2776. for(i=0; i<nArg; i++){
  2777. if( i>0 ) raw_printf(p->out, ",");
  2778. output_quoted_string(p->out, azCol[i]);
  2779. }
  2780. raw_printf(p->out,"\n");
  2781. }
  2782. p->cnt++;
  2783. for(i=0; i<nArg; i++){
  2784. if( i>0 ) raw_printf(p->out, ",");
  2785. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  2786. utf8_printf(p->out,"NULL");
  2787. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  2788. output_quoted_string(p->out, azArg[i]);
  2789. }else if( aiType && aiType[i]==SQLITE_INTEGER ){
  2790. utf8_printf(p->out,"%s", azArg[i]);
  2791. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  2792. char z[50];
  2793. double r = sqlite3_column_double(p->pStmt, i);
  2794. sqlite3_snprintf(50,z,"%!.20g", r);
  2795. raw_printf(p->out, "%s", z);
  2796. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  2797. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  2798. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  2799. output_hex_blob(p->out, pBlob, nBlob);
  2800. }else if( isNumber(azArg[i], 0) ){
  2801. utf8_printf(p->out,"%s", azArg[i]);
  2802. }else{
  2803. output_quoted_string(p->out, azArg[i]);
  2804. }
  2805. }
  2806. raw_printf(p->out,"\n");
  2807. break;
  2808. }
  2809. case MODE_Ascii: {
  2810. if( p->cnt++==0 && p->showHeader ){
  2811. for(i=0; i<nArg; i++){
  2812. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  2813. utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
  2814. }
  2815. utf8_printf(p->out, "%s", p->rowSeparator);
  2816. }
  2817. if( azArg==0 ) break;
  2818. for(i=0; i<nArg; i++){
  2819. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  2820. utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
  2821. }
  2822. utf8_printf(p->out, "%s", p->rowSeparator);
  2823. break;
  2824. }
  2825. }
  2826. return 0;
  2827. }
  2828. /*
  2829. ** This is the callback routine that the SQLite library
  2830. ** invokes for each row of a query result.
  2831. */
  2832. static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  2833. /* since we don't have type info, call the shell_callback with a NULL value */
  2834. return shell_callback(pArg, nArg, azArg, azCol, NULL);
  2835. }
  2836. /*
  2837. ** This is the callback routine from sqlite3_exec() that appends all
  2838. ** output onto the end of a ShellText object.
  2839. */
  2840. static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
  2841. ShellText *p = (ShellText*)pArg;
  2842. int i;
  2843. UNUSED_PARAMETER(az);
  2844. if( azArg==0 ) return 0;
  2845. if( p->n ) appendText(p, "|", 0);
  2846. for(i=0; i<nArg; i++){
  2847. if( i ) appendText(p, ",", 0);
  2848. if( azArg[i] ) appendText(p, azArg[i], 0);
  2849. }
  2850. return 0;
  2851. }
  2852. /*
  2853. ** Generate an appropriate SELFTEST table in the main database.
  2854. */
  2855. static void createSelftestTable(ShellState *p){
  2856. char *zErrMsg = 0;
  2857. sqlite3_exec(p->db,
  2858. "SAVEPOINT selftest_init;\n"
  2859. "CREATE TABLE IF NOT EXISTS selftest(\n"
  2860. " tno INTEGER PRIMARY KEY,\n" /* Test number */
  2861. " op TEXT,\n" /* Operator: memo run */
  2862. " cmd TEXT,\n" /* Command text */
  2863. " ans TEXT\n" /* Desired answer */
  2864. ");"
  2865. "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
  2866. "INSERT INTO [_shell$self](rowid,op,cmd)\n"
  2867. " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
  2868. " 'memo','Tests generated by --init');\n"
  2869. "INSERT INTO [_shell$self]\n"
  2870. " SELECT 'run',\n"
  2871. " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
  2872. "FROM sqlite_master ORDER BY 2'',224))',\n"
  2873. " hex(sha3_query('SELECT type,name,tbl_name,sql "
  2874. "FROM sqlite_master ORDER BY 2',224));\n"
  2875. "INSERT INTO [_shell$self]\n"
  2876. " SELECT 'run',"
  2877. " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
  2878. " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
  2879. " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
  2880. " FROM (\n"
  2881. " SELECT name FROM sqlite_master\n"
  2882. " WHERE type='table'\n"
  2883. " AND name<>'selftest'\n"
  2884. " AND coalesce(rootpage,0)>0\n"
  2885. " )\n"
  2886. " ORDER BY name;\n"
  2887. "INSERT INTO [_shell$self]\n"
  2888. " VALUES('run','PRAGMA integrity_check','ok');\n"
  2889. "INSERT INTO selftest(tno,op,cmd,ans)"
  2890. " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
  2891. "DROP TABLE [_shell$self];"
  2892. ,0,0,&zErrMsg);
  2893. if( zErrMsg ){
  2894. utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
  2895. sqlite3_free(zErrMsg);
  2896. }
  2897. sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
  2898. }
  2899. /*
  2900. ** Set the destination table field of the ShellState structure to
  2901. ** the name of the table given. Escape any quote characters in the
  2902. ** table name.
  2903. */
  2904. static void set_table_name(ShellState *p, const char *zName){
  2905. int i, n;
  2906. char cQuote;
  2907. char *z;
  2908. if( p->zDestTable ){
  2909. free(p->zDestTable);
  2910. p->zDestTable = 0;
  2911. }
  2912. if( zName==0 ) return;
  2913. cQuote = quoteChar(zName);
  2914. n = strlen30(zName);
  2915. if( cQuote ) n += n+2;
  2916. z = p->zDestTable = malloc( n+1 );
  2917. if( z==0 ){
  2918. raw_printf(stderr,"Error: out of memory\n");
  2919. exit(1);
  2920. }
  2921. n = 0;
  2922. if( cQuote ) z[n++] = cQuote;
  2923. for(i=0; zName[i]; i++){
  2924. z[n++] = zName[i];
  2925. if( zName[i]==cQuote ) z[n++] = cQuote;
  2926. }
  2927. if( cQuote ) z[n++] = cQuote;
  2928. z[n] = 0;
  2929. }
  2930. /*
  2931. ** Execute a query statement that will generate SQL output. Print
  2932. ** the result columns, comma-separated, on a line and then add a
  2933. ** semicolon terminator to the end of that line.
  2934. **
  2935. ** If the number of columns is 1 and that column contains text "--"
  2936. ** then write the semicolon on a separate line. That way, if a
  2937. ** "--" comment occurs at the end of the statement, the comment
  2938. ** won't consume the semicolon terminator.
  2939. */
  2940. static int run_table_dump_query(
  2941. ShellState *p, /* Query context */
  2942. const char *zSelect, /* SELECT statement to extract content */
  2943. const char *zFirstRow /* Print before first row, if not NULL */
  2944. ){
  2945. sqlite3_stmt *pSelect;
  2946. int rc;
  2947. int nResult;
  2948. int i;
  2949. const char *z;
  2950. rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
  2951. if( rc!=SQLITE_OK || !pSelect ){
  2952. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  2953. sqlite3_errmsg(p->db));
  2954. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  2955. return rc;
  2956. }
  2957. rc = sqlite3_step(pSelect);
  2958. nResult = sqlite3_column_count(pSelect);
  2959. while( rc==SQLITE_ROW ){
  2960. if( zFirstRow ){
  2961. utf8_printf(p->out, "%s", zFirstRow);
  2962. zFirstRow = 0;
  2963. }
  2964. z = (const char*)sqlite3_column_text(pSelect, 0);
  2965. utf8_printf(p->out, "%s", z);
  2966. for(i=1; i<nResult; i++){
  2967. utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
  2968. }
  2969. if( z==0 ) z = "";
  2970. while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
  2971. if( z[0] ){
  2972. raw_printf(p->out, "\n;\n");
  2973. }else{
  2974. raw_printf(p->out, ";\n");
  2975. }
  2976. rc = sqlite3_step(pSelect);
  2977. }
  2978. rc = sqlite3_finalize(pSelect);
  2979. if( rc!=SQLITE_OK ){
  2980. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  2981. sqlite3_errmsg(p->db));
  2982. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  2983. }
  2984. return rc;
  2985. }
  2986. /*
  2987. ** Allocate space and save off current error string.
  2988. */
  2989. static char *save_err_msg(
  2990. sqlite3 *db /* Database to query */
  2991. ){
  2992. int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
  2993. char *zErrMsg = sqlite3_malloc64(nErrMsg);
  2994. if( zErrMsg ){
  2995. memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
  2996. }
  2997. return zErrMsg;
  2998. }
  2999. #ifdef __linux__
  3000. /*
  3001. ** Attempt to display I/O stats on Linux using /proc/PID/io
  3002. */
  3003. static void displayLinuxIoStats(FILE *out){
  3004. FILE *in;
  3005. char z[200];
  3006. sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
  3007. in = fopen(z, "rb");
  3008. if( in==0 ) return;
  3009. while( fgets(z, sizeof(z), in)!=0 ){
  3010. static const struct {
  3011. const char *zPattern;
  3012. const char *zDesc;
  3013. } aTrans[] = {
  3014. { "rchar: ", "Bytes received by read():" },
  3015. { "wchar: ", "Bytes sent to write():" },
  3016. { "syscr: ", "Read() system calls:" },
  3017. { "syscw: ", "Write() system calls:" },
  3018. { "read_bytes: ", "Bytes read from storage:" },
  3019. { "write_bytes: ", "Bytes written to storage:" },
  3020. { "cancelled_write_bytes: ", "Cancelled write bytes:" },
  3021. };
  3022. int i;
  3023. for(i=0; i<ArraySize(aTrans); i++){
  3024. int n = (int)strlen(aTrans[i].zPattern);
  3025. if( strncmp(aTrans[i].zPattern, z, n)==0 ){
  3026. utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
  3027. break;
  3028. }
  3029. }
  3030. }
  3031. fclose(in);
  3032. }
  3033. #endif
  3034. /*
  3035. ** Display a single line of status using 64-bit values.
  3036. */
  3037. static void displayStatLine(
  3038. ShellState *p, /* The shell context */
  3039. char *zLabel, /* Label for this one line */
  3040. char *zFormat, /* Format for the result */
  3041. int iStatusCtrl, /* Which status to display */
  3042. int bReset /* True to reset the stats */
  3043. ){
  3044. sqlite3_int64 iCur = -1;
  3045. sqlite3_int64 iHiwtr = -1;
  3046. int i, nPercent;
  3047. char zLine[200];
  3048. sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
  3049. for(i=0, nPercent=0; zFormat[i]; i++){
  3050. if( zFormat[i]=='%' ) nPercent++;
  3051. }
  3052. if( nPercent>1 ){
  3053. sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
  3054. }else{
  3055. sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
  3056. }
  3057. raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
  3058. }
  3059. /*
  3060. ** Display memory stats.
  3061. */
  3062. static int display_stats(
  3063. sqlite3 *db, /* Database to query */
  3064. ShellState *pArg, /* Pointer to ShellState */
  3065. int bReset /* True to reset the stats */
  3066. ){
  3067. int iCur;
  3068. int iHiwtr;
  3069. if( pArg && pArg->out ){
  3070. displayStatLine(pArg, "Memory Used:",
  3071. "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
  3072. displayStatLine(pArg, "Number of Outstanding Allocations:",
  3073. "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
  3074. if( pArg->shellFlgs & SHFLG_Pagecache ){
  3075. displayStatLine(pArg, "Number of Pcache Pages Used:",
  3076. "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
  3077. }
  3078. displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
  3079. "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
  3080. displayStatLine(pArg, "Largest Allocation:",
  3081. "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
  3082. displayStatLine(pArg, "Largest Pcache Allocation:",
  3083. "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
  3084. #ifdef YYTRACKMAXSTACKDEPTH
  3085. displayStatLine(pArg, "Deepest Parser Stack:",
  3086. "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
  3087. #endif
  3088. }
  3089. if( pArg && pArg->out && db ){
  3090. if( pArg->shellFlgs & SHFLG_Lookaside ){
  3091. iHiwtr = iCur = -1;
  3092. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
  3093. &iCur, &iHiwtr, bReset);
  3094. raw_printf(pArg->out,
  3095. "Lookaside Slots Used: %d (max %d)\n",
  3096. iCur, iHiwtr);
  3097. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
  3098. &iCur, &iHiwtr, bReset);
  3099. raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
  3100. iHiwtr);
  3101. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
  3102. &iCur, &iHiwtr, bReset);
  3103. raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
  3104. iHiwtr);
  3105. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
  3106. &iCur, &iHiwtr, bReset);
  3107. raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
  3108. iHiwtr);
  3109. }
  3110. iHiwtr = iCur = -1;
  3111. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
  3112. raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
  3113. iCur);
  3114. iHiwtr = iCur = -1;
  3115. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
  3116. raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
  3117. iHiwtr = iCur = -1;
  3118. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
  3119. raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
  3120. iHiwtr = iCur = -1;
  3121. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
  3122. raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
  3123. iHiwtr = iCur = -1;
  3124. sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
  3125. raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
  3126. iCur);
  3127. iHiwtr = iCur = -1;
  3128. sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
  3129. raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
  3130. iCur);
  3131. }
  3132. if( pArg && pArg->out && db && pArg->pStmt ){
  3133. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
  3134. bReset);
  3135. raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
  3136. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
  3137. raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
  3138. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
  3139. raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
  3140. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
  3141. raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
  3142. }
  3143. #ifdef __linux__
  3144. displayLinuxIoStats(pArg->out);
  3145. #endif
  3146. /* Do not remove this machine readable comment: extra-stats-output-here */
  3147. return 0;
  3148. }
  3149. /*
  3150. ** Display scan stats.
  3151. */
  3152. static void display_scanstats(
  3153. sqlite3 *db, /* Database to query */
  3154. ShellState *pArg /* Pointer to ShellState */
  3155. ){
  3156. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  3157. UNUSED_PARAMETER(db);
  3158. UNUSED_PARAMETER(pArg);
  3159. #else
  3160. int i, k, n, mx;
  3161. raw_printf(pArg->out, "-------- scanstats --------\n");
  3162. mx = 0;
  3163. for(k=0; k<=mx; k++){
  3164. double rEstLoop = 1.0;
  3165. for(i=n=0; 1; i++){
  3166. sqlite3_stmt *p = pArg->pStmt;
  3167. sqlite3_int64 nLoop, nVisit;
  3168. double rEst;
  3169. int iSid;
  3170. const char *zExplain;
  3171. if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
  3172. break;
  3173. }
  3174. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
  3175. if( iSid>mx ) mx = iSid;
  3176. if( iSid!=k ) continue;
  3177. if( n==0 ){
  3178. rEstLoop = (double)nLoop;
  3179. if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
  3180. }
  3181. n++;
  3182. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
  3183. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
  3184. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
  3185. utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
  3186. rEstLoop *= rEst;
  3187. raw_printf(pArg->out,
  3188. " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
  3189. nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
  3190. );
  3191. }
  3192. }
  3193. raw_printf(pArg->out, "---------------------------\n");
  3194. #endif
  3195. }
  3196. /*
  3197. ** Parameter azArray points to a zero-terminated array of strings. zStr
  3198. ** points to a single nul-terminated string. Return non-zero if zStr
  3199. ** is equal, according to strcmp(), to any of the strings in the array.
  3200. ** Otherwise, return zero.
  3201. */
  3202. static int str_in_array(const char *zStr, const char **azArray){
  3203. int i;
  3204. for(i=0; azArray[i]; i++){
  3205. if( 0==strcmp(zStr, azArray[i]) ) return 1;
  3206. }
  3207. return 0;
  3208. }
  3209. /*
  3210. ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
  3211. ** and populate the ShellState.aiIndent[] array with the number of
  3212. ** spaces each opcode should be indented before it is output.
  3213. **
  3214. ** The indenting rules are:
  3215. **
  3216. ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
  3217. ** all opcodes that occur between the p2 jump destination and the opcode
  3218. ** itself by 2 spaces.
  3219. **
  3220. ** * For each "Goto", if the jump destination is earlier in the program
  3221. ** and ends on one of:
  3222. ** Yield SeekGt SeekLt RowSetRead Rewind
  3223. ** or if the P1 parameter is one instead of zero,
  3224. ** then indent all opcodes between the earlier instruction
  3225. ** and "Goto" by 2 spaces.
  3226. */
  3227. static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
  3228. const char *zSql; /* The text of the SQL statement */
  3229. const char *z; /* Used to check if this is an EXPLAIN */
  3230. int *abYield = 0; /* True if op is an OP_Yield */
  3231. int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
  3232. int iOp; /* Index of operation in p->aiIndent[] */
  3233. const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
  3234. "NextIfOpen", "PrevIfOpen", 0 };
  3235. const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
  3236. "Rewind", 0 };
  3237. const char *azGoto[] = { "Goto", 0 };
  3238. /* Try to figure out if this is really an EXPLAIN statement. If this
  3239. ** cannot be verified, return early. */
  3240. if( sqlite3_column_count(pSql)!=8 ){
  3241. p->cMode = p->mode;
  3242. return;
  3243. }
  3244. zSql = sqlite3_sql(pSql);
  3245. if( zSql==0 ) return;
  3246. for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
  3247. if( sqlite3_strnicmp(z, "explain", 7) ){
  3248. p->cMode = p->mode;
  3249. return;
  3250. }
  3251. for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
  3252. int i;
  3253. int iAddr = sqlite3_column_int(pSql, 0);
  3254. const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
  3255. /* Set p2 to the P2 field of the current opcode. Then, assuming that
  3256. ** p2 is an instruction address, set variable p2op to the index of that
  3257. ** instruction in the aiIndent[] array. p2 and p2op may be different if
  3258. ** the current instruction is part of a sub-program generated by an
  3259. ** SQL trigger or foreign key. */
  3260. int p2 = sqlite3_column_int(pSql, 3);
  3261. int p2op = (p2 + (iOp-iAddr));
  3262. /* Grow the p->aiIndent array as required */
  3263. if( iOp>=nAlloc ){
  3264. if( iOp==0 ){
  3265. /* Do further verfication that this is explain output. Abort if
  3266. ** it is not */
  3267. static const char *explainCols[] = {
  3268. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
  3269. int jj;
  3270. for(jj=0; jj<ArraySize(explainCols); jj++){
  3271. if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
  3272. p->cMode = p->mode;
  3273. sqlite3_reset(pSql);
  3274. return;
  3275. }
  3276. }
  3277. }
  3278. nAlloc += 100;
  3279. p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
  3280. abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
  3281. }
  3282. abYield[iOp] = str_in_array(zOp, azYield);
  3283. p->aiIndent[iOp] = 0;
  3284. p->nIndent = iOp+1;
  3285. if( str_in_array(zOp, azNext) ){
  3286. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  3287. }
  3288. if( str_in_array(zOp, azGoto) && p2op<p->nIndent
  3289. && (abYield[p2op] || sqlite3_column_int(pSql, 2))
  3290. ){
  3291. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  3292. }
  3293. }
  3294. p->iIndent = 0;
  3295. sqlite3_free(abYield);
  3296. sqlite3_reset(pSql);
  3297. }
  3298. /*
  3299. ** Free the array allocated by explain_data_prepare().
  3300. */
  3301. static void explain_data_delete(ShellState *p){
  3302. sqlite3_free(p->aiIndent);
  3303. p->aiIndent = 0;
  3304. p->nIndent = 0;
  3305. p->iIndent = 0;
  3306. }
  3307. /*
  3308. ** Disable and restore .wheretrace and .selecttrace settings.
  3309. */
  3310. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  3311. extern int sqlite3SelectTrace;
  3312. static int savedSelectTrace;
  3313. #endif
  3314. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  3315. extern int sqlite3WhereTrace;
  3316. static int savedWhereTrace;
  3317. #endif
  3318. static void disable_debug_trace_modes(void){
  3319. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  3320. savedSelectTrace = sqlite3SelectTrace;
  3321. sqlite3SelectTrace = 0;
  3322. #endif
  3323. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  3324. savedWhereTrace = sqlite3WhereTrace;
  3325. sqlite3WhereTrace = 0;
  3326. #endif
  3327. }
  3328. static void restore_debug_trace_modes(void){
  3329. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  3330. sqlite3SelectTrace = savedSelectTrace;
  3331. #endif
  3332. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  3333. sqlite3WhereTrace = savedWhereTrace;
  3334. #endif
  3335. }
  3336. /*
  3337. ** Run a prepared statement
  3338. */
  3339. static void exec_prepared_stmt(
  3340. ShellState *pArg, /* Pointer to ShellState */
  3341. sqlite3_stmt *pStmt, /* Statment to run */
  3342. int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
  3343. ){
  3344. int rc;
  3345. /* perform the first step. this will tell us if we
  3346. ** have a result set or not and how wide it is.
  3347. */
  3348. rc = sqlite3_step(pStmt);
  3349. /* if we have a result set... */
  3350. if( SQLITE_ROW == rc ){
  3351. /* if we have a callback... */
  3352. if( xCallback ){
  3353. /* allocate space for col name ptr, value ptr, and type */
  3354. int nCol = sqlite3_column_count(pStmt);
  3355. void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
  3356. if( !pData ){
  3357. rc = SQLITE_NOMEM;
  3358. }else{
  3359. char **azCols = (char **)pData; /* Names of result columns */
  3360. char **azVals = &azCols[nCol]; /* Results */
  3361. int *aiTypes = (int *)&azVals[nCol]; /* Result types */
  3362. int i, x;
  3363. assert(sizeof(int) <= sizeof(char *));
  3364. /* save off ptrs to column names */
  3365. for(i=0; i<nCol; i++){
  3366. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  3367. }
  3368. do{
  3369. /* extract the data and data types */
  3370. for(i=0; i<nCol; i++){
  3371. aiTypes[i] = x = sqlite3_column_type(pStmt, i);
  3372. if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
  3373. azVals[i] = "";
  3374. }else{
  3375. azVals[i] = (char*)sqlite3_column_text(pStmt, i);
  3376. }
  3377. if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
  3378. rc = SQLITE_NOMEM;
  3379. break; /* from for */
  3380. }
  3381. } /* end for */
  3382. /* if data and types extracted successfully... */
  3383. if( SQLITE_ROW == rc ){
  3384. /* call the supplied callback with the result row data */
  3385. if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
  3386. rc = SQLITE_ABORT;
  3387. }else{
  3388. rc = sqlite3_step(pStmt);
  3389. }
  3390. }
  3391. } while( SQLITE_ROW == rc );
  3392. sqlite3_free(pData);
  3393. }
  3394. }else{
  3395. do{
  3396. rc = sqlite3_step(pStmt);
  3397. } while( rc == SQLITE_ROW );
  3398. }
  3399. }
  3400. }
  3401. /*
  3402. ** Execute a statement or set of statements. Print
  3403. ** any result rows/columns depending on the current mode
  3404. ** set via the supplied callback.
  3405. **
  3406. ** This is very similar to SQLite's built-in sqlite3_exec()
  3407. ** function except it takes a slightly different callback
  3408. ** and callback data argument.
  3409. */
  3410. static int shell_exec(
  3411. sqlite3 *db, /* An open database */
  3412. const char *zSql, /* SQL to be evaluated */
  3413. int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
  3414. /* (not the same as sqlite3_exec) */
  3415. ShellState *pArg, /* Pointer to ShellState */
  3416. char **pzErrMsg /* Error msg written here */
  3417. ){
  3418. sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
  3419. int rc = SQLITE_OK; /* Return Code */
  3420. int rc2;
  3421. const char *zLeftover; /* Tail of unprocessed SQL */
  3422. if( pzErrMsg ){
  3423. *pzErrMsg = NULL;
  3424. }
  3425. while( zSql[0] && (SQLITE_OK == rc) ){
  3426. static const char *zStmtSql;
  3427. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  3428. if( SQLITE_OK != rc ){
  3429. if( pzErrMsg ){
  3430. *pzErrMsg = save_err_msg(db);
  3431. }
  3432. }else{
  3433. if( !pStmt ){
  3434. /* this happens for a comment or white-space */
  3435. zSql = zLeftover;
  3436. while( IsSpace(zSql[0]) ) zSql++;
  3437. continue;
  3438. }
  3439. zStmtSql = sqlite3_sql(pStmt);
  3440. if( zStmtSql==0 ) zStmtSql = "";
  3441. while( IsSpace(zStmtSql[0]) ) zStmtSql++;
  3442. /* save off the prepared statment handle and reset row count */
  3443. if( pArg ){
  3444. pArg->pStmt = pStmt;
  3445. pArg->cnt = 0;
  3446. }
  3447. /* echo the sql statement if echo on */
  3448. if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
  3449. utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  3450. }
  3451. /* Show the EXPLAIN QUERY PLAN if .eqp is on */
  3452. if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
  3453. sqlite3_stmt *pExplain;
  3454. char *zEQP;
  3455. disable_debug_trace_modes();
  3456. zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
  3457. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  3458. if( rc==SQLITE_OK ){
  3459. while( sqlite3_step(pExplain)==SQLITE_ROW ){
  3460. raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
  3461. raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
  3462. raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
  3463. utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
  3464. }
  3465. }
  3466. sqlite3_finalize(pExplain);
  3467. sqlite3_free(zEQP);
  3468. if( pArg->autoEQP>=2 ){
  3469. /* Also do an EXPLAIN for ".eqp full" mode */
  3470. zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
  3471. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  3472. if( rc==SQLITE_OK ){
  3473. pArg->cMode = MODE_Explain;
  3474. explain_data_prepare(pArg, pExplain);
  3475. exec_prepared_stmt(pArg, pExplain, xCallback);
  3476. explain_data_delete(pArg);
  3477. }
  3478. sqlite3_finalize(pExplain);
  3479. sqlite3_free(zEQP);
  3480. }
  3481. restore_debug_trace_modes();
  3482. }
  3483. if( pArg ){
  3484. pArg->cMode = pArg->mode;
  3485. if( pArg->autoExplain
  3486. && sqlite3_column_count(pStmt)==8
  3487. && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
  3488. ){
  3489. pArg->cMode = MODE_Explain;
  3490. }
  3491. /* If the shell is currently in ".explain" mode, gather the extra
  3492. ** data required to add indents to the output.*/
  3493. if( pArg->cMode==MODE_Explain ){
  3494. explain_data_prepare(pArg, pStmt);
  3495. }
  3496. }
  3497. exec_prepared_stmt(pArg, pStmt, xCallback);
  3498. explain_data_delete(pArg);
  3499. /* print usage stats if stats on */
  3500. if( pArg && pArg->statsOn ){
  3501. display_stats(db, pArg, 0);
  3502. }
  3503. /* print loop-counters if required */
  3504. if( pArg && pArg->scanstatsOn ){
  3505. display_scanstats(db, pArg);
  3506. }
  3507. /* Finalize the statement just executed. If this fails, save a
  3508. ** copy of the error message. Otherwise, set zSql to point to the
  3509. ** next statement to execute. */
  3510. rc2 = sqlite3_finalize(pStmt);
  3511. if( rc!=SQLITE_NOMEM ) rc = rc2;
  3512. if( rc==SQLITE_OK ){
  3513. zSql = zLeftover;
  3514. while( IsSpace(zSql[0]) ) zSql++;
  3515. }else if( pzErrMsg ){
  3516. *pzErrMsg = save_err_msg(db);
  3517. }
  3518. /* clear saved stmt handle */
  3519. if( pArg ){
  3520. pArg->pStmt = NULL;
  3521. }
  3522. }
  3523. } /* end while */
  3524. return rc;
  3525. }
  3526. /*
  3527. ** Release memory previously allocated by tableColumnList().
  3528. */
  3529. static void freeColumnList(char **azCol){
  3530. int i;
  3531. for(i=1; azCol[i]; i++){
  3532. sqlite3_free(azCol[i]);
  3533. }
  3534. /* azCol[0] is a static string */
  3535. sqlite3_free(azCol);
  3536. }
  3537. /*
  3538. ** Return a list of pointers to strings which are the names of all
  3539. ** columns in table zTab. The memory to hold the names is dynamically
  3540. ** allocated and must be released by the caller using a subsequent call
  3541. ** to freeColumnList().
  3542. **
  3543. ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
  3544. ** value that needs to be preserved, then azCol[0] is filled in with the
  3545. ** name of the rowid column.
  3546. **
  3547. ** The first regular column in the table is azCol[1]. The list is terminated
  3548. ** by an entry with azCol[i]==0.
  3549. */
  3550. static char **tableColumnList(ShellState *p, const char *zTab){
  3551. char **azCol = 0;
  3552. sqlite3_stmt *pStmt;
  3553. char *zSql;
  3554. int nCol = 0;
  3555. int nAlloc = 0;
  3556. int nPK = 0; /* Number of PRIMARY KEY columns seen */
  3557. int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
  3558. int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
  3559. int rc;
  3560. zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
  3561. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3562. sqlite3_free(zSql);
  3563. if( rc ) return 0;
  3564. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  3565. if( nCol>=nAlloc-2 ){
  3566. nAlloc = nAlloc*2 + nCol + 10;
  3567. azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
  3568. if( azCol==0 ){
  3569. raw_printf(stderr, "Error: out of memory\n");
  3570. exit(1);
  3571. }
  3572. }
  3573. azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
  3574. if( sqlite3_column_int(pStmt, 5) ){
  3575. nPK++;
  3576. if( nPK==1
  3577. && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
  3578. "INTEGER")==0
  3579. ){
  3580. isIPK = 1;
  3581. }else{
  3582. isIPK = 0;
  3583. }
  3584. }
  3585. }
  3586. sqlite3_finalize(pStmt);
  3587. if( azCol==0 ) return 0;
  3588. azCol[0] = 0;
  3589. azCol[nCol+1] = 0;
  3590. /* The decision of whether or not a rowid really needs to be preserved
  3591. ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
  3592. ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
  3593. ** rowids on tables where the rowid is inaccessible because there are other
  3594. ** columns in the table named "rowid", "_rowid_", and "oid".
  3595. */
  3596. if( preserveRowid && isIPK ){
  3597. /* If a single PRIMARY KEY column with type INTEGER was seen, then it
  3598. ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
  3599. ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
  3600. ** ROWID aliases. To distinguish these cases, check to see if
  3601. ** there is a "pk" entry in "PRAGMA index_list". There will be
  3602. ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
  3603. */
  3604. zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
  3605. " WHERE origin='pk'", zTab);
  3606. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3607. sqlite3_free(zSql);
  3608. if( rc ){
  3609. freeColumnList(azCol);
  3610. return 0;
  3611. }
  3612. rc = sqlite3_step(pStmt);
  3613. sqlite3_finalize(pStmt);
  3614. preserveRowid = rc==SQLITE_ROW;
  3615. }
  3616. if( preserveRowid ){
  3617. /* Only preserve the rowid if we can find a name to use for the
  3618. ** rowid */
  3619. static char *azRowid[] = { "rowid", "_rowid_", "oid" };
  3620. int i, j;
  3621. for(j=0; j<3; j++){
  3622. for(i=1; i<=nCol; i++){
  3623. if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
  3624. }
  3625. if( i>nCol ){
  3626. /* At this point, we know that azRowid[j] is not the name of any
  3627. ** ordinary column in the table. Verify that azRowid[j] is a valid
  3628. ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
  3629. ** tables will fail this last check */
  3630. rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
  3631. if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
  3632. break;
  3633. }
  3634. }
  3635. }
  3636. return azCol;
  3637. }
  3638. /*
  3639. ** Toggle the reverse_unordered_selects setting.
  3640. */
  3641. static void toggleSelectOrder(sqlite3 *db){
  3642. sqlite3_stmt *pStmt = 0;
  3643. int iSetting = 0;
  3644. char zStmt[100];
  3645. sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
  3646. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  3647. iSetting = sqlite3_column_int(pStmt, 0);
  3648. }
  3649. sqlite3_finalize(pStmt);
  3650. sqlite3_snprintf(sizeof(zStmt), zStmt,
  3651. "PRAGMA reverse_unordered_selects(%d)", !iSetting);
  3652. sqlite3_exec(db, zStmt, 0, 0, 0);
  3653. }
  3654. /*
  3655. ** This is a different callback routine used for dumping the database.
  3656. ** Each row received by this callback consists of a table name,
  3657. ** the table type ("index" or "table") and SQL to create the table.
  3658. ** This routine should print text sufficient to recreate the table.
  3659. */
  3660. static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
  3661. int rc;
  3662. const char *zTable;
  3663. const char *zType;
  3664. const char *zSql;
  3665. ShellState *p = (ShellState *)pArg;
  3666. UNUSED_PARAMETER(azNotUsed);
  3667. if( nArg!=3 || azArg==0 ) return 0;
  3668. zTable = azArg[0];
  3669. zType = azArg[1];
  3670. zSql = azArg[2];
  3671. if( strcmp(zTable, "sqlite_sequence")==0 ){
  3672. raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
  3673. }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
  3674. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  3675. }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  3676. return 0;
  3677. }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  3678. char *zIns;
  3679. if( !p->writableSchema ){
  3680. raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
  3681. p->writableSchema = 1;
  3682. }
  3683. zIns = sqlite3_mprintf(
  3684. "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
  3685. "VALUES('table','%q','%q',0,'%q');",
  3686. zTable, zTable, zSql);
  3687. utf8_printf(p->out, "%s\n", zIns);
  3688. sqlite3_free(zIns);
  3689. return 0;
  3690. }else{
  3691. printSchemaLine(p->out, zSql, ";\n");
  3692. }
  3693. if( strcmp(zType, "table")==0 ){
  3694. ShellText sSelect;
  3695. ShellText sTable;
  3696. char **azCol;
  3697. int i;
  3698. char *savedDestTable;
  3699. int savedMode;
  3700. azCol = tableColumnList(p, zTable);
  3701. if( azCol==0 ){
  3702. p->nErr++;
  3703. return 0;
  3704. }
  3705. /* Always quote the table name, even if it appears to be pure ascii,
  3706. ** in case it is a keyword. Ex: INSERT INTO "table" ... */
  3707. initText(&sTable);
  3708. appendText(&sTable, zTable, quoteChar(zTable));
  3709. /* If preserving the rowid, add a column list after the table name.
  3710. ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
  3711. ** instead of the usual "INSERT INTO tab VALUES(...)".
  3712. */
  3713. if( azCol[0] ){
  3714. appendText(&sTable, "(", 0);
  3715. appendText(&sTable, azCol[0], 0);
  3716. for(i=1; azCol[i]; i++){
  3717. appendText(&sTable, ",", 0);
  3718. appendText(&sTable, azCol[i], quoteChar(azCol[i]));
  3719. }
  3720. appendText(&sTable, ")", 0);
  3721. }
  3722. /* Build an appropriate SELECT statement */
  3723. initText(&sSelect);
  3724. appendText(&sSelect, "SELECT ", 0);
  3725. if( azCol[0] ){
  3726. appendText(&sSelect, azCol[0], 0);
  3727. appendText(&sSelect, ",", 0);
  3728. }
  3729. for(i=1; azCol[i]; i++){
  3730. appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
  3731. if( azCol[i+1] ){
  3732. appendText(&sSelect, ",", 0);
  3733. }
  3734. }
  3735. freeColumnList(azCol);
  3736. appendText(&sSelect, " FROM ", 0);
  3737. appendText(&sSelect, zTable, quoteChar(zTable));
  3738. savedDestTable = p->zDestTable;
  3739. savedMode = p->mode;
  3740. p->zDestTable = sTable.z;
  3741. p->mode = p->cMode = MODE_Insert;
  3742. rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
  3743. if( (rc&0xff)==SQLITE_CORRUPT ){
  3744. raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  3745. toggleSelectOrder(p->db);
  3746. shell_exec(p->db, sSelect.z, shell_callback, p, 0);
  3747. toggleSelectOrder(p->db);
  3748. }
  3749. p->zDestTable = savedDestTable;
  3750. p->mode = savedMode;
  3751. freeText(&sTable);
  3752. freeText(&sSelect);
  3753. if( rc ) p->nErr++;
  3754. }
  3755. return 0;
  3756. }
  3757. /*
  3758. ** Run zQuery. Use dump_callback() as the callback routine so that
  3759. ** the contents of the query are output as SQL statements.
  3760. **
  3761. ** If we get a SQLITE_CORRUPT error, rerun the query after appending
  3762. ** "ORDER BY rowid DESC" to the end.
  3763. */
  3764. static int run_schema_dump_query(
  3765. ShellState *p,
  3766. const char *zQuery
  3767. ){
  3768. int rc;
  3769. char *zErr = 0;
  3770. rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
  3771. if( rc==SQLITE_CORRUPT ){
  3772. char *zQ2;
  3773. int len = strlen30(zQuery);
  3774. raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  3775. if( zErr ){
  3776. utf8_printf(p->out, "/****** %s ******/\n", zErr);
  3777. sqlite3_free(zErr);
  3778. zErr = 0;
  3779. }
  3780. zQ2 = malloc( len+100 );
  3781. if( zQ2==0 ) return rc;
  3782. sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
  3783. rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
  3784. if( rc ){
  3785. utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
  3786. }else{
  3787. rc = SQLITE_CORRUPT;
  3788. }
  3789. sqlite3_free(zErr);
  3790. free(zQ2);
  3791. }
  3792. return rc;
  3793. }
  3794. /*
  3795. ** Text of a help message
  3796. */
  3797. static char zHelp[] =
  3798. #ifndef SQLITE_OMIT_AUTHORIZATION
  3799. ".auth ON|OFF Show authorizer callbacks\n"
  3800. #endif
  3801. ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
  3802. ".bail on|off Stop after hitting an error. Default OFF\n"
  3803. ".binary on|off Turn binary output on or off. Default OFF\n"
  3804. ".cd DIRECTORY Change the working directory to DIRECTORY\n"
  3805. ".changes on|off Show number of rows changed by SQL\n"
  3806. ".check GLOB Fail if output since .testcase does not match\n"
  3807. ".clone NEWDB Clone data into NEWDB from the existing database\n"
  3808. ".databases List names and files of attached databases\n"
  3809. ".dbinfo ?DB? Show status information about the database\n"
  3810. ".dump ?TABLE? ... Dump the database in an SQL text format\n"
  3811. " If TABLE specified, only dump tables matching\n"
  3812. " LIKE pattern TABLE.\n"
  3813. ".echo on|off Turn command echo on or off\n"
  3814. ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
  3815. ".exit Exit this program\n"
  3816. /* Because explain mode comes on automatically now, the ".explain" mode
  3817. ** is removed from the help screen. It is still supported for legacy, however */
  3818. /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
  3819. ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
  3820. ".headers on|off Turn display of headers on or off\n"
  3821. ".help Show this message\n"
  3822. ".import FILE TABLE Import data from FILE into TABLE\n"
  3823. #ifndef SQLITE_OMIT_TEST_CONTROL
  3824. ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
  3825. #endif
  3826. ".indexes ?TABLE? Show names of all indexes\n"
  3827. " If TABLE specified, only show indexes for tables\n"
  3828. " matching LIKE pattern TABLE.\n"
  3829. #ifdef SQLITE_ENABLE_IOTRACE
  3830. ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
  3831. #endif
  3832. ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
  3833. ".lint OPTIONS Report potential schema issues. Options:\n"
  3834. " fkey-indexes Find missing foreign key indexes\n"
  3835. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  3836. ".load FILE ?ENTRY? Load an extension library\n"
  3837. #endif
  3838. ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
  3839. ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
  3840. " ascii Columns/rows delimited by 0x1F and 0x1E\n"
  3841. " csv Comma-separated values\n"
  3842. " column Left-aligned columns. (See .width)\n"
  3843. " html HTML <table> code\n"
  3844. " insert SQL insert statements for TABLE\n"
  3845. " line One value per line\n"
  3846. " list Values delimited by \"|\"\n"
  3847. " quote Escape answers as for SQL\n"
  3848. " tabs Tab-separated values\n"
  3849. " tcl TCL list elements\n"
  3850. ".nullvalue STRING Use STRING in place of NULL values\n"
  3851. ".once FILENAME Output for the next SQL command only to FILENAME\n"
  3852. ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
  3853. " The --new option starts with an empty file\n"
  3854. ".output ?FILENAME? Send output to FILENAME or stdout\n"
  3855. ".print STRING... Print literal STRING\n"
  3856. ".prompt MAIN CONTINUE Replace the standard prompts\n"
  3857. ".quit Exit this program\n"
  3858. ".read FILENAME Execute SQL in FILENAME\n"
  3859. ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
  3860. ".save FILE Write in-memory database into FILE\n"
  3861. ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
  3862. ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
  3863. " Add --indent for pretty-printing\n"
  3864. ".selftest ?--init? Run tests defined in the SELFTEST table\n"
  3865. ".separator COL ?ROW? Change the column separator and optionally the row\n"
  3866. " separator for both the output mode and .import\n"
  3867. #if defined(SQLITE_ENABLE_SESSION)
  3868. ".session CMD ... Create or control sessions\n"
  3869. #endif
  3870. ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
  3871. ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
  3872. ".show Show the current values for various settings\n"
  3873. ".stats ?on|off? Show stats or turn stats on or off\n"
  3874. ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
  3875. ".tables ?TABLE? List names of tables\n"
  3876. " If TABLE specified, only list tables matching\n"
  3877. " LIKE pattern TABLE.\n"
  3878. ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
  3879. ".timeout MS Try opening locked tables for MS milliseconds\n"
  3880. ".timer on|off Turn SQL timer on or off\n"
  3881. ".trace FILE|off Output each SQL statement as it is run\n"
  3882. ".vfsinfo ?AUX? Information about the top-level VFS\n"
  3883. ".vfslist List all available VFSes\n"
  3884. ".vfsname ?AUX? Print the name of the VFS stack\n"
  3885. ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
  3886. " Negative values right-justify\n"
  3887. ;
  3888. #if defined(SQLITE_ENABLE_SESSION)
  3889. /*
  3890. ** Print help information for the ".sessions" command
  3891. */
  3892. void session_help(ShellState *p){
  3893. raw_printf(p->out,
  3894. ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
  3895. "If ?NAME? is omitted, the first defined session is used.\n"
  3896. "Subcommands:\n"
  3897. " attach TABLE Attach TABLE\n"
  3898. " changeset FILE Write a changeset into FILE\n"
  3899. " close Close one session\n"
  3900. " enable ?BOOLEAN? Set or query the enable bit\n"
  3901. " filter GLOB... Reject tables matching GLOBs\n"
  3902. " indirect ?BOOLEAN? Mark or query the indirect status\n"
  3903. " isempty Query whether the session is empty\n"
  3904. " list List currently open session names\n"
  3905. " open DB NAME Open a new session on DB\n"
  3906. " patchset FILE Write a patchset into FILE\n"
  3907. );
  3908. }
  3909. #endif
  3910. /* Forward reference */
  3911. static int process_input(ShellState *p, FILE *in);
  3912. /*
  3913. ** Read the content of file zName into memory obtained from sqlite3_malloc64()
  3914. ** and return a pointer to the buffer. The caller is responsible for freeing
  3915. ** the memory.
  3916. **
  3917. ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
  3918. ** read.
  3919. **
  3920. ** For convenience, a nul-terminator byte is always appended to the data read
  3921. ** from the file before the buffer is returned. This byte is not included in
  3922. ** the final value of (*pnByte), if applicable.
  3923. **
  3924. ** NULL is returned if any error is encountered. The final value of *pnByte
  3925. ** is undefined in this case.
  3926. */
  3927. static char *readFile(const char *zName, int *pnByte){
  3928. FILE *in = fopen(zName, "rb");
  3929. long nIn;
  3930. size_t nRead;
  3931. char *pBuf;
  3932. if( in==0 ) return 0;
  3933. fseek(in, 0, SEEK_END);
  3934. nIn = ftell(in);
  3935. rewind(in);
  3936. pBuf = sqlite3_malloc64( nIn+1 );
  3937. if( pBuf==0 ) return 0;
  3938. nRead = fread(pBuf, nIn, 1, in);
  3939. fclose(in);
  3940. if( nRead!=1 ){
  3941. sqlite3_free(pBuf);
  3942. return 0;
  3943. }
  3944. pBuf[nIn] = 0;
  3945. if( pnByte ) *pnByte = nIn;
  3946. return pBuf;
  3947. }
  3948. #if defined(SQLITE_ENABLE_SESSION)
  3949. /*
  3950. ** Close a single OpenSession object and release all of its associated
  3951. ** resources.
  3952. */
  3953. static void session_close(OpenSession *pSession){
  3954. int i;
  3955. sqlite3session_delete(pSession->p);
  3956. sqlite3_free(pSession->zName);
  3957. for(i=0; i<pSession->nFilter; i++){
  3958. sqlite3_free(pSession->azFilter[i]);
  3959. }
  3960. sqlite3_free(pSession->azFilter);
  3961. memset(pSession, 0, sizeof(OpenSession));
  3962. }
  3963. #endif
  3964. /*
  3965. ** Close all OpenSession objects and release all associated resources.
  3966. */
  3967. #if defined(SQLITE_ENABLE_SESSION)
  3968. static void session_close_all(ShellState *p){
  3969. int i;
  3970. for(i=0; i<p->nSession; i++){
  3971. session_close(&p->aSession[i]);
  3972. }
  3973. p->nSession = 0;
  3974. }
  3975. #else
  3976. # define session_close_all(X)
  3977. #endif
  3978. /*
  3979. ** Implementation of the xFilter function for an open session. Omit
  3980. ** any tables named by ".session filter" but let all other table through.
  3981. */
  3982. #if defined(SQLITE_ENABLE_SESSION)
  3983. static int session_filter(void *pCtx, const char *zTab){
  3984. OpenSession *pSession = (OpenSession*)pCtx;
  3985. int i;
  3986. for(i=0; i<pSession->nFilter; i++){
  3987. if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
  3988. }
  3989. return 1;
  3990. }
  3991. #endif
  3992. /*
  3993. ** Make sure the database is open. If it is not, then open it. If
  3994. ** the database fails to open, print an error message and exit.
  3995. */
  3996. static void open_db(ShellState *p, int keepAlive){
  3997. if( p->db==0 ){
  3998. sqlite3_initialize();
  3999. sqlite3_open(p->zDbFilename, &p->db);
  4000. globalDb = p->db;
  4001. if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
  4002. utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
  4003. p->zDbFilename, sqlite3_errmsg(p->db));
  4004. if( keepAlive ) return;
  4005. exit(1);
  4006. }
  4007. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  4008. sqlite3_enable_load_extension(p->db, 1);
  4009. #endif
  4010. sqlite3_fileio_init(p->db, 0, 0);
  4011. sqlite3_shathree_init(p->db, 0, 0);
  4012. sqlite3_completion_init(p->db, 0, 0);
  4013. sqlite3_create_function(p->db, "shell_add_schema", 2, SQLITE_UTF8, 0,
  4014. shellAddSchemaName, 0, 0);
  4015. }
  4016. }
  4017. #if HAVE_READLINE || HAVE_EDITLINE
  4018. /*
  4019. ** Readline completion callbacks
  4020. */
  4021. static char *readline_completion_generator(const char *text, int state){
  4022. static sqlite3_stmt *pStmt = 0;
  4023. char *zRet;
  4024. if( state==0 ){
  4025. char *zSql;
  4026. sqlite3_finalize(pStmt);
  4027. zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
  4028. " FROM completion(%Q) ORDER BY 1", text);
  4029. sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
  4030. sqlite3_free(zSql);
  4031. }
  4032. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  4033. zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
  4034. }else{
  4035. sqlite3_finalize(pStmt);
  4036. pStmt = 0;
  4037. zRet = 0;
  4038. }
  4039. return zRet;
  4040. }
  4041. static char **readline_completion(const char *zText, int iStart, int iEnd){
  4042. rl_attempted_completion_over = 1;
  4043. return rl_completion_matches(zText, readline_completion_generator);
  4044. }
  4045. #elif HAVE_LINENOISE
  4046. /*
  4047. ** Linenoise completion callback
  4048. */
  4049. static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
  4050. int nLine = (int)strlen(zLine);
  4051. int i, iStart;
  4052. sqlite3_stmt *pStmt = 0;
  4053. char *zSql;
  4054. char zBuf[1000];
  4055. if( nLine>sizeof(zBuf)-30 ) return;
  4056. if( zLine[0]=='.' ) return;
  4057. for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
  4058. if( i==nLine-1 ) return;
  4059. iStart = i+1;
  4060. memcpy(zBuf, zLine, iStart);
  4061. zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
  4062. " FROM completion(%Q,%Q) ORDER BY 1",
  4063. &zLine[iStart], zLine);
  4064. sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
  4065. sqlite3_free(zSql);
  4066. sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
  4067. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  4068. const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
  4069. int nCompletion = sqlite3_column_bytes(pStmt, 0);
  4070. if( iStart+nCompletion < sizeof(zBuf)-1 ){
  4071. memcpy(zBuf+iStart, zCompletion, nCompletion+1);
  4072. linenoiseAddCompletion(lc, zBuf);
  4073. }
  4074. }
  4075. sqlite3_finalize(pStmt);
  4076. }
  4077. #endif
  4078. /*
  4079. ** Do C-language style dequoting.
  4080. **
  4081. ** \a -> alarm
  4082. ** \b -> backspace
  4083. ** \t -> tab
  4084. ** \n -> newline
  4085. ** \v -> vertical tab
  4086. ** \f -> form feed
  4087. ** \r -> carriage return
  4088. ** \s -> space
  4089. ** \" -> "
  4090. ** \' -> '
  4091. ** \\ -> backslash
  4092. ** \NNN -> ascii character NNN in octal
  4093. */
  4094. static void resolve_backslashes(char *z){
  4095. int i, j;
  4096. char c;
  4097. while( *z && *z!='\\' ) z++;
  4098. for(i=j=0; (c = z[i])!=0; i++, j++){
  4099. if( c=='\\' && z[i+1]!=0 ){
  4100. c = z[++i];
  4101. if( c=='a' ){
  4102. c = '\a';
  4103. }else if( c=='b' ){
  4104. c = '\b';
  4105. }else if( c=='t' ){
  4106. c = '\t';
  4107. }else if( c=='n' ){
  4108. c = '\n';
  4109. }else if( c=='v' ){
  4110. c = '\v';
  4111. }else if( c=='f' ){
  4112. c = '\f';
  4113. }else if( c=='r' ){
  4114. c = '\r';
  4115. }else if( c=='"' ){
  4116. c = '"';
  4117. }else if( c=='\'' ){
  4118. c = '\'';
  4119. }else if( c=='\\' ){
  4120. c = '\\';
  4121. }else if( c>='0' && c<='7' ){
  4122. c -= '0';
  4123. if( z[i+1]>='0' && z[i+1]<='7' ){
  4124. i++;
  4125. c = (c<<3) + z[i] - '0';
  4126. if( z[i+1]>='0' && z[i+1]<='7' ){
  4127. i++;
  4128. c = (c<<3) + z[i] - '0';
  4129. }
  4130. }
  4131. }
  4132. }
  4133. z[j] = c;
  4134. }
  4135. if( j<i ) z[j] = 0;
  4136. }
  4137. /*
  4138. ** Return the value of a hexadecimal digit. Return -1 if the input
  4139. ** is not a hex digit.
  4140. */
  4141. static int hexDigitValue(char c){
  4142. if( c>='0' && c<='9' ) return c - '0';
  4143. if( c>='a' && c<='f' ) return c - 'a' + 10;
  4144. if( c>='A' && c<='F' ) return c - 'A' + 10;
  4145. return -1;
  4146. }
  4147. /*
  4148. ** Interpret zArg as an integer value, possibly with suffixes.
  4149. */
  4150. static sqlite3_int64 integerValue(const char *zArg){
  4151. sqlite3_int64 v = 0;
  4152. static const struct { char *zSuffix; int iMult; } aMult[] = {
  4153. { "KiB", 1024 },
  4154. { "MiB", 1024*1024 },
  4155. { "GiB", 1024*1024*1024 },
  4156. { "KB", 1000 },
  4157. { "MB", 1000000 },
  4158. { "GB", 1000000000 },
  4159. { "K", 1000 },
  4160. { "M", 1000000 },
  4161. { "G", 1000000000 },
  4162. };
  4163. int i;
  4164. int isNeg = 0;
  4165. if( zArg[0]=='-' ){
  4166. isNeg = 1;
  4167. zArg++;
  4168. }else if( zArg[0]=='+' ){
  4169. zArg++;
  4170. }
  4171. if( zArg[0]=='0' && zArg[1]=='x' ){
  4172. int x;
  4173. zArg += 2;
  4174. while( (x = hexDigitValue(zArg[0]))>=0 ){
  4175. v = (v<<4) + x;
  4176. zArg++;
  4177. }
  4178. }else{
  4179. while( IsDigit(zArg[0]) ){
  4180. v = v*10 + zArg[0] - '0';
  4181. zArg++;
  4182. }
  4183. }
  4184. for(i=0; i<ArraySize(aMult); i++){
  4185. if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
  4186. v *= aMult[i].iMult;
  4187. break;
  4188. }
  4189. }
  4190. return isNeg? -v : v;
  4191. }
  4192. /*
  4193. ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
  4194. ** for TRUE and FALSE. Return the integer value if appropriate.
  4195. */
  4196. static int booleanValue(const char *zArg){
  4197. int i;
  4198. if( zArg[0]=='0' && zArg[1]=='x' ){
  4199. for(i=2; hexDigitValue(zArg[i])>=0; i++){}
  4200. }else{
  4201. for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
  4202. }
  4203. if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
  4204. if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
  4205. return 1;
  4206. }
  4207. if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
  4208. return 0;
  4209. }
  4210. utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
  4211. zArg);
  4212. return 0;
  4213. }
  4214. /*
  4215. ** Set or clear a shell flag according to a boolean value.
  4216. */
  4217. static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
  4218. if( booleanValue(zArg) ){
  4219. ShellSetFlag(p, mFlag);
  4220. }else{
  4221. ShellClearFlag(p, mFlag);
  4222. }
  4223. }
  4224. /*
  4225. ** Close an output file, assuming it is not stderr or stdout
  4226. */
  4227. static void output_file_close(FILE *f){
  4228. if( f && f!=stdout && f!=stderr ) fclose(f);
  4229. }
  4230. /*
  4231. ** Try to open an output file. The names "stdout" and "stderr" are
  4232. ** recognized and do the right thing. NULL is returned if the output
  4233. ** filename is "off".
  4234. */
  4235. static FILE *output_file_open(const char *zFile){
  4236. FILE *f;
  4237. if( strcmp(zFile,"stdout")==0 ){
  4238. f = stdout;
  4239. }else if( strcmp(zFile, "stderr")==0 ){
  4240. f = stderr;
  4241. }else if( strcmp(zFile, "off")==0 ){
  4242. f = 0;
  4243. }else{
  4244. f = fopen(zFile, "wb");
  4245. if( f==0 ){
  4246. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  4247. }
  4248. }
  4249. return f;
  4250. }
  4251. #if !defined(SQLITE_UNTESTABLE)
  4252. #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
  4253. /*
  4254. ** A routine for handling output from sqlite3_trace().
  4255. */
  4256. static int sql_trace_callback(
  4257. unsigned mType,
  4258. void *pArg,
  4259. void *pP,
  4260. void *pX
  4261. ){
  4262. FILE *f = (FILE*)pArg;
  4263. UNUSED_PARAMETER(mType);
  4264. UNUSED_PARAMETER(pP);
  4265. if( f ){
  4266. const char *z = (const char*)pX;
  4267. int i = (int)strlen(z);
  4268. while( i>0 && z[i-1]==';' ){ i--; }
  4269. utf8_printf(f, "%.*s;\n", i, z);
  4270. }
  4271. return 0;
  4272. }
  4273. #endif
  4274. #endif
  4275. /*
  4276. ** A no-op routine that runs with the ".breakpoint" doc-command. This is
  4277. ** a useful spot to set a debugger breakpoint.
  4278. */
  4279. static void test_breakpoint(void){
  4280. static int nCall = 0;
  4281. nCall++;
  4282. }
  4283. /*
  4284. ** An object used to read a CSV and other files for import.
  4285. */
  4286. typedef struct ImportCtx ImportCtx;
  4287. struct ImportCtx {
  4288. const char *zFile; /* Name of the input file */
  4289. FILE *in; /* Read the CSV text from this input stream */
  4290. char *z; /* Accumulated text for a field */
  4291. int n; /* Number of bytes in z */
  4292. int nAlloc; /* Space allocated for z[] */
  4293. int nLine; /* Current line number */
  4294. int bNotFirst; /* True if one or more bytes already read */
  4295. int cTerm; /* Character that terminated the most recent field */
  4296. int cColSep; /* The column separator character. (Usually ",") */
  4297. int cRowSep; /* The row separator character. (Usually "\n") */
  4298. };
  4299. /* Append a single byte to z[] */
  4300. static void import_append_char(ImportCtx *p, int c){
  4301. if( p->n+1>=p->nAlloc ){
  4302. p->nAlloc += p->nAlloc + 100;
  4303. p->z = sqlite3_realloc64(p->z, p->nAlloc);
  4304. if( p->z==0 ){
  4305. raw_printf(stderr, "out of memory\n");
  4306. exit(1);
  4307. }
  4308. }
  4309. p->z[p->n++] = (char)c;
  4310. }
  4311. /* Read a single field of CSV text. Compatible with rfc4180 and extended
  4312. ** with the option of having a separator other than ",".
  4313. **
  4314. ** + Input comes from p->in.
  4315. ** + Store results in p->z of length p->n. Space to hold p->z comes
  4316. ** from sqlite3_malloc64().
  4317. ** + Use p->cSep as the column separator. The default is ",".
  4318. ** + Use p->rSep as the row separator. The default is "\n".
  4319. ** + Keep track of the line number in p->nLine.
  4320. ** + Store the character that terminates the field in p->cTerm. Store
  4321. ** EOF on end-of-file.
  4322. ** + Report syntax errors on stderr
  4323. */
  4324. static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
  4325. int c;
  4326. int cSep = p->cColSep;
  4327. int rSep = p->cRowSep;
  4328. p->n = 0;
  4329. c = fgetc(p->in);
  4330. if( c==EOF || seenInterrupt ){
  4331. p->cTerm = EOF;
  4332. return 0;
  4333. }
  4334. if( c=='"' ){
  4335. int pc, ppc;
  4336. int startLine = p->nLine;
  4337. int cQuote = c;
  4338. pc = ppc = 0;
  4339. while( 1 ){
  4340. c = fgetc(p->in);
  4341. if( c==rSep ) p->nLine++;
  4342. if( c==cQuote ){
  4343. if( pc==cQuote ){
  4344. pc = 0;
  4345. continue;
  4346. }
  4347. }
  4348. if( (c==cSep && pc==cQuote)
  4349. || (c==rSep && pc==cQuote)
  4350. || (c==rSep && pc=='\r' && ppc==cQuote)
  4351. || (c==EOF && pc==cQuote)
  4352. ){
  4353. do{ p->n--; }while( p->z[p->n]!=cQuote );
  4354. p->cTerm = c;
  4355. break;
  4356. }
  4357. if( pc==cQuote && c!='\r' ){
  4358. utf8_printf(stderr, "%s:%d: unescaped %c character\n",
  4359. p->zFile, p->nLine, cQuote);
  4360. }
  4361. if( c==EOF ){
  4362. utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
  4363. p->zFile, startLine, cQuote);
  4364. p->cTerm = c;
  4365. break;
  4366. }
  4367. import_append_char(p, c);
  4368. ppc = pc;
  4369. pc = c;
  4370. }
  4371. }else{
  4372. /* If this is the first field being parsed and it begins with the
  4373. ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
  4374. if( (c&0xff)==0xef && p->bNotFirst==0 ){
  4375. import_append_char(p, c);
  4376. c = fgetc(p->in);
  4377. if( (c&0xff)==0xbb ){
  4378. import_append_char(p, c);
  4379. c = fgetc(p->in);
  4380. if( (c&0xff)==0xbf ){
  4381. p->bNotFirst = 1;
  4382. p->n = 0;
  4383. return csv_read_one_field(p);
  4384. }
  4385. }
  4386. }
  4387. while( c!=EOF && c!=cSep && c!=rSep ){
  4388. import_append_char(p, c);
  4389. c = fgetc(p->in);
  4390. }
  4391. if( c==rSep ){
  4392. p->nLine++;
  4393. if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
  4394. }
  4395. p->cTerm = c;
  4396. }
  4397. if( p->z ) p->z[p->n] = 0;
  4398. p->bNotFirst = 1;
  4399. return p->z;
  4400. }
  4401. /* Read a single field of ASCII delimited text.
  4402. **
  4403. ** + Input comes from p->in.
  4404. ** + Store results in p->z of length p->n. Space to hold p->z comes
  4405. ** from sqlite3_malloc64().
  4406. ** + Use p->cSep as the column separator. The default is "\x1F".
  4407. ** + Use p->rSep as the row separator. The default is "\x1E".
  4408. ** + Keep track of the row number in p->nLine.
  4409. ** + Store the character that terminates the field in p->cTerm. Store
  4410. ** EOF on end-of-file.
  4411. ** + Report syntax errors on stderr
  4412. */
  4413. static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
  4414. int c;
  4415. int cSep = p->cColSep;
  4416. int rSep = p->cRowSep;
  4417. p->n = 0;
  4418. c = fgetc(p->in);
  4419. if( c==EOF || seenInterrupt ){
  4420. p->cTerm = EOF;
  4421. return 0;
  4422. }
  4423. while( c!=EOF && c!=cSep && c!=rSep ){
  4424. import_append_char(p, c);
  4425. c = fgetc(p->in);
  4426. }
  4427. if( c==rSep ){
  4428. p->nLine++;
  4429. }
  4430. p->cTerm = c;
  4431. if( p->z ) p->z[p->n] = 0;
  4432. return p->z;
  4433. }
  4434. /*
  4435. ** Try to transfer data for table zTable. If an error is seen while
  4436. ** moving forward, try to go backwards. The backwards movement won't
  4437. ** work for WITHOUT ROWID tables.
  4438. */
  4439. static void tryToCloneData(
  4440. ShellState *p,
  4441. sqlite3 *newDb,
  4442. const char *zTable
  4443. ){
  4444. sqlite3_stmt *pQuery = 0;
  4445. sqlite3_stmt *pInsert = 0;
  4446. char *zQuery = 0;
  4447. char *zInsert = 0;
  4448. int rc;
  4449. int i, j, n;
  4450. int nTable = (int)strlen(zTable);
  4451. int k = 0;
  4452. int cnt = 0;
  4453. const int spinRate = 10000;
  4454. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
  4455. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  4456. if( rc ){
  4457. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  4458. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  4459. zQuery);
  4460. goto end_data_xfer;
  4461. }
  4462. n = sqlite3_column_count(pQuery);
  4463. zInsert = sqlite3_malloc64(200 + nTable + n*3);
  4464. if( zInsert==0 ){
  4465. raw_printf(stderr, "out of memory\n");
  4466. goto end_data_xfer;
  4467. }
  4468. sqlite3_snprintf(200+nTable,zInsert,
  4469. "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
  4470. i = (int)strlen(zInsert);
  4471. for(j=1; j<n; j++){
  4472. memcpy(zInsert+i, ",?", 2);
  4473. i += 2;
  4474. }
  4475. memcpy(zInsert+i, ");", 3);
  4476. rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
  4477. if( rc ){
  4478. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  4479. sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
  4480. zQuery);
  4481. goto end_data_xfer;
  4482. }
  4483. for(k=0; k<2; k++){
  4484. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  4485. for(i=0; i<n; i++){
  4486. switch( sqlite3_column_type(pQuery, i) ){
  4487. case SQLITE_NULL: {
  4488. sqlite3_bind_null(pInsert, i+1);
  4489. break;
  4490. }
  4491. case SQLITE_INTEGER: {
  4492. sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
  4493. break;
  4494. }
  4495. case SQLITE_FLOAT: {
  4496. sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
  4497. break;
  4498. }
  4499. case SQLITE_TEXT: {
  4500. sqlite3_bind_text(pInsert, i+1,
  4501. (const char*)sqlite3_column_text(pQuery,i),
  4502. -1, SQLITE_STATIC);
  4503. break;
  4504. }
  4505. case SQLITE_BLOB: {
  4506. sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
  4507. sqlite3_column_bytes(pQuery,i),
  4508. SQLITE_STATIC);
  4509. break;
  4510. }
  4511. }
  4512. } /* End for */
  4513. rc = sqlite3_step(pInsert);
  4514. if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  4515. utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
  4516. sqlite3_errmsg(newDb));
  4517. }
  4518. sqlite3_reset(pInsert);
  4519. cnt++;
  4520. if( (cnt%spinRate)==0 ){
  4521. printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
  4522. fflush(stdout);
  4523. }
  4524. } /* End while */
  4525. if( rc==SQLITE_DONE ) break;
  4526. sqlite3_finalize(pQuery);
  4527. sqlite3_free(zQuery);
  4528. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
  4529. zTable);
  4530. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  4531. if( rc ){
  4532. utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
  4533. break;
  4534. }
  4535. } /* End for(k=0...) */
  4536. end_data_xfer:
  4537. sqlite3_finalize(pQuery);
  4538. sqlite3_finalize(pInsert);
  4539. sqlite3_free(zQuery);
  4540. sqlite3_free(zInsert);
  4541. }
  4542. /*
  4543. ** Try to transfer all rows of the schema that match zWhere. For
  4544. ** each row, invoke xForEach() on the object defined by that row.
  4545. ** If an error is encountered while moving forward through the
  4546. ** sqlite_master table, try again moving backwards.
  4547. */
  4548. static void tryToCloneSchema(
  4549. ShellState *p,
  4550. sqlite3 *newDb,
  4551. const char *zWhere,
  4552. void (*xForEach)(ShellState*,sqlite3*,const char*)
  4553. ){
  4554. sqlite3_stmt *pQuery = 0;
  4555. char *zQuery = 0;
  4556. int rc;
  4557. const unsigned char *zName;
  4558. const unsigned char *zSql;
  4559. char *zErrMsg = 0;
  4560. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  4561. " WHERE %s", zWhere);
  4562. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  4563. if( rc ){
  4564. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  4565. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  4566. zQuery);
  4567. goto end_schema_xfer;
  4568. }
  4569. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  4570. zName = sqlite3_column_text(pQuery, 0);
  4571. zSql = sqlite3_column_text(pQuery, 1);
  4572. printf("%s... ", zName); fflush(stdout);
  4573. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  4574. if( zErrMsg ){
  4575. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  4576. sqlite3_free(zErrMsg);
  4577. zErrMsg = 0;
  4578. }
  4579. if( xForEach ){
  4580. xForEach(p, newDb, (const char*)zName);
  4581. }
  4582. printf("done\n");
  4583. }
  4584. if( rc!=SQLITE_DONE ){
  4585. sqlite3_finalize(pQuery);
  4586. sqlite3_free(zQuery);
  4587. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  4588. " WHERE %s ORDER BY rowid DESC", zWhere);
  4589. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  4590. if( rc ){
  4591. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  4592. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  4593. zQuery);
  4594. goto end_schema_xfer;
  4595. }
  4596. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  4597. zName = sqlite3_column_text(pQuery, 0);
  4598. zSql = sqlite3_column_text(pQuery, 1);
  4599. printf("%s... ", zName); fflush(stdout);
  4600. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  4601. if( zErrMsg ){
  4602. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  4603. sqlite3_free(zErrMsg);
  4604. zErrMsg = 0;
  4605. }
  4606. if( xForEach ){
  4607. xForEach(p, newDb, (const char*)zName);
  4608. }
  4609. printf("done\n");
  4610. }
  4611. }
  4612. end_schema_xfer:
  4613. sqlite3_finalize(pQuery);
  4614. sqlite3_free(zQuery);
  4615. }
  4616. /*
  4617. ** Open a new database file named "zNewDb". Try to recover as much information
  4618. ** as possible out of the main database (which might be corrupt) and write it
  4619. ** into zNewDb.
  4620. */
  4621. static void tryToClone(ShellState *p, const char *zNewDb){
  4622. int rc;
  4623. sqlite3 *newDb = 0;
  4624. if( access(zNewDb,0)==0 ){
  4625. utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
  4626. return;
  4627. }
  4628. rc = sqlite3_open(zNewDb, &newDb);
  4629. if( rc ){
  4630. utf8_printf(stderr, "Cannot create output database: %s\n",
  4631. sqlite3_errmsg(newDb));
  4632. }else{
  4633. sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
  4634. sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
  4635. tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
  4636. tryToCloneSchema(p, newDb, "type!='table'", 0);
  4637. sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
  4638. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  4639. }
  4640. sqlite3_close(newDb);
  4641. }
  4642. /*
  4643. ** Change the output file back to stdout
  4644. */
  4645. static void output_reset(ShellState *p){
  4646. if( p->outfile[0]=='|' ){
  4647. #ifndef SQLITE_OMIT_POPEN
  4648. pclose(p->out);
  4649. #endif
  4650. }else{
  4651. output_file_close(p->out);
  4652. }
  4653. p->outfile[0] = 0;
  4654. p->out = stdout;
  4655. }
  4656. /*
  4657. ** Run an SQL command and return the single integer result.
  4658. */
  4659. static int db_int(ShellState *p, const char *zSql){
  4660. sqlite3_stmt *pStmt;
  4661. int res = 0;
  4662. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  4663. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  4664. res = sqlite3_column_int(pStmt,0);
  4665. }
  4666. sqlite3_finalize(pStmt);
  4667. return res;
  4668. }
  4669. /*
  4670. ** Convert a 2-byte or 4-byte big-endian integer into a native integer
  4671. */
  4672. static unsigned int get2byteInt(unsigned char *a){
  4673. return (a[0]<<8) + a[1];
  4674. }
  4675. static unsigned int get4byteInt(unsigned char *a){
  4676. return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
  4677. }
  4678. /*
  4679. ** Implementation of the ".info" command.
  4680. **
  4681. ** Return 1 on error, 2 to exit, and 0 otherwise.
  4682. */
  4683. static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
  4684. static const struct { const char *zName; int ofst; } aField[] = {
  4685. { "file change counter:", 24 },
  4686. { "database page count:", 28 },
  4687. { "freelist page count:", 36 },
  4688. { "schema cookie:", 40 },
  4689. { "schema format:", 44 },
  4690. { "default cache size:", 48 },
  4691. { "autovacuum top root:", 52 },
  4692. { "incremental vacuum:", 64 },
  4693. { "text encoding:", 56 },
  4694. { "user version:", 60 },
  4695. { "application id:", 68 },
  4696. { "software version:", 96 },
  4697. };
  4698. static const struct { const char *zName; const char *zSql; } aQuery[] = {
  4699. { "number of tables:",
  4700. "SELECT count(*) FROM %s WHERE type='table'" },
  4701. { "number of indexes:",
  4702. "SELECT count(*) FROM %s WHERE type='index'" },
  4703. { "number of triggers:",
  4704. "SELECT count(*) FROM %s WHERE type='trigger'" },
  4705. { "number of views:",
  4706. "SELECT count(*) FROM %s WHERE type='view'" },
  4707. { "schema size:",
  4708. "SELECT total(length(sql)) FROM %s" },
  4709. };
  4710. int i;
  4711. char *zSchemaTab;
  4712. char *zDb = nArg>=2 ? azArg[1] : "main";
  4713. sqlite3_stmt *pStmt = 0;
  4714. unsigned char aHdr[100];
  4715. open_db(p, 0);
  4716. if( p->db==0 ) return 1;
  4717. sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
  4718. -1, &pStmt, 0);
  4719. sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
  4720. if( sqlite3_step(pStmt)==SQLITE_ROW
  4721. && sqlite3_column_bytes(pStmt,0)>100
  4722. ){
  4723. memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
  4724. sqlite3_finalize(pStmt);
  4725. }else{
  4726. raw_printf(stderr, "unable to read database header\n");
  4727. sqlite3_finalize(pStmt);
  4728. return 1;
  4729. }
  4730. i = get2byteInt(aHdr+16);
  4731. if( i==1 ) i = 65536;
  4732. utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
  4733. utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
  4734. utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
  4735. utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
  4736. for(i=0; i<ArraySize(aField); i++){
  4737. int ofst = aField[i].ofst;
  4738. unsigned int val = get4byteInt(aHdr + ofst);
  4739. utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
  4740. switch( ofst ){
  4741. case 56: {
  4742. if( val==1 ) raw_printf(p->out, " (utf8)");
  4743. if( val==2 ) raw_printf(p->out, " (utf16le)");
  4744. if( val==3 ) raw_printf(p->out, " (utf16be)");
  4745. }
  4746. }
  4747. raw_printf(p->out, "\n");
  4748. }
  4749. if( zDb==0 ){
  4750. zSchemaTab = sqlite3_mprintf("main.sqlite_master");
  4751. }else if( strcmp(zDb,"temp")==0 ){
  4752. zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
  4753. }else{
  4754. zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
  4755. }
  4756. for(i=0; i<ArraySize(aQuery); i++){
  4757. char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
  4758. int val = db_int(p, zSql);
  4759. sqlite3_free(zSql);
  4760. utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
  4761. }
  4762. sqlite3_free(zSchemaTab);
  4763. return 0;
  4764. }
  4765. /*
  4766. ** Print the current sqlite3_errmsg() value to stderr and return 1.
  4767. */
  4768. static int shellDatabaseError(sqlite3 *db){
  4769. const char *zErr = sqlite3_errmsg(db);
  4770. utf8_printf(stderr, "Error: %s\n", zErr);
  4771. return 1;
  4772. }
  4773. /*
  4774. ** Print an out-of-memory message to stderr and return 1.
  4775. */
  4776. static int shellNomemError(void){
  4777. raw_printf(stderr, "Error: out of memory\n");
  4778. return 1;
  4779. }
  4780. /*
  4781. ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
  4782. ** if they match and FALSE (0) if they do not match.
  4783. **
  4784. ** Globbing rules:
  4785. **
  4786. ** '*' Matches any sequence of zero or more characters.
  4787. **
  4788. ** '?' Matches exactly one character.
  4789. **
  4790. ** [...] Matches one character from the enclosed list of
  4791. ** characters.
  4792. **
  4793. ** [^...] Matches one character not in the enclosed list.
  4794. **
  4795. ** '#' Matches any sequence of one or more digits with an
  4796. ** optional + or - sign in front
  4797. **
  4798. ** ' ' Any span of whitespace matches any other span of
  4799. ** whitespace.
  4800. **
  4801. ** Extra whitespace at the end of z[] is ignored.
  4802. */
  4803. static int testcase_glob(const char *zGlob, const char *z){
  4804. int c, c2;
  4805. int invert;
  4806. int seen;
  4807. while( (c = (*(zGlob++)))!=0 ){
  4808. if( IsSpace(c) ){
  4809. if( !IsSpace(*z) ) return 0;
  4810. while( IsSpace(*zGlob) ) zGlob++;
  4811. while( IsSpace(*z) ) z++;
  4812. }else if( c=='*' ){
  4813. while( (c=(*(zGlob++))) == '*' || c=='?' ){
  4814. if( c=='?' && (*(z++))==0 ) return 0;
  4815. }
  4816. if( c==0 ){
  4817. return 1;
  4818. }else if( c=='[' ){
  4819. while( *z && testcase_glob(zGlob-1,z)==0 ){
  4820. z++;
  4821. }
  4822. return (*z)!=0;
  4823. }
  4824. while( (c2 = (*(z++)))!=0 ){
  4825. while( c2!=c ){
  4826. c2 = *(z++);
  4827. if( c2==0 ) return 0;
  4828. }
  4829. if( testcase_glob(zGlob,z) ) return 1;
  4830. }
  4831. return 0;
  4832. }else if( c=='?' ){
  4833. if( (*(z++))==0 ) return 0;
  4834. }else if( c=='[' ){
  4835. int prior_c = 0;
  4836. seen = 0;
  4837. invert = 0;
  4838. c = *(z++);
  4839. if( c==0 ) return 0;
  4840. c2 = *(zGlob++);
  4841. if( c2=='^' ){
  4842. invert = 1;
  4843. c2 = *(zGlob++);
  4844. }
  4845. if( c2==']' ){
  4846. if( c==']' ) seen = 1;
  4847. c2 = *(zGlob++);
  4848. }
  4849. while( c2 && c2!=']' ){
  4850. if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
  4851. c2 = *(zGlob++);
  4852. if( c>=prior_c && c<=c2 ) seen = 1;
  4853. prior_c = 0;
  4854. }else{
  4855. if( c==c2 ){
  4856. seen = 1;
  4857. }
  4858. prior_c = c2;
  4859. }
  4860. c2 = *(zGlob++);
  4861. }
  4862. if( c2==0 || (seen ^ invert)==0 ) return 0;
  4863. }else if( c=='#' ){
  4864. if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
  4865. if( !IsDigit(z[0]) ) return 0;
  4866. z++;
  4867. while( IsDigit(z[0]) ){ z++; }
  4868. }else{
  4869. if( c!=(*(z++)) ) return 0;
  4870. }
  4871. }
  4872. while( IsSpace(*z) ){ z++; }
  4873. return *z==0;
  4874. }
  4875. /*
  4876. ** Compare the string as a command-line option with either one or two
  4877. ** initial "-" characters.
  4878. */
  4879. static int optionMatch(const char *zStr, const char *zOpt){
  4880. if( zStr[0]!='-' ) return 0;
  4881. zStr++;
  4882. if( zStr[0]=='-' ) zStr++;
  4883. return strcmp(zStr, zOpt)==0;
  4884. }
  4885. /*
  4886. ** Delete a file.
  4887. */
  4888. int shellDeleteFile(const char *zFilename){
  4889. int rc;
  4890. #ifdef _WIN32
  4891. wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
  4892. rc = _wunlink(z);
  4893. sqlite3_free(z);
  4894. #else
  4895. rc = unlink(zFilename);
  4896. #endif
  4897. return rc;
  4898. }
  4899. /*
  4900. ** The implementation of SQL scalar function fkey_collate_clause(), used
  4901. ** by the ".lint fkey-indexes" command. This scalar function is always
  4902. ** called with four arguments - the parent table name, the parent column name,
  4903. ** the child table name and the child column name.
  4904. **
  4905. ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
  4906. **
  4907. ** If either of the named tables or columns do not exist, this function
  4908. ** returns an empty string. An empty string is also returned if both tables
  4909. ** and columns exist but have the same default collation sequence. Or,
  4910. ** if both exist but the default collation sequences are different, this
  4911. ** function returns the string " COLLATE <parent-collation>", where
  4912. ** <parent-collation> is the default collation sequence of the parent column.
  4913. */
  4914. static void shellFkeyCollateClause(
  4915. sqlite3_context *pCtx,
  4916. int nVal,
  4917. sqlite3_value **apVal
  4918. ){
  4919. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  4920. const char *zParent;
  4921. const char *zParentCol;
  4922. const char *zParentSeq;
  4923. const char *zChild;
  4924. const char *zChildCol;
  4925. const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
  4926. int rc;
  4927. assert( nVal==4 );
  4928. zParent = (const char*)sqlite3_value_text(apVal[0]);
  4929. zParentCol = (const char*)sqlite3_value_text(apVal[1]);
  4930. zChild = (const char*)sqlite3_value_text(apVal[2]);
  4931. zChildCol = (const char*)sqlite3_value_text(apVal[3]);
  4932. sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
  4933. rc = sqlite3_table_column_metadata(
  4934. db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
  4935. );
  4936. if( rc==SQLITE_OK ){
  4937. rc = sqlite3_table_column_metadata(
  4938. db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
  4939. );
  4940. }
  4941. if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
  4942. char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
  4943. sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
  4944. sqlite3_free(z);
  4945. }
  4946. }
  4947. /*
  4948. ** The implementation of dot-command ".lint fkey-indexes".
  4949. */
  4950. static int lintFkeyIndexes(
  4951. ShellState *pState, /* Current shell tool state */
  4952. char **azArg, /* Array of arguments passed to dot command */
  4953. int nArg /* Number of entries in azArg[] */
  4954. ){
  4955. sqlite3 *db = pState->db; /* Database handle to query "main" db of */
  4956. FILE *out = pState->out; /* Stream to write non-error output to */
  4957. int bVerbose = 0; /* If -verbose is present */
  4958. int bGroupByParent = 0; /* If -groupbyparent is present */
  4959. int i; /* To iterate through azArg[] */
  4960. const char *zIndent = ""; /* How much to indent CREATE INDEX by */
  4961. int rc; /* Return code */
  4962. sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
  4963. /*
  4964. ** This SELECT statement returns one row for each foreign key constraint
  4965. ** in the schema of the main database. The column values are:
  4966. **
  4967. ** 0. The text of an SQL statement similar to:
  4968. **
  4969. ** "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
  4970. **
  4971. ** This is the same SELECT that the foreign keys implementation needs
  4972. ** to run internally on child tables. If there is an index that can
  4973. ** be used to optimize this query, then it can also be used by the FK
  4974. ** implementation to optimize DELETE or UPDATE statements on the parent
  4975. ** table.
  4976. **
  4977. ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
  4978. ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
  4979. ** contains an index that can be used to optimize the query.
  4980. **
  4981. ** 2. Human readable text that describes the child table and columns. e.g.
  4982. **
  4983. ** "child_table(child_key1, child_key2)"
  4984. **
  4985. ** 3. Human readable text that describes the parent table and columns. e.g.
  4986. **
  4987. ** "parent_table(parent_key1, parent_key2)"
  4988. **
  4989. ** 4. A full CREATE INDEX statement for an index that could be used to
  4990. ** optimize DELETE or UPDATE statements on the parent table. e.g.
  4991. **
  4992. ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
  4993. **
  4994. ** 5. The name of the parent table.
  4995. **
  4996. ** These six values are used by the C logic below to generate the report.
  4997. */
  4998. const char *zSql =
  4999. "SELECT "
  5000. " 'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
  5001. " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
  5002. " || fkey_collate_clause("
  5003. " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
  5004. ", "
  5005. " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
  5006. " || group_concat('*=?', ' AND ') || ')'"
  5007. ", "
  5008. " s.name || '(' || group_concat(f.[from], ', ') || ')'"
  5009. ", "
  5010. " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
  5011. ", "
  5012. " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
  5013. " || ' ON ' || quote(s.name) || '('"
  5014. " || group_concat(quote(f.[from]) ||"
  5015. " fkey_collate_clause("
  5016. " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
  5017. " || ');'"
  5018. ", "
  5019. " f.[table] "
  5020. "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
  5021. "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
  5022. "GROUP BY s.name, f.id "
  5023. "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
  5024. ;
  5025. const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
  5026. for(i=2; i<nArg; i++){
  5027. int n = (int)strlen(azArg[i]);
  5028. if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
  5029. bVerbose = 1;
  5030. }
  5031. else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
  5032. bGroupByParent = 1;
  5033. zIndent = " ";
  5034. }
  5035. else{
  5036. raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
  5037. azArg[0], azArg[1]
  5038. );
  5039. return SQLITE_ERROR;
  5040. }
  5041. }
  5042. /* Register the fkey_collate_clause() SQL function */
  5043. rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
  5044. 0, shellFkeyCollateClause, 0, 0
  5045. );
  5046. if( rc==SQLITE_OK ){
  5047. rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
  5048. }
  5049. if( rc==SQLITE_OK ){
  5050. sqlite3_bind_int(pSql, 1, bGroupByParent);
  5051. }
  5052. if( rc==SQLITE_OK ){
  5053. int rc2;
  5054. char *zPrev = 0;
  5055. while( SQLITE_ROW==sqlite3_step(pSql) ){
  5056. int res = -1;
  5057. sqlite3_stmt *pExplain = 0;
  5058. const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
  5059. const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
  5060. const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
  5061. const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
  5062. const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
  5063. const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
  5064. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  5065. if( rc!=SQLITE_OK ) break;
  5066. if( SQLITE_ROW==sqlite3_step(pExplain) ){
  5067. const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
  5068. res = (
  5069. 0==sqlite3_strglob(zGlob, zPlan)
  5070. || 0==sqlite3_strglob(zGlobIPK, zPlan)
  5071. );
  5072. }
  5073. rc = sqlite3_finalize(pExplain);
  5074. if( rc!=SQLITE_OK ) break;
  5075. if( res<0 ){
  5076. raw_printf(stderr, "Error: internal error");
  5077. break;
  5078. }else{
  5079. if( bGroupByParent
  5080. && (bVerbose || res==0)
  5081. && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
  5082. ){
  5083. raw_printf(out, "-- Parent table %s\n", zParent);
  5084. sqlite3_free(zPrev);
  5085. zPrev = sqlite3_mprintf("%s", zParent);
  5086. }
  5087. if( res==0 ){
  5088. raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
  5089. }else if( bVerbose ){
  5090. raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
  5091. zIndent, zFrom, zTarget
  5092. );
  5093. }
  5094. }
  5095. }
  5096. sqlite3_free(zPrev);
  5097. if( rc!=SQLITE_OK ){
  5098. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  5099. }
  5100. rc2 = sqlite3_finalize(pSql);
  5101. if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
  5102. rc = rc2;
  5103. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  5104. }
  5105. }else{
  5106. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  5107. }
  5108. return rc;
  5109. }
  5110. /*
  5111. ** Implementation of ".lint" dot command.
  5112. */
  5113. static int lintDotCommand(
  5114. ShellState *pState, /* Current shell tool state */
  5115. char **azArg, /* Array of arguments passed to dot command */
  5116. int nArg /* Number of entries in azArg[] */
  5117. ){
  5118. int n;
  5119. n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
  5120. if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
  5121. return lintFkeyIndexes(pState, azArg, nArg);
  5122. usage:
  5123. raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
  5124. raw_printf(stderr, "Where sub-commands are:\n");
  5125. raw_printf(stderr, " fkey-indexes\n");
  5126. return SQLITE_ERROR;
  5127. }
  5128. /*
  5129. ** If an input line begins with "." then invoke this routine to
  5130. ** process that line.
  5131. **
  5132. ** Return 1 on error, 2 to exit, and 0 otherwise.
  5133. */
  5134. static int do_meta_command(char *zLine, ShellState *p){
  5135. int h = 1;
  5136. int nArg = 0;
  5137. int n, c;
  5138. int rc = 0;
  5139. char *azArg[50];
  5140. /* Parse the input line into tokens.
  5141. */
  5142. while( zLine[h] && nArg<ArraySize(azArg) ){
  5143. while( IsSpace(zLine[h]) ){ h++; }
  5144. if( zLine[h]==0 ) break;
  5145. if( zLine[h]=='\'' || zLine[h]=='"' ){
  5146. int delim = zLine[h++];
  5147. azArg[nArg++] = &zLine[h];
  5148. while( zLine[h] && zLine[h]!=delim ){
  5149. if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
  5150. h++;
  5151. }
  5152. if( zLine[h]==delim ){
  5153. zLine[h++] = 0;
  5154. }
  5155. if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  5156. }else{
  5157. azArg[nArg++] = &zLine[h];
  5158. while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
  5159. if( zLine[h] ) zLine[h++] = 0;
  5160. resolve_backslashes(azArg[nArg-1]);
  5161. }
  5162. }
  5163. /* Process the input line.
  5164. */
  5165. if( nArg==0 ) return 0; /* no tokens, no error */
  5166. n = strlen30(azArg[0]);
  5167. c = azArg[0][0];
  5168. #ifndef SQLITE_OMIT_AUTHORIZATION
  5169. if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
  5170. if( nArg!=2 ){
  5171. raw_printf(stderr, "Usage: .auth ON|OFF\n");
  5172. rc = 1;
  5173. goto meta_command_exit;
  5174. }
  5175. open_db(p, 0);
  5176. if( booleanValue(azArg[1]) ){
  5177. sqlite3_set_authorizer(p->db, shellAuth, p);
  5178. }else{
  5179. sqlite3_set_authorizer(p->db, 0, 0);
  5180. }
  5181. }else
  5182. #endif
  5183. if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
  5184. || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
  5185. ){
  5186. const char *zDestFile = 0;
  5187. const char *zDb = 0;
  5188. sqlite3 *pDest;
  5189. sqlite3_backup *pBackup;
  5190. int j;
  5191. for(j=1; j<nArg; j++){
  5192. const char *z = azArg[j];
  5193. if( z[0]=='-' ){
  5194. while( z[0]=='-' ) z++;
  5195. /* No options to process at this time */
  5196. {
  5197. utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
  5198. return 1;
  5199. }
  5200. }else if( zDestFile==0 ){
  5201. zDestFile = azArg[j];
  5202. }else if( zDb==0 ){
  5203. zDb = zDestFile;
  5204. zDestFile = azArg[j];
  5205. }else{
  5206. raw_printf(stderr, "too many arguments to .backup\n");
  5207. return 1;
  5208. }
  5209. }
  5210. if( zDestFile==0 ){
  5211. raw_printf(stderr, "missing FILENAME argument on .backup\n");
  5212. return 1;
  5213. }
  5214. if( zDb==0 ) zDb = "main";
  5215. rc = sqlite3_open(zDestFile, &pDest);
  5216. if( rc!=SQLITE_OK ){
  5217. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  5218. sqlite3_close(pDest);
  5219. return 1;
  5220. }
  5221. open_db(p, 0);
  5222. pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  5223. if( pBackup==0 ){
  5224. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  5225. sqlite3_close(pDest);
  5226. return 1;
  5227. }
  5228. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  5229. sqlite3_backup_finish(pBackup);
  5230. if( rc==SQLITE_DONE ){
  5231. rc = 0;
  5232. }else{
  5233. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  5234. rc = 1;
  5235. }
  5236. sqlite3_close(pDest);
  5237. }else
  5238. if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
  5239. if( nArg==2 ){
  5240. bail_on_error = booleanValue(azArg[1]);
  5241. }else{
  5242. raw_printf(stderr, "Usage: .bail on|off\n");
  5243. rc = 1;
  5244. }
  5245. }else
  5246. if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
  5247. if( nArg==2 ){
  5248. if( booleanValue(azArg[1]) ){
  5249. setBinaryMode(p->out, 1);
  5250. }else{
  5251. setTextMode(p->out, 1);
  5252. }
  5253. }else{
  5254. raw_printf(stderr, "Usage: .binary on|off\n");
  5255. rc = 1;
  5256. }
  5257. }else
  5258. if( c=='c' && strcmp(azArg[0],"cd")==0 ){
  5259. if( nArg==2 ){
  5260. #if defined(_WIN32) || defined(WIN32)
  5261. wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
  5262. rc = !SetCurrentDirectoryW(z);
  5263. sqlite3_free(z);
  5264. #else
  5265. rc = chdir(azArg[1]);
  5266. #endif
  5267. if( rc ){
  5268. utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
  5269. rc = 1;
  5270. }
  5271. }else{
  5272. raw_printf(stderr, "Usage: .cd DIRECTORY\n");
  5273. rc = 1;
  5274. }
  5275. }else
  5276. /* The undocumented ".breakpoint" command causes a call to the no-op
  5277. ** routine named test_breakpoint().
  5278. */
  5279. if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
  5280. test_breakpoint();
  5281. }else
  5282. if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
  5283. if( nArg==2 ){
  5284. setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
  5285. }else{
  5286. raw_printf(stderr, "Usage: .changes on|off\n");
  5287. rc = 1;
  5288. }
  5289. }else
  5290. /* Cancel output redirection, if it is currently set (by .testcase)
  5291. ** Then read the content of the testcase-out.txt file and compare against
  5292. ** azArg[1]. If there are differences, report an error and exit.
  5293. */
  5294. if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
  5295. char *zRes = 0;
  5296. output_reset(p);
  5297. if( nArg!=2 ){
  5298. raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
  5299. rc = 2;
  5300. }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
  5301. raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
  5302. rc = 2;
  5303. }else if( testcase_glob(azArg[1],zRes)==0 ){
  5304. utf8_printf(stderr,
  5305. "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
  5306. p->zTestcase, azArg[1], zRes);
  5307. rc = 1;
  5308. }else{
  5309. utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
  5310. p->nCheck++;
  5311. }
  5312. sqlite3_free(zRes);
  5313. }else
  5314. if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
  5315. if( nArg==2 ){
  5316. tryToClone(p, azArg[1]);
  5317. }else{
  5318. raw_printf(stderr, "Usage: .clone FILENAME\n");
  5319. rc = 1;
  5320. }
  5321. }else
  5322. if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
  5323. ShellState data;
  5324. char *zErrMsg = 0;
  5325. open_db(p, 0);
  5326. memcpy(&data, p, sizeof(data));
  5327. data.showHeader = 0;
  5328. data.cMode = data.mode = MODE_List;
  5329. sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
  5330. data.cnt = 0;
  5331. sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
  5332. callback, &data, &zErrMsg);
  5333. if( zErrMsg ){
  5334. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  5335. sqlite3_free(zErrMsg);
  5336. rc = 1;
  5337. }
  5338. }else
  5339. if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
  5340. rc = shell_dbinfo_command(p, nArg, azArg);
  5341. }else
  5342. if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
  5343. const char *zLike = 0;
  5344. int i;
  5345. int savedShowHeader = p->showHeader;
  5346. ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
  5347. for(i=1; i<nArg; i++){
  5348. if( azArg[i][0]=='-' ){
  5349. const char *z = azArg[i]+1;
  5350. if( z[0]=='-' ) z++;
  5351. if( strcmp(z,"preserve-rowids")==0 ){
  5352. #ifdef SQLITE_OMIT_VIRTUALTABLE
  5353. raw_printf(stderr, "The --preserve-rowids option is not compatible"
  5354. " with SQLITE_OMIT_VIRTUALTABLE\n");
  5355. rc = 1;
  5356. goto meta_command_exit;
  5357. #else
  5358. ShellSetFlag(p, SHFLG_PreserveRowid);
  5359. #endif
  5360. }else
  5361. if( strcmp(z,"newlines")==0 ){
  5362. ShellSetFlag(p, SHFLG_Newlines);
  5363. }else
  5364. {
  5365. raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
  5366. rc = 1;
  5367. goto meta_command_exit;
  5368. }
  5369. }else if( zLike ){
  5370. raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
  5371. "?--newlines? ?LIKE-PATTERN?\n");
  5372. rc = 1;
  5373. goto meta_command_exit;
  5374. }else{
  5375. zLike = azArg[i];
  5376. }
  5377. }
  5378. open_db(p, 0);
  5379. /* When playing back a "dump", the content might appear in an order
  5380. ** which causes immediate foreign key constraints to be violated.
  5381. ** So disable foreign-key constraint enforcement to prevent problems. */
  5382. raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
  5383. raw_printf(p->out, "BEGIN TRANSACTION;\n");
  5384. p->writableSchema = 0;
  5385. p->showHeader = 0;
  5386. /* Set writable_schema=ON since doing so forces SQLite to initialize
  5387. ** as much of the schema as it can even if the sqlite_master table is
  5388. ** corrupt. */
  5389. sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
  5390. p->nErr = 0;
  5391. if( zLike==0 ){
  5392. run_schema_dump_query(p,
  5393. "SELECT name, type, sql FROM sqlite_master "
  5394. "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
  5395. );
  5396. run_schema_dump_query(p,
  5397. "SELECT name, type, sql FROM sqlite_master "
  5398. "WHERE name=='sqlite_sequence'"
  5399. );
  5400. run_table_dump_query(p,
  5401. "SELECT sql FROM sqlite_master "
  5402. "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
  5403. );
  5404. }else{
  5405. char *zSql;
  5406. zSql = sqlite3_mprintf(
  5407. "SELECT name, type, sql FROM sqlite_master "
  5408. "WHERE tbl_name LIKE %Q AND type=='table'"
  5409. " AND sql NOT NULL", zLike);
  5410. run_schema_dump_query(p,zSql);
  5411. sqlite3_free(zSql);
  5412. zSql = sqlite3_mprintf(
  5413. "SELECT sql FROM sqlite_master "
  5414. "WHERE sql NOT NULL"
  5415. " AND type IN ('index','trigger','view')"
  5416. " AND tbl_name LIKE %Q", zLike);
  5417. run_table_dump_query(p, zSql, 0);
  5418. sqlite3_free(zSql);
  5419. }
  5420. if( p->writableSchema ){
  5421. raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
  5422. p->writableSchema = 0;
  5423. }
  5424. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  5425. sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
  5426. raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
  5427. p->showHeader = savedShowHeader;
  5428. }else
  5429. if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
  5430. if( nArg==2 ){
  5431. setOrClearFlag(p, SHFLG_Echo, azArg[1]);
  5432. }else{
  5433. raw_printf(stderr, "Usage: .echo on|off\n");
  5434. rc = 1;
  5435. }
  5436. }else
  5437. if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
  5438. if( nArg==2 ){
  5439. if( strcmp(azArg[1],"full")==0 ){
  5440. p->autoEQP = 2;
  5441. }else{
  5442. p->autoEQP = booleanValue(azArg[1]);
  5443. }
  5444. }else{
  5445. raw_printf(stderr, "Usage: .eqp on|off|full\n");
  5446. rc = 1;
  5447. }
  5448. }else
  5449. if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
  5450. if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
  5451. rc = 2;
  5452. }else
  5453. /* The ".explain" command is automatic now. It is largely pointless. It
  5454. ** retained purely for backwards compatibility */
  5455. if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
  5456. int val = 1;
  5457. if( nArg>=2 ){
  5458. if( strcmp(azArg[1],"auto")==0 ){
  5459. val = 99;
  5460. }else{
  5461. val = booleanValue(azArg[1]);
  5462. }
  5463. }
  5464. if( val==1 && p->mode!=MODE_Explain ){
  5465. p->normalMode = p->mode;
  5466. p->mode = MODE_Explain;
  5467. p->autoExplain = 0;
  5468. }else if( val==0 ){
  5469. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  5470. p->autoExplain = 0;
  5471. }else if( val==99 ){
  5472. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  5473. p->autoExplain = 1;
  5474. }
  5475. }else
  5476. if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
  5477. ShellState data;
  5478. char *zErrMsg = 0;
  5479. int doStats = 0;
  5480. memcpy(&data, p, sizeof(data));
  5481. data.showHeader = 0;
  5482. data.cMode = data.mode = MODE_Semi;
  5483. if( nArg==2 && optionMatch(azArg[1], "indent") ){
  5484. data.cMode = data.mode = MODE_Pretty;
  5485. nArg = 1;
  5486. }
  5487. if( nArg!=1 ){
  5488. raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
  5489. rc = 1;
  5490. goto meta_command_exit;
  5491. }
  5492. open_db(p, 0);
  5493. rc = sqlite3_exec(p->db,
  5494. "SELECT sql FROM"
  5495. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  5496. " FROM sqlite_master UNION ALL"
  5497. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  5498. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  5499. "ORDER BY rowid",
  5500. callback, &data, &zErrMsg
  5501. );
  5502. if( rc==SQLITE_OK ){
  5503. sqlite3_stmt *pStmt;
  5504. rc = sqlite3_prepare_v2(p->db,
  5505. "SELECT rowid FROM sqlite_master"
  5506. " WHERE name GLOB 'sqlite_stat[134]'",
  5507. -1, &pStmt, 0);
  5508. doStats = sqlite3_step(pStmt)==SQLITE_ROW;
  5509. sqlite3_finalize(pStmt);
  5510. }
  5511. if( doStats==0 ){
  5512. raw_printf(p->out, "/* No STAT tables available */\n");
  5513. }else{
  5514. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  5515. sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
  5516. callback, &data, &zErrMsg);
  5517. data.cMode = data.mode = MODE_Insert;
  5518. data.zDestTable = "sqlite_stat1";
  5519. shell_exec(p->db, "SELECT * FROM sqlite_stat1",
  5520. shell_callback, &data,&zErrMsg);
  5521. data.zDestTable = "sqlite_stat3";
  5522. shell_exec(p->db, "SELECT * FROM sqlite_stat3",
  5523. shell_callback, &data,&zErrMsg);
  5524. data.zDestTable = "sqlite_stat4";
  5525. shell_exec(p->db, "SELECT * FROM sqlite_stat4",
  5526. shell_callback, &data, &zErrMsg);
  5527. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  5528. }
  5529. }else
  5530. if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
  5531. if( nArg==2 ){
  5532. p->showHeader = booleanValue(azArg[1]);
  5533. }else{
  5534. raw_printf(stderr, "Usage: .headers on|off\n");
  5535. rc = 1;
  5536. }
  5537. }else
  5538. if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  5539. utf8_printf(p->out, "%s", zHelp);
  5540. }else
  5541. if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
  5542. char *zTable; /* Insert data into this table */
  5543. char *zFile; /* Name of file to extra content from */
  5544. sqlite3_stmt *pStmt = NULL; /* A statement */
  5545. int nCol; /* Number of columns in the table */
  5546. int nByte; /* Number of bytes in an SQL string */
  5547. int i, j; /* Loop counters */
  5548. int needCommit; /* True to COMMIT or ROLLBACK at end */
  5549. int nSep; /* Number of bytes in p->colSeparator[] */
  5550. char *zSql; /* An SQL statement */
  5551. ImportCtx sCtx; /* Reader context */
  5552. char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
  5553. int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
  5554. if( nArg!=3 ){
  5555. raw_printf(stderr, "Usage: .import FILE TABLE\n");
  5556. goto meta_command_exit;
  5557. }
  5558. zFile = azArg[1];
  5559. zTable = azArg[2];
  5560. seenInterrupt = 0;
  5561. memset(&sCtx, 0, sizeof(sCtx));
  5562. open_db(p, 0);
  5563. nSep = strlen30(p->colSeparator);
  5564. if( nSep==0 ){
  5565. raw_printf(stderr,
  5566. "Error: non-null column separator required for import\n");
  5567. return 1;
  5568. }
  5569. if( nSep>1 ){
  5570. raw_printf(stderr, "Error: multi-character column separators not allowed"
  5571. " for import\n");
  5572. return 1;
  5573. }
  5574. nSep = strlen30(p->rowSeparator);
  5575. if( nSep==0 ){
  5576. raw_printf(stderr, "Error: non-null row separator required for import\n");
  5577. return 1;
  5578. }
  5579. if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
  5580. /* When importing CSV (only), if the row separator is set to the
  5581. ** default output row separator, change it to the default input
  5582. ** row separator. This avoids having to maintain different input
  5583. ** and output row separators. */
  5584. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  5585. nSep = strlen30(p->rowSeparator);
  5586. }
  5587. if( nSep>1 ){
  5588. raw_printf(stderr, "Error: multi-character row separators not allowed"
  5589. " for import\n");
  5590. return 1;
  5591. }
  5592. sCtx.zFile = zFile;
  5593. sCtx.nLine = 1;
  5594. if( sCtx.zFile[0]=='|' ){
  5595. #ifdef SQLITE_OMIT_POPEN
  5596. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  5597. return 1;
  5598. #else
  5599. sCtx.in = popen(sCtx.zFile+1, "r");
  5600. sCtx.zFile = "<pipe>";
  5601. xCloser = pclose;
  5602. #endif
  5603. }else{
  5604. sCtx.in = fopen(sCtx.zFile, "rb");
  5605. xCloser = fclose;
  5606. }
  5607. if( p->mode==MODE_Ascii ){
  5608. xRead = ascii_read_one_field;
  5609. }else{
  5610. xRead = csv_read_one_field;
  5611. }
  5612. if( sCtx.in==0 ){
  5613. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  5614. return 1;
  5615. }
  5616. sCtx.cColSep = p->colSeparator[0];
  5617. sCtx.cRowSep = p->rowSeparator[0];
  5618. zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
  5619. if( zSql==0 ){
  5620. raw_printf(stderr, "Error: out of memory\n");
  5621. xCloser(sCtx.in);
  5622. return 1;
  5623. }
  5624. nByte = strlen30(zSql);
  5625. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  5626. import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
  5627. if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
  5628. char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
  5629. char cSep = '(';
  5630. while( xRead(&sCtx) ){
  5631. zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
  5632. cSep = ',';
  5633. if( sCtx.cTerm!=sCtx.cColSep ) break;
  5634. }
  5635. if( cSep=='(' ){
  5636. sqlite3_free(zCreate);
  5637. sqlite3_free(sCtx.z);
  5638. xCloser(sCtx.in);
  5639. utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
  5640. return 1;
  5641. }
  5642. zCreate = sqlite3_mprintf("%z\n)", zCreate);
  5643. rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
  5644. sqlite3_free(zCreate);
  5645. if( rc ){
  5646. utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
  5647. sqlite3_errmsg(p->db));
  5648. sqlite3_free(sCtx.z);
  5649. xCloser(sCtx.in);
  5650. return 1;
  5651. }
  5652. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  5653. }
  5654. sqlite3_free(zSql);
  5655. if( rc ){
  5656. if (pStmt) sqlite3_finalize(pStmt);
  5657. utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
  5658. xCloser(sCtx.in);
  5659. return 1;
  5660. }
  5661. nCol = sqlite3_column_count(pStmt);
  5662. sqlite3_finalize(pStmt);
  5663. pStmt = 0;
  5664. if( nCol==0 ) return 0; /* no columns, no error */
  5665. zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
  5666. if( zSql==0 ){
  5667. raw_printf(stderr, "Error: out of memory\n");
  5668. xCloser(sCtx.in);
  5669. return 1;
  5670. }
  5671. sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
  5672. j = strlen30(zSql);
  5673. for(i=1; i<nCol; i++){
  5674. zSql[j++] = ',';
  5675. zSql[j++] = '?';
  5676. }
  5677. zSql[j++] = ')';
  5678. zSql[j] = 0;
  5679. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  5680. sqlite3_free(zSql);
  5681. if( rc ){
  5682. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  5683. if (pStmt) sqlite3_finalize(pStmt);
  5684. xCloser(sCtx.in);
  5685. return 1;
  5686. }
  5687. needCommit = sqlite3_get_autocommit(p->db);
  5688. if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
  5689. do{
  5690. int startLine = sCtx.nLine;
  5691. for(i=0; i<nCol; i++){
  5692. char *z = xRead(&sCtx);
  5693. /*
  5694. ** Did we reach end-of-file before finding any columns?
  5695. ** If so, stop instead of NULL filling the remaining columns.
  5696. */
  5697. if( z==0 && i==0 ) break;
  5698. /*
  5699. ** Did we reach end-of-file OR end-of-line before finding any
  5700. ** columns in ASCII mode? If so, stop instead of NULL filling
  5701. ** the remaining columns.
  5702. */
  5703. if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
  5704. sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
  5705. if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
  5706. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  5707. "filling the rest with NULL\n",
  5708. sCtx.zFile, startLine, nCol, i+1);
  5709. i += 2;
  5710. while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
  5711. }
  5712. }
  5713. if( sCtx.cTerm==sCtx.cColSep ){
  5714. do{
  5715. xRead(&sCtx);
  5716. i++;
  5717. }while( sCtx.cTerm==sCtx.cColSep );
  5718. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  5719. "extras ignored\n",
  5720. sCtx.zFile, startLine, nCol, i);
  5721. }
  5722. if( i>=nCol ){
  5723. sqlite3_step(pStmt);
  5724. rc = sqlite3_reset(pStmt);
  5725. if( rc!=SQLITE_OK ){
  5726. utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
  5727. startLine, sqlite3_errmsg(p->db));
  5728. }
  5729. }
  5730. }while( sCtx.cTerm!=EOF );
  5731. xCloser(sCtx.in);
  5732. sqlite3_free(sCtx.z);
  5733. sqlite3_finalize(pStmt);
  5734. if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
  5735. }else
  5736. #ifndef SQLITE_UNTESTABLE
  5737. if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
  5738. char *zSql;
  5739. char *zCollist = 0;
  5740. sqlite3_stmt *pStmt;
  5741. int tnum = 0;
  5742. int i;
  5743. if( nArg!=3 ){
  5744. utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
  5745. rc = 1;
  5746. goto meta_command_exit;
  5747. }
  5748. open_db(p, 0);
  5749. zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
  5750. " WHERE name='%q' AND type='index'", azArg[1]);
  5751. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  5752. sqlite3_free(zSql);
  5753. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  5754. tnum = sqlite3_column_int(pStmt, 0);
  5755. }
  5756. sqlite3_finalize(pStmt);
  5757. if( tnum==0 ){
  5758. utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
  5759. rc = 1;
  5760. goto meta_command_exit;
  5761. }
  5762. zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
  5763. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  5764. sqlite3_free(zSql);
  5765. i = 0;
  5766. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  5767. char zLabel[20];
  5768. const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
  5769. i++;
  5770. if( zCol==0 ){
  5771. if( sqlite3_column_int(pStmt,1)==-1 ){
  5772. zCol = "_ROWID_";
  5773. }else{
  5774. sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
  5775. zCol = zLabel;
  5776. }
  5777. }
  5778. if( zCollist==0 ){
  5779. zCollist = sqlite3_mprintf("\"%w\"", zCol);
  5780. }else{
  5781. zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
  5782. }
  5783. }
  5784. sqlite3_finalize(pStmt);
  5785. zSql = sqlite3_mprintf(
  5786. "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
  5787. azArg[2], zCollist, zCollist);
  5788. sqlite3_free(zCollist);
  5789. rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
  5790. if( rc==SQLITE_OK ){
  5791. rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
  5792. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
  5793. if( rc ){
  5794. utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
  5795. }else{
  5796. utf8_printf(stdout, "%s;\n", zSql);
  5797. raw_printf(stdout,
  5798. "WARNING: writing to an imposter table will corrupt the index!\n"
  5799. );
  5800. }
  5801. }else{
  5802. raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
  5803. rc = 1;
  5804. }
  5805. sqlite3_free(zSql);
  5806. }else
  5807. #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
  5808. #ifdef SQLITE_ENABLE_IOTRACE
  5809. if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
  5810. SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
  5811. if( iotrace && iotrace!=stdout ) fclose(iotrace);
  5812. iotrace = 0;
  5813. if( nArg<2 ){
  5814. sqlite3IoTrace = 0;
  5815. }else if( strcmp(azArg[1], "-")==0 ){
  5816. sqlite3IoTrace = iotracePrintf;
  5817. iotrace = stdout;
  5818. }else{
  5819. iotrace = fopen(azArg[1], "w");
  5820. if( iotrace==0 ){
  5821. utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  5822. sqlite3IoTrace = 0;
  5823. rc = 1;
  5824. }else{
  5825. sqlite3IoTrace = iotracePrintf;
  5826. }
  5827. }
  5828. }else
  5829. #endif
  5830. if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
  5831. static const struct {
  5832. const char *zLimitName; /* Name of a limit */
  5833. int limitCode; /* Integer code for that limit */
  5834. } aLimit[] = {
  5835. { "length", SQLITE_LIMIT_LENGTH },
  5836. { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
  5837. { "column", SQLITE_LIMIT_COLUMN },
  5838. { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
  5839. { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
  5840. { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
  5841. { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
  5842. { "attached", SQLITE_LIMIT_ATTACHED },
  5843. { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
  5844. { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
  5845. { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
  5846. { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
  5847. };
  5848. int i, n2;
  5849. open_db(p, 0);
  5850. if( nArg==1 ){
  5851. for(i=0; i<ArraySize(aLimit); i++){
  5852. printf("%20s %d\n", aLimit[i].zLimitName,
  5853. sqlite3_limit(p->db, aLimit[i].limitCode, -1));
  5854. }
  5855. }else if( nArg>3 ){
  5856. raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
  5857. rc = 1;
  5858. goto meta_command_exit;
  5859. }else{
  5860. int iLimit = -1;
  5861. n2 = strlen30(azArg[1]);
  5862. for(i=0; i<ArraySize(aLimit); i++){
  5863. if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
  5864. if( iLimit<0 ){
  5865. iLimit = i;
  5866. }else{
  5867. utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
  5868. rc = 1;
  5869. goto meta_command_exit;
  5870. }
  5871. }
  5872. }
  5873. if( iLimit<0 ){
  5874. utf8_printf(stderr, "unknown limit: \"%s\"\n"
  5875. "enter \".limits\" with no arguments for a list.\n",
  5876. azArg[1]);
  5877. rc = 1;
  5878. goto meta_command_exit;
  5879. }
  5880. if( nArg==3 ){
  5881. sqlite3_limit(p->db, aLimit[iLimit].limitCode,
  5882. (int)integerValue(azArg[2]));
  5883. }
  5884. printf("%20s %d\n", aLimit[iLimit].zLimitName,
  5885. sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
  5886. }
  5887. }else
  5888. if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
  5889. open_db(p, 0);
  5890. lintDotCommand(p, azArg, nArg);
  5891. }else
  5892. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  5893. if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
  5894. const char *zFile, *zProc;
  5895. char *zErrMsg = 0;
  5896. if( nArg<2 ){
  5897. raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
  5898. rc = 1;
  5899. goto meta_command_exit;
  5900. }
  5901. zFile = azArg[1];
  5902. zProc = nArg>=3 ? azArg[2] : 0;
  5903. open_db(p, 0);
  5904. rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  5905. if( rc!=SQLITE_OK ){
  5906. utf8_printf(stderr, "Error: %s\n", zErrMsg);
  5907. sqlite3_free(zErrMsg);
  5908. rc = 1;
  5909. }
  5910. }else
  5911. #endif
  5912. if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
  5913. if( nArg!=2 ){
  5914. raw_printf(stderr, "Usage: .log FILENAME\n");
  5915. rc = 1;
  5916. }else{
  5917. const char *zFile = azArg[1];
  5918. output_file_close(p->pLog);
  5919. p->pLog = output_file_open(zFile);
  5920. }
  5921. }else
  5922. if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
  5923. const char *zMode = nArg>=2 ? azArg[1] : "";
  5924. int n2 = (int)strlen(zMode);
  5925. int c2 = zMode[0];
  5926. if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
  5927. p->mode = MODE_Line;
  5928. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  5929. }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
  5930. p->mode = MODE_Column;
  5931. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  5932. }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
  5933. p->mode = MODE_List;
  5934. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
  5935. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  5936. }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
  5937. p->mode = MODE_Html;
  5938. }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
  5939. p->mode = MODE_Tcl;
  5940. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
  5941. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  5942. }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
  5943. p->mode = MODE_Csv;
  5944. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  5945. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  5946. }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
  5947. p->mode = MODE_List;
  5948. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
  5949. }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
  5950. p->mode = MODE_Insert;
  5951. set_table_name(p, nArg>=3 ? azArg[2] : "table");
  5952. }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
  5953. p->mode = MODE_Quote;
  5954. }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
  5955. p->mode = MODE_Ascii;
  5956. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
  5957. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
  5958. }else if( nArg==1 ){
  5959. raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
  5960. }else{
  5961. raw_printf(stderr, "Error: mode should be one of: "
  5962. "ascii column csv html insert line list quote tabs tcl\n");
  5963. rc = 1;
  5964. }
  5965. p->cMode = p->mode;
  5966. }else
  5967. if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
  5968. if( nArg==2 ){
  5969. sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
  5970. "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
  5971. }else{
  5972. raw_printf(stderr, "Usage: .nullvalue STRING\n");
  5973. rc = 1;
  5974. }
  5975. }else
  5976. if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
  5977. char *zNewFilename; /* Name of the database file to open */
  5978. int iName = 1; /* Index in azArg[] of the filename */
  5979. int newFlag = 0; /* True to delete file before opening */
  5980. /* Close the existing database */
  5981. session_close_all(p);
  5982. sqlite3_close(p->db);
  5983. p->db = 0;
  5984. p->zDbFilename = 0;
  5985. sqlite3_free(p->zFreeOnClose);
  5986. p->zFreeOnClose = 0;
  5987. /* Check for command-line arguments */
  5988. for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
  5989. const char *z = azArg[iName];
  5990. if( optionMatch(z,"new") ){
  5991. newFlag = 1;
  5992. }else if( z[0]=='-' ){
  5993. utf8_printf(stderr, "unknown option: %s\n", z);
  5994. rc = 1;
  5995. goto meta_command_exit;
  5996. }
  5997. }
  5998. /* If a filename is specified, try to open it first */
  5999. zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
  6000. if( zNewFilename ){
  6001. if( newFlag ) shellDeleteFile(zNewFilename);
  6002. p->zDbFilename = zNewFilename;
  6003. open_db(p, 1);
  6004. if( p->db==0 ){
  6005. utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
  6006. sqlite3_free(zNewFilename);
  6007. }else{
  6008. p->zFreeOnClose = zNewFilename;
  6009. }
  6010. }
  6011. if( p->db==0 ){
  6012. /* As a fall-back open a TEMP database */
  6013. p->zDbFilename = 0;
  6014. open_db(p, 0);
  6015. }
  6016. }else
  6017. if( c=='o'
  6018. && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
  6019. ){
  6020. const char *zFile = nArg>=2 ? azArg[1] : "stdout";
  6021. if( nArg>2 ){
  6022. utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
  6023. rc = 1;
  6024. goto meta_command_exit;
  6025. }
  6026. if( n>1 && strncmp(azArg[0], "once", n)==0 ){
  6027. if( nArg<2 ){
  6028. raw_printf(stderr, "Usage: .once FILE\n");
  6029. rc = 1;
  6030. goto meta_command_exit;
  6031. }
  6032. p->outCount = 2;
  6033. }else{
  6034. p->outCount = 0;
  6035. }
  6036. output_reset(p);
  6037. if( zFile[0]=='|' ){
  6038. #ifdef SQLITE_OMIT_POPEN
  6039. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  6040. rc = 1;
  6041. p->out = stdout;
  6042. #else
  6043. p->out = popen(zFile + 1, "w");
  6044. if( p->out==0 ){
  6045. utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
  6046. p->out = stdout;
  6047. rc = 1;
  6048. }else{
  6049. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  6050. }
  6051. #endif
  6052. }else{
  6053. p->out = output_file_open(zFile);
  6054. if( p->out==0 ){
  6055. if( strcmp(zFile,"off")!=0 ){
  6056. utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
  6057. }
  6058. p->out = stdout;
  6059. rc = 1;
  6060. } else {
  6061. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  6062. }
  6063. }
  6064. }else
  6065. if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
  6066. int i;
  6067. for(i=1; i<nArg; i++){
  6068. if( i>1 ) raw_printf(p->out, " ");
  6069. utf8_printf(p->out, "%s", azArg[i]);
  6070. }
  6071. raw_printf(p->out, "\n");
  6072. }else
  6073. if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
  6074. if( nArg >= 2) {
  6075. strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  6076. }
  6077. if( nArg >= 3) {
  6078. strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  6079. }
  6080. }else
  6081. if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
  6082. rc = 2;
  6083. }else
  6084. if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
  6085. FILE *alt;
  6086. if( nArg!=2 ){
  6087. raw_printf(stderr, "Usage: .read FILE\n");
  6088. rc = 1;
  6089. goto meta_command_exit;
  6090. }
  6091. alt = fopen(azArg[1], "rb");
  6092. if( alt==0 ){
  6093. utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
  6094. rc = 1;
  6095. }else{
  6096. rc = process_input(p, alt);
  6097. fclose(alt);
  6098. }
  6099. }else
  6100. if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
  6101. const char *zSrcFile;
  6102. const char *zDb;
  6103. sqlite3 *pSrc;
  6104. sqlite3_backup *pBackup;
  6105. int nTimeout = 0;
  6106. if( nArg==2 ){
  6107. zSrcFile = azArg[1];
  6108. zDb = "main";
  6109. }else if( nArg==3 ){
  6110. zSrcFile = azArg[2];
  6111. zDb = azArg[1];
  6112. }else{
  6113. raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
  6114. rc = 1;
  6115. goto meta_command_exit;
  6116. }
  6117. rc = sqlite3_open(zSrcFile, &pSrc);
  6118. if( rc!=SQLITE_OK ){
  6119. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  6120. sqlite3_close(pSrc);
  6121. return 1;
  6122. }
  6123. open_db(p, 0);
  6124. pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  6125. if( pBackup==0 ){
  6126. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  6127. sqlite3_close(pSrc);
  6128. return 1;
  6129. }
  6130. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  6131. || rc==SQLITE_BUSY ){
  6132. if( rc==SQLITE_BUSY ){
  6133. if( nTimeout++ >= 3 ) break;
  6134. sqlite3_sleep(100);
  6135. }
  6136. }
  6137. sqlite3_backup_finish(pBackup);
  6138. if( rc==SQLITE_DONE ){
  6139. rc = 0;
  6140. }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  6141. raw_printf(stderr, "Error: source database is busy\n");
  6142. rc = 1;
  6143. }else{
  6144. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  6145. rc = 1;
  6146. }
  6147. sqlite3_close(pSrc);
  6148. }else
  6149. if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
  6150. if( nArg==2 ){
  6151. p->scanstatsOn = booleanValue(azArg[1]);
  6152. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  6153. raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
  6154. #endif
  6155. }else{
  6156. raw_printf(stderr, "Usage: .scanstats on|off\n");
  6157. rc = 1;
  6158. }
  6159. }else
  6160. if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
  6161. ShellText sSelect;
  6162. ShellState data;
  6163. char *zErrMsg = 0;
  6164. const char *zDiv = 0;
  6165. int iSchema = 0;
  6166. open_db(p, 0);
  6167. memcpy(&data, p, sizeof(data));
  6168. data.showHeader = 0;
  6169. data.cMode = data.mode = MODE_Semi;
  6170. initText(&sSelect);
  6171. if( nArg>=2 && optionMatch(azArg[1], "indent") ){
  6172. data.cMode = data.mode = MODE_Pretty;
  6173. nArg--;
  6174. if( nArg==2 ) azArg[1] = azArg[2];
  6175. }
  6176. if( nArg==2 && azArg[1][0]!='-' ){
  6177. int i;
  6178. for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
  6179. if( strcmp(azArg[1],"sqlite_master")==0 ){
  6180. char *new_argv[2], *new_colv[2];
  6181. new_argv[0] = "CREATE TABLE sqlite_master (\n"
  6182. " type text,\n"
  6183. " name text,\n"
  6184. " tbl_name text,\n"
  6185. " rootpage integer,\n"
  6186. " sql text\n"
  6187. ")";
  6188. new_argv[1] = 0;
  6189. new_colv[0] = "sql";
  6190. new_colv[1] = 0;
  6191. callback(&data, 1, new_argv, new_colv);
  6192. rc = SQLITE_OK;
  6193. }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
  6194. char *new_argv[2], *new_colv[2];
  6195. new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
  6196. " type text,\n"
  6197. " name text,\n"
  6198. " tbl_name text,\n"
  6199. " rootpage integer,\n"
  6200. " sql text\n"
  6201. ")";
  6202. new_argv[1] = 0;
  6203. new_colv[0] = "sql";
  6204. new_colv[1] = 0;
  6205. callback(&data, 1, new_argv, new_colv);
  6206. rc = SQLITE_OK;
  6207. }else{
  6208. zDiv = "(";
  6209. }
  6210. }else if( nArg==1 ){
  6211. zDiv = "(";
  6212. }else{
  6213. raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
  6214. rc = 1;
  6215. goto meta_command_exit;
  6216. }
  6217. if( zDiv ){
  6218. sqlite3_stmt *pStmt = 0;
  6219. rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
  6220. -1, &pStmt, 0);
  6221. if( rc ){
  6222. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  6223. sqlite3_finalize(pStmt);
  6224. rc = 1;
  6225. goto meta_command_exit;
  6226. }
  6227. appendText(&sSelect, "SELECT sql FROM", 0);
  6228. iSchema = 0;
  6229. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  6230. const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
  6231. char zScNum[30];
  6232. sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
  6233. appendText(&sSelect, zDiv, 0);
  6234. zDiv = " UNION ALL ";
  6235. if( strcmp(zDb, "main")!=0 ){
  6236. appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
  6237. appendText(&sSelect, zDb, '"');
  6238. appendText(&sSelect, ") AS sql, type, tbl_name, name, rowid,", 0);
  6239. appendText(&sSelect, zScNum, 0);
  6240. appendText(&sSelect, " AS snum, ", 0);
  6241. appendText(&sSelect, zDb, '\'');
  6242. appendText(&sSelect, " AS sname FROM ", 0);
  6243. appendText(&sSelect, zDb, '"');
  6244. appendText(&sSelect, ".sqlite_master", 0);
  6245. }else{
  6246. appendText(&sSelect, "SELECT sql, type, tbl_name, name, rowid, ", 0);
  6247. appendText(&sSelect, zScNum, 0);
  6248. appendText(&sSelect, " AS snum, 'main' AS sname FROM sqlite_master",0);
  6249. }
  6250. }
  6251. sqlite3_finalize(pStmt);
  6252. appendText(&sSelect, ") WHERE ", 0);
  6253. if( nArg>1 ){
  6254. char *zQarg = sqlite3_mprintf("%Q", azArg[1]);
  6255. if( strchr(azArg[1], '.') ){
  6256. appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
  6257. }else{
  6258. appendText(&sSelect, "lower(tbl_name)", 0);
  6259. }
  6260. appendText(&sSelect, strchr(azArg[1], '*') ? " GLOB " : " LIKE ", 0);
  6261. appendText(&sSelect, zQarg, 0);
  6262. appendText(&sSelect, " AND ", 0);
  6263. sqlite3_free(zQarg);
  6264. }
  6265. appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
  6266. " ORDER BY snum, rowid", 0);
  6267. rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
  6268. freeText(&sSelect);
  6269. }
  6270. if( zErrMsg ){
  6271. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  6272. sqlite3_free(zErrMsg);
  6273. rc = 1;
  6274. }else if( rc != SQLITE_OK ){
  6275. raw_printf(stderr,"Error: querying schema information\n");
  6276. rc = 1;
  6277. }else{
  6278. rc = 0;
  6279. }
  6280. }else
  6281. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  6282. if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
  6283. sqlite3SelectTrace = (int)integerValue(azArg[1]);
  6284. }else
  6285. #endif
  6286. #if defined(SQLITE_ENABLE_SESSION)
  6287. if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
  6288. OpenSession *pSession = &p->aSession[0];
  6289. char **azCmd = &azArg[1];
  6290. int iSes = 0;
  6291. int nCmd = nArg - 1;
  6292. int i;
  6293. if( nArg<=1 ) goto session_syntax_error;
  6294. open_db(p, 0);
  6295. if( nArg>=3 ){
  6296. for(iSes=0; iSes<p->nSession; iSes++){
  6297. if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
  6298. }
  6299. if( iSes<p->nSession ){
  6300. pSession = &p->aSession[iSes];
  6301. azCmd++;
  6302. nCmd--;
  6303. }else{
  6304. pSession = &p->aSession[0];
  6305. iSes = 0;
  6306. }
  6307. }
  6308. /* .session attach TABLE
  6309. ** Invoke the sqlite3session_attach() interface to attach a particular
  6310. ** table so that it is never filtered.
  6311. */
  6312. if( strcmp(azCmd[0],"attach")==0 ){
  6313. if( nCmd!=2 ) goto session_syntax_error;
  6314. if( pSession->p==0 ){
  6315. session_not_open:
  6316. raw_printf(stderr, "ERROR: No sessions are open\n");
  6317. }else{
  6318. rc = sqlite3session_attach(pSession->p, azCmd[1]);
  6319. if( rc ){
  6320. raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
  6321. rc = 0;
  6322. }
  6323. }
  6324. }else
  6325. /* .session changeset FILE
  6326. ** .session patchset FILE
  6327. ** Write a changeset or patchset into a file. The file is overwritten.
  6328. */
  6329. if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
  6330. FILE *out = 0;
  6331. if( nCmd!=2 ) goto session_syntax_error;
  6332. if( pSession->p==0 ) goto session_not_open;
  6333. out = fopen(azCmd[1], "wb");
  6334. if( out==0 ){
  6335. utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
  6336. }else{
  6337. int szChng;
  6338. void *pChng;
  6339. if( azCmd[0][0]=='c' ){
  6340. rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
  6341. }else{
  6342. rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
  6343. }
  6344. if( rc ){
  6345. printf("Error: error code %d\n", rc);
  6346. rc = 0;
  6347. }
  6348. if( pChng
  6349. && fwrite(pChng, szChng, 1, out)!=1 ){
  6350. raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
  6351. szChng);
  6352. }
  6353. sqlite3_free(pChng);
  6354. fclose(out);
  6355. }
  6356. }else
  6357. /* .session close
  6358. ** Close the identified session
  6359. */
  6360. if( strcmp(azCmd[0], "close")==0 ){
  6361. if( nCmd!=1 ) goto session_syntax_error;
  6362. if( p->nSession ){
  6363. session_close(pSession);
  6364. p->aSession[iSes] = p->aSession[--p->nSession];
  6365. }
  6366. }else
  6367. /* .session enable ?BOOLEAN?
  6368. ** Query or set the enable flag
  6369. */
  6370. if( strcmp(azCmd[0], "enable")==0 ){
  6371. int ii;
  6372. if( nCmd>2 ) goto session_syntax_error;
  6373. ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  6374. if( p->nSession ){
  6375. ii = sqlite3session_enable(pSession->p, ii);
  6376. utf8_printf(p->out, "session %s enable flag = %d\n",
  6377. pSession->zName, ii);
  6378. }
  6379. }else
  6380. /* .session filter GLOB ....
  6381. ** Set a list of GLOB patterns of table names to be excluded.
  6382. */
  6383. if( strcmp(azCmd[0], "filter")==0 ){
  6384. int ii, nByte;
  6385. if( nCmd<2 ) goto session_syntax_error;
  6386. if( p->nSession ){
  6387. for(ii=0; ii<pSession->nFilter; ii++){
  6388. sqlite3_free(pSession->azFilter[ii]);
  6389. }
  6390. sqlite3_free(pSession->azFilter);
  6391. nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
  6392. pSession->azFilter = sqlite3_malloc( nByte );
  6393. if( pSession->azFilter==0 ){
  6394. raw_printf(stderr, "Error: out or memory\n");
  6395. exit(1);
  6396. }
  6397. for(ii=1; ii<nCmd; ii++){
  6398. pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
  6399. }
  6400. pSession->nFilter = ii-1;
  6401. }
  6402. }else
  6403. /* .session indirect ?BOOLEAN?
  6404. ** Query or set the indirect flag
  6405. */
  6406. if( strcmp(azCmd[0], "indirect")==0 ){
  6407. int ii;
  6408. if( nCmd>2 ) goto session_syntax_error;
  6409. ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  6410. if( p->nSession ){
  6411. ii = sqlite3session_indirect(pSession->p, ii);
  6412. utf8_printf(p->out, "session %s indirect flag = %d\n",
  6413. pSession->zName, ii);
  6414. }
  6415. }else
  6416. /* .session isempty
  6417. ** Determine if the session is empty
  6418. */
  6419. if( strcmp(azCmd[0], "isempty")==0 ){
  6420. int ii;
  6421. if( nCmd!=1 ) goto session_syntax_error;
  6422. if( p->nSession ){
  6423. ii = sqlite3session_isempty(pSession->p);
  6424. utf8_printf(p->out, "session %s isempty flag = %d\n",
  6425. pSession->zName, ii);
  6426. }
  6427. }else
  6428. /* .session list
  6429. ** List all currently open sessions
  6430. */
  6431. if( strcmp(azCmd[0],"list")==0 ){
  6432. for(i=0; i<p->nSession; i++){
  6433. utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
  6434. }
  6435. }else
  6436. /* .session open DB NAME
  6437. ** Open a new session called NAME on the attached database DB.
  6438. ** DB is normally "main".
  6439. */
  6440. if( strcmp(azCmd[0],"open")==0 ){
  6441. char *zName;
  6442. if( nCmd!=3 ) goto session_syntax_error;
  6443. zName = azCmd[2];
  6444. if( zName[0]==0 ) goto session_syntax_error;
  6445. for(i=0; i<p->nSession; i++){
  6446. if( strcmp(p->aSession[i].zName,zName)==0 ){
  6447. utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
  6448. goto meta_command_exit;
  6449. }
  6450. }
  6451. if( p->nSession>=ArraySize(p->aSession) ){
  6452. raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
  6453. goto meta_command_exit;
  6454. }
  6455. pSession = &p->aSession[p->nSession];
  6456. rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
  6457. if( rc ){
  6458. raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
  6459. rc = 0;
  6460. goto meta_command_exit;
  6461. }
  6462. pSession->nFilter = 0;
  6463. sqlite3session_table_filter(pSession->p, session_filter, pSession);
  6464. p->nSession++;
  6465. pSession->zName = sqlite3_mprintf("%s", zName);
  6466. }else
  6467. /* If no command name matches, show a syntax error */
  6468. session_syntax_error:
  6469. session_help(p);
  6470. }else
  6471. #endif
  6472. #ifdef SQLITE_DEBUG
  6473. /* Undocumented commands for internal testing. Subject to change
  6474. ** without notice. */
  6475. if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
  6476. if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
  6477. int i, v;
  6478. for(i=1; i<nArg; i++){
  6479. v = booleanValue(azArg[i]);
  6480. utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
  6481. }
  6482. }
  6483. if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
  6484. int i; sqlite3_int64 v;
  6485. for(i=1; i<nArg; i++){
  6486. char zBuf[200];
  6487. v = integerValue(azArg[i]);
  6488. sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
  6489. utf8_printf(p->out, "%s", zBuf);
  6490. }
  6491. }
  6492. }else
  6493. #endif
  6494. if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
  6495. int bIsInit = 0; /* True to initialize the SELFTEST table */
  6496. int bVerbose = 0; /* Verbose output */
  6497. int bSelftestExists; /* True if SELFTEST already exists */
  6498. int i, k; /* Loop counters */
  6499. int nTest = 0; /* Number of tests runs */
  6500. int nErr = 0; /* Number of errors seen */
  6501. ShellText str; /* Answer for a query */
  6502. sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
  6503. open_db(p,0);
  6504. for(i=1; i<nArg; i++){
  6505. const char *z = azArg[i];
  6506. if( z[0]=='-' && z[1]=='-' ) z++;
  6507. if( strcmp(z,"-init")==0 ){
  6508. bIsInit = 1;
  6509. }else
  6510. if( strcmp(z,"-v")==0 ){
  6511. bVerbose++;
  6512. }else
  6513. {
  6514. utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
  6515. azArg[i], azArg[0]);
  6516. raw_printf(stderr, "Should be one of: --init -v\n");
  6517. rc = 1;
  6518. goto meta_command_exit;
  6519. }
  6520. }
  6521. if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
  6522. != SQLITE_OK ){
  6523. bSelftestExists = 0;
  6524. }else{
  6525. bSelftestExists = 1;
  6526. }
  6527. if( bIsInit ){
  6528. createSelftestTable(p);
  6529. bSelftestExists = 1;
  6530. }
  6531. initText(&str);
  6532. appendText(&str, "x", 0);
  6533. for(k=bSelftestExists; k>=0; k--){
  6534. if( k==1 ){
  6535. rc = sqlite3_prepare_v2(p->db,
  6536. "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
  6537. -1, &pStmt, 0);
  6538. }else{
  6539. rc = sqlite3_prepare_v2(p->db,
  6540. "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
  6541. " (1,'run','PRAGMA integrity_check','ok')",
  6542. -1, &pStmt, 0);
  6543. }
  6544. if( rc ){
  6545. raw_printf(stderr, "Error querying the selftest table\n");
  6546. rc = 1;
  6547. sqlite3_finalize(pStmt);
  6548. goto meta_command_exit;
  6549. }
  6550. for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
  6551. int tno = sqlite3_column_int(pStmt, 0);
  6552. const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
  6553. const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
  6554. const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
  6555. k = 0;
  6556. if( bVerbose>0 ){
  6557. char *zQuote = sqlite3_mprintf("%q", zSql);
  6558. printf("%d: %s %s\n", tno, zOp, zSql);
  6559. sqlite3_free(zQuote);
  6560. }
  6561. if( strcmp(zOp,"memo")==0 ){
  6562. utf8_printf(p->out, "%s\n", zSql);
  6563. }else
  6564. if( strcmp(zOp,"run")==0 ){
  6565. char *zErrMsg = 0;
  6566. str.n = 0;
  6567. str.z[0] = 0;
  6568. rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
  6569. nTest++;
  6570. if( bVerbose ){
  6571. utf8_printf(p->out, "Result: %s\n", str.z);
  6572. }
  6573. if( rc || zErrMsg ){
  6574. nErr++;
  6575. rc = 1;
  6576. utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
  6577. sqlite3_free(zErrMsg);
  6578. }else if( strcmp(zAns,str.z)!=0 ){
  6579. nErr++;
  6580. rc = 1;
  6581. utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
  6582. utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
  6583. }
  6584. }else
  6585. {
  6586. utf8_printf(stderr,
  6587. "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
  6588. rc = 1;
  6589. break;
  6590. }
  6591. } /* End loop over rows of content from SELFTEST */
  6592. sqlite3_finalize(pStmt);
  6593. } /* End loop over k */
  6594. freeText(&str);
  6595. utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
  6596. }else
  6597. if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
  6598. if( nArg<2 || nArg>3 ){
  6599. raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
  6600. rc = 1;
  6601. }
  6602. if( nArg>=2 ){
  6603. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
  6604. "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
  6605. }
  6606. if( nArg>=3 ){
  6607. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
  6608. "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
  6609. }
  6610. }else
  6611. if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
  6612. const char *zLike = 0; /* Which table to checksum. 0 means everything */
  6613. int i; /* Loop counter */
  6614. int bSchema = 0; /* Also hash the schema */
  6615. int bSeparate = 0; /* Hash each table separately */
  6616. int iSize = 224; /* Hash algorithm to use */
  6617. int bDebug = 0; /* Only show the query that would have run */
  6618. sqlite3_stmt *pStmt; /* For querying tables names */
  6619. char *zSql; /* SQL to be run */
  6620. char *zSep; /* Separator */
  6621. ShellText sSql; /* Complete SQL for the query to run the hash */
  6622. ShellText sQuery; /* Set of queries used to read all content */
  6623. open_db(p, 0);
  6624. for(i=1; i<nArg; i++){
  6625. const char *z = azArg[i];
  6626. if( z[0]=='-' ){
  6627. z++;
  6628. if( z[0]=='-' ) z++;
  6629. if( strcmp(z,"schema")==0 ){
  6630. bSchema = 1;
  6631. }else
  6632. if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
  6633. || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
  6634. ){
  6635. iSize = atoi(&z[5]);
  6636. }else
  6637. if( strcmp(z,"debug")==0 ){
  6638. bDebug = 1;
  6639. }else
  6640. {
  6641. utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
  6642. azArg[i], azArg[0]);
  6643. raw_printf(stderr, "Should be one of: --schema"
  6644. " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
  6645. rc = 1;
  6646. goto meta_command_exit;
  6647. }
  6648. }else if( zLike ){
  6649. raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
  6650. rc = 1;
  6651. goto meta_command_exit;
  6652. }else{
  6653. zLike = z;
  6654. bSeparate = 1;
  6655. if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
  6656. }
  6657. }
  6658. if( bSchema ){
  6659. zSql = "SELECT lower(name) FROM sqlite_master"
  6660. " WHERE type='table' AND coalesce(rootpage,0)>1"
  6661. " UNION ALL SELECT 'sqlite_master'"
  6662. " ORDER BY 1 collate nocase";
  6663. }else{
  6664. zSql = "SELECT lower(name) FROM sqlite_master"
  6665. " WHERE type='table' AND coalesce(rootpage,0)>1"
  6666. " AND name NOT LIKE 'sqlite_%'"
  6667. " ORDER BY 1 collate nocase";
  6668. }
  6669. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  6670. initText(&sQuery);
  6671. initText(&sSql);
  6672. appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
  6673. zSep = "VALUES(";
  6674. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  6675. const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
  6676. if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
  6677. if( strncmp(zTab, "sqlite_",7)!=0 ){
  6678. appendText(&sQuery,"SELECT * FROM ", 0);
  6679. appendText(&sQuery,zTab,'"');
  6680. appendText(&sQuery," NOT INDEXED;", 0);
  6681. }else if( strcmp(zTab, "sqlite_master")==0 ){
  6682. appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
  6683. " ORDER BY name;", 0);
  6684. }else if( strcmp(zTab, "sqlite_sequence")==0 ){
  6685. appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
  6686. " ORDER BY name;", 0);
  6687. }else if( strcmp(zTab, "sqlite_stat1")==0 ){
  6688. appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
  6689. " ORDER BY tbl,idx;", 0);
  6690. }else if( strcmp(zTab, "sqlite_stat3")==0
  6691. || strcmp(zTab, "sqlite_stat4")==0 ){
  6692. appendText(&sQuery, "SELECT * FROM ", 0);
  6693. appendText(&sQuery, zTab, 0);
  6694. appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
  6695. }
  6696. appendText(&sSql, zSep, 0);
  6697. appendText(&sSql, sQuery.z, '\'');
  6698. sQuery.n = 0;
  6699. appendText(&sSql, ",", 0);
  6700. appendText(&sSql, zTab, '\'');
  6701. zSep = "),(";
  6702. }
  6703. sqlite3_finalize(pStmt);
  6704. if( bSeparate ){
  6705. zSql = sqlite3_mprintf(
  6706. "%s))"
  6707. " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
  6708. " FROM [sha3sum$query]",
  6709. sSql.z, iSize);
  6710. }else{
  6711. zSql = sqlite3_mprintf(
  6712. "%s))"
  6713. " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
  6714. " FROM [sha3sum$query]",
  6715. sSql.z, iSize);
  6716. }
  6717. freeText(&sQuery);
  6718. freeText(&sSql);
  6719. if( bDebug ){
  6720. utf8_printf(p->out, "%s\n", zSql);
  6721. }else{
  6722. shell_exec(p->db, zSql, shell_callback, p, 0);
  6723. }
  6724. sqlite3_free(zSql);
  6725. }else
  6726. if( c=='s'
  6727. && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
  6728. ){
  6729. char *zCmd;
  6730. int i, x;
  6731. if( nArg<2 ){
  6732. raw_printf(stderr, "Usage: .system COMMAND\n");
  6733. rc = 1;
  6734. goto meta_command_exit;
  6735. }
  6736. zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
  6737. for(i=2; i<nArg; i++){
  6738. zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
  6739. zCmd, azArg[i]);
  6740. }
  6741. x = system(zCmd);
  6742. sqlite3_free(zCmd);
  6743. if( x ) raw_printf(stderr, "System command returns %d\n", x);
  6744. }else
  6745. if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
  6746. static const char *azBool[] = { "off", "on", "full", "unk" };
  6747. int i;
  6748. if( nArg!=1 ){
  6749. raw_printf(stderr, "Usage: .show\n");
  6750. rc = 1;
  6751. goto meta_command_exit;
  6752. }
  6753. utf8_printf(p->out, "%12.12s: %s\n","echo",
  6754. azBool[ShellHasFlag(p, SHFLG_Echo)]);
  6755. utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
  6756. utf8_printf(p->out, "%12.12s: %s\n","explain",
  6757. p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
  6758. utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
  6759. utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
  6760. utf8_printf(p->out, "%12.12s: ", "nullvalue");
  6761. output_c_string(p->out, p->nullValue);
  6762. raw_printf(p->out, "\n");
  6763. utf8_printf(p->out,"%12.12s: %s\n","output",
  6764. strlen30(p->outfile) ? p->outfile : "stdout");
  6765. utf8_printf(p->out,"%12.12s: ", "colseparator");
  6766. output_c_string(p->out, p->colSeparator);
  6767. raw_printf(p->out, "\n");
  6768. utf8_printf(p->out,"%12.12s: ", "rowseparator");
  6769. output_c_string(p->out, p->rowSeparator);
  6770. raw_printf(p->out, "\n");
  6771. utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
  6772. utf8_printf(p->out, "%12.12s: ", "width");
  6773. for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
  6774. raw_printf(p->out, "%d ", p->colWidth[i]);
  6775. }
  6776. raw_printf(p->out, "\n");
  6777. utf8_printf(p->out, "%12.12s: %s\n", "filename",
  6778. p->zDbFilename ? p->zDbFilename : "");
  6779. }else
  6780. if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
  6781. if( nArg==2 ){
  6782. p->statsOn = booleanValue(azArg[1]);
  6783. }else if( nArg==1 ){
  6784. display_stats(p->db, p, 0);
  6785. }else{
  6786. raw_printf(stderr, "Usage: .stats ?on|off?\n");
  6787. rc = 1;
  6788. }
  6789. }else
  6790. if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
  6791. || (c=='i' && (strncmp(azArg[0], "indices", n)==0
  6792. || strncmp(azArg[0], "indexes", n)==0) )
  6793. ){
  6794. sqlite3_stmt *pStmt;
  6795. char **azResult;
  6796. int nRow, nAlloc;
  6797. int ii;
  6798. ShellText s;
  6799. initText(&s);
  6800. open_db(p, 0);
  6801. rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
  6802. if( rc ) return shellDatabaseError(p->db);
  6803. if( nArg>2 && c=='i' ){
  6804. /* It is an historical accident that the .indexes command shows an error
  6805. ** when called with the wrong number of arguments whereas the .tables
  6806. ** command does not. */
  6807. raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
  6808. rc = 1;
  6809. goto meta_command_exit;
  6810. }
  6811. for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
  6812. const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
  6813. if( zDbName==0 ) continue;
  6814. if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
  6815. if( sqlite3_stricmp(zDbName, "main")==0 ){
  6816. appendText(&s, "SELECT name FROM ", 0);
  6817. }else{
  6818. appendText(&s, "SELECT ", 0);
  6819. appendText(&s, zDbName, '\'');
  6820. appendText(&s, "||'.'||name FROM ", 0);
  6821. }
  6822. appendText(&s, zDbName, '"');
  6823. appendText(&s, ".sqlite_master ", 0);
  6824. if( c=='t' ){
  6825. appendText(&s," WHERE type IN ('table','view')"
  6826. " AND name NOT LIKE 'sqlite_%'"
  6827. " AND name LIKE ?1", 0);
  6828. }else{
  6829. appendText(&s," WHERE type='index'"
  6830. " AND tbl_name LIKE ?1", 0);
  6831. }
  6832. }
  6833. rc = sqlite3_finalize(pStmt);
  6834. appendText(&s, " ORDER BY 1", 0);
  6835. rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
  6836. freeText(&s);
  6837. if( rc ) return shellDatabaseError(p->db);
  6838. /* Run the SQL statement prepared by the above block. Store the results
  6839. ** as an array of nul-terminated strings in azResult[]. */
  6840. nRow = nAlloc = 0;
  6841. azResult = 0;
  6842. if( nArg>1 ){
  6843. sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
  6844. }else{
  6845. sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
  6846. }
  6847. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  6848. if( nRow>=nAlloc ){
  6849. char **azNew;
  6850. int n2 = nAlloc*2 + 10;
  6851. azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
  6852. if( azNew==0 ){
  6853. rc = shellNomemError();
  6854. break;
  6855. }
  6856. nAlloc = n2;
  6857. azResult = azNew;
  6858. }
  6859. azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  6860. if( 0==azResult[nRow] ){
  6861. rc = shellNomemError();
  6862. break;
  6863. }
  6864. nRow++;
  6865. }
  6866. if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
  6867. rc = shellDatabaseError(p->db);
  6868. }
  6869. /* Pretty-print the contents of array azResult[] to the output */
  6870. if( rc==0 && nRow>0 ){
  6871. int len, maxlen = 0;
  6872. int i, j;
  6873. int nPrintCol, nPrintRow;
  6874. for(i=0; i<nRow; i++){
  6875. len = strlen30(azResult[i]);
  6876. if( len>maxlen ) maxlen = len;
  6877. }
  6878. nPrintCol = 80/(maxlen+2);
  6879. if( nPrintCol<1 ) nPrintCol = 1;
  6880. nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  6881. for(i=0; i<nPrintRow; i++){
  6882. for(j=i; j<nRow; j+=nPrintRow){
  6883. char *zSp = j<nPrintRow ? "" : " ";
  6884. utf8_printf(p->out, "%s%-*s", zSp, maxlen,
  6885. azResult[j] ? azResult[j]:"");
  6886. }
  6887. raw_printf(p->out, "\n");
  6888. }
  6889. }
  6890. for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
  6891. sqlite3_free(azResult);
  6892. }else
  6893. /* Begin redirecting output to the file "testcase-out.txt" */
  6894. if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
  6895. output_reset(p);
  6896. p->out = output_file_open("testcase-out.txt");
  6897. if( p->out==0 ){
  6898. raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
  6899. }
  6900. if( nArg>=2 ){
  6901. sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
  6902. }else{
  6903. sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
  6904. }
  6905. }else
  6906. #ifndef SQLITE_UNTESTABLE
  6907. if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
  6908. static const struct {
  6909. const char *zCtrlName; /* Name of a test-control option */
  6910. int ctrlCode; /* Integer code for that option */
  6911. } aCtrl[] = {
  6912. { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
  6913. { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
  6914. { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
  6915. { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
  6916. { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
  6917. { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
  6918. { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
  6919. { "assert", SQLITE_TESTCTRL_ASSERT },
  6920. { "always", SQLITE_TESTCTRL_ALWAYS },
  6921. { "reserve", SQLITE_TESTCTRL_RESERVE },
  6922. { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
  6923. { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
  6924. { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
  6925. { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
  6926. { "imposter", SQLITE_TESTCTRL_IMPOSTER },
  6927. };
  6928. int testctrl = -1;
  6929. int rc2 = 0;
  6930. int i, n2;
  6931. open_db(p, 0);
  6932. /* convert testctrl text option to value. allow any unique prefix
  6933. ** of the option name, or a numerical value. */
  6934. n2 = strlen30(azArg[1]);
  6935. for(i=0; i<ArraySize(aCtrl); i++){
  6936. if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
  6937. if( testctrl<0 ){
  6938. testctrl = aCtrl[i].ctrlCode;
  6939. }else{
  6940. utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
  6941. testctrl = -1;
  6942. break;
  6943. }
  6944. }
  6945. }
  6946. if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
  6947. if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
  6948. utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
  6949. }else{
  6950. switch(testctrl){
  6951. /* sqlite3_test_control(int, db, int) */
  6952. case SQLITE_TESTCTRL_OPTIMIZATIONS:
  6953. case SQLITE_TESTCTRL_RESERVE:
  6954. if( nArg==3 ){
  6955. int opt = (int)strtol(azArg[2], 0, 0);
  6956. rc2 = sqlite3_test_control(testctrl, p->db, opt);
  6957. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  6958. } else {
  6959. utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
  6960. azArg[1]);
  6961. }
  6962. break;
  6963. /* sqlite3_test_control(int) */
  6964. case SQLITE_TESTCTRL_PRNG_SAVE:
  6965. case SQLITE_TESTCTRL_PRNG_RESTORE:
  6966. case SQLITE_TESTCTRL_PRNG_RESET:
  6967. case SQLITE_TESTCTRL_BYTEORDER:
  6968. if( nArg==2 ){
  6969. rc2 = sqlite3_test_control(testctrl);
  6970. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  6971. } else {
  6972. utf8_printf(stderr,"Error: testctrl %s takes no options\n",
  6973. azArg[1]);
  6974. }
  6975. break;
  6976. /* sqlite3_test_control(int, uint) */
  6977. case SQLITE_TESTCTRL_PENDING_BYTE:
  6978. if( nArg==3 ){
  6979. unsigned int opt = (unsigned int)integerValue(azArg[2]);
  6980. rc2 = sqlite3_test_control(testctrl, opt);
  6981. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  6982. } else {
  6983. utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
  6984. " int option\n", azArg[1]);
  6985. }
  6986. break;
  6987. /* sqlite3_test_control(int, int) */
  6988. case SQLITE_TESTCTRL_ASSERT:
  6989. case SQLITE_TESTCTRL_ALWAYS:
  6990. case SQLITE_TESTCTRL_NEVER_CORRUPT:
  6991. if( nArg==3 ){
  6992. int opt = booleanValue(azArg[2]);
  6993. rc2 = sqlite3_test_control(testctrl, opt);
  6994. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  6995. } else {
  6996. utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
  6997. azArg[1]);
  6998. }
  6999. break;
  7000. /* sqlite3_test_control(int, char *) */
  7001. #ifdef SQLITE_N_KEYWORD
  7002. case SQLITE_TESTCTRL_ISKEYWORD:
  7003. if( nArg==3 ){
  7004. const char *opt = azArg[2];
  7005. rc2 = sqlite3_test_control(testctrl, opt);
  7006. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  7007. } else {
  7008. utf8_printf(stderr,
  7009. "Error: testctrl %s takes a single char * option\n",
  7010. azArg[1]);
  7011. }
  7012. break;
  7013. #endif
  7014. case SQLITE_TESTCTRL_IMPOSTER:
  7015. if( nArg==5 ){
  7016. rc2 = sqlite3_test_control(testctrl, p->db,
  7017. azArg[2],
  7018. integerValue(azArg[3]),
  7019. integerValue(azArg[4]));
  7020. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  7021. }else{
  7022. raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
  7023. }
  7024. break;
  7025. case SQLITE_TESTCTRL_BITVEC_TEST:
  7026. case SQLITE_TESTCTRL_FAULT_INSTALL:
  7027. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
  7028. default:
  7029. utf8_printf(stderr,
  7030. "Error: CLI support for testctrl %s not implemented\n",
  7031. azArg[1]);
  7032. break;
  7033. }
  7034. }
  7035. }else
  7036. #endif /* !defined(SQLITE_UNTESTABLE) */
  7037. if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
  7038. open_db(p, 0);
  7039. sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
  7040. }else
  7041. if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
  7042. if( nArg==2 ){
  7043. enableTimer = booleanValue(azArg[1]);
  7044. if( enableTimer && !HAS_TIMER ){
  7045. raw_printf(stderr, "Error: timer not available on this system.\n");
  7046. enableTimer = 0;
  7047. }
  7048. }else{
  7049. raw_printf(stderr, "Usage: .timer on|off\n");
  7050. rc = 1;
  7051. }
  7052. }else
  7053. if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
  7054. open_db(p, 0);
  7055. if( nArg!=2 ){
  7056. raw_printf(stderr, "Usage: .trace FILE|off\n");
  7057. rc = 1;
  7058. goto meta_command_exit;
  7059. }
  7060. output_file_close(p->traceOut);
  7061. p->traceOut = output_file_open(azArg[1]);
  7062. #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
  7063. if( p->traceOut==0 ){
  7064. sqlite3_trace_v2(p->db, 0, 0, 0);
  7065. }else{
  7066. sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
  7067. }
  7068. #endif
  7069. }else
  7070. #if SQLITE_USER_AUTHENTICATION
  7071. if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
  7072. if( nArg<2 ){
  7073. raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
  7074. rc = 1;
  7075. goto meta_command_exit;
  7076. }
  7077. open_db(p, 0);
  7078. if( strcmp(azArg[1],"login")==0 ){
  7079. if( nArg!=4 ){
  7080. raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
  7081. rc = 1;
  7082. goto meta_command_exit;
  7083. }
  7084. rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
  7085. (int)strlen(azArg[3]));
  7086. if( rc ){
  7087. utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
  7088. rc = 1;
  7089. }
  7090. }else if( strcmp(azArg[1],"add")==0 ){
  7091. if( nArg!=5 ){
  7092. raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
  7093. rc = 1;
  7094. goto meta_command_exit;
  7095. }
  7096. rc = sqlite3_user_add(p->db, azArg[2],
  7097. azArg[3], (int)strlen(azArg[3]),
  7098. booleanValue(azArg[4]));
  7099. if( rc ){
  7100. raw_printf(stderr, "User-Add failed: %d\n", rc);
  7101. rc = 1;
  7102. }
  7103. }else if( strcmp(azArg[1],"edit")==0 ){
  7104. if( nArg!=5 ){
  7105. raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
  7106. rc = 1;
  7107. goto meta_command_exit;
  7108. }
  7109. rc = sqlite3_user_change(p->db, azArg[2],
  7110. azArg[3], (int)strlen(azArg[3]),
  7111. booleanValue(azArg[4]));
  7112. if( rc ){
  7113. raw_printf(stderr, "User-Edit failed: %d\n", rc);
  7114. rc = 1;
  7115. }
  7116. }else if( strcmp(azArg[1],"delete")==0 ){
  7117. if( nArg!=3 ){
  7118. raw_printf(stderr, "Usage: .user delete USER\n");
  7119. rc = 1;
  7120. goto meta_command_exit;
  7121. }
  7122. rc = sqlite3_user_delete(p->db, azArg[2]);
  7123. if( rc ){
  7124. raw_printf(stderr, "User-Delete failed: %d\n", rc);
  7125. rc = 1;
  7126. }
  7127. }else{
  7128. raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
  7129. rc = 1;
  7130. goto meta_command_exit;
  7131. }
  7132. }else
  7133. #endif /* SQLITE_USER_AUTHENTICATION */
  7134. if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
  7135. utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
  7136. sqlite3_libversion(), sqlite3_sourceid());
  7137. }else
  7138. if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
  7139. const char *zDbName = nArg==2 ? azArg[1] : "main";
  7140. sqlite3_vfs *pVfs = 0;
  7141. if( p->db ){
  7142. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
  7143. if( pVfs ){
  7144. utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
  7145. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  7146. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  7147. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  7148. }
  7149. }
  7150. }else
  7151. if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
  7152. sqlite3_vfs *pVfs;
  7153. sqlite3_vfs *pCurrent = 0;
  7154. if( p->db ){
  7155. sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
  7156. }
  7157. for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
  7158. utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
  7159. pVfs==pCurrent ? " <--- CURRENT" : "");
  7160. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  7161. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  7162. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  7163. if( pVfs->pNext ){
  7164. raw_printf(p->out, "-----------------------------------\n");
  7165. }
  7166. }
  7167. }else
  7168. if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
  7169. const char *zDbName = nArg==2 ? azArg[1] : "main";
  7170. char *zVfsName = 0;
  7171. if( p->db ){
  7172. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
  7173. if( zVfsName ){
  7174. utf8_printf(p->out, "%s\n", zVfsName);
  7175. sqlite3_free(zVfsName);
  7176. }
  7177. }
  7178. }else
  7179. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  7180. if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
  7181. sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
  7182. }else
  7183. #endif
  7184. if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
  7185. int j;
  7186. assert( nArg<=ArraySize(azArg) );
  7187. for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
  7188. p->colWidth[j-1] = (int)integerValue(azArg[j]);
  7189. }
  7190. }else
  7191. {
  7192. utf8_printf(stderr, "Error: unknown command or invalid arguments: "
  7193. " \"%s\". Enter \".help\" for help\n", azArg[0]);
  7194. rc = 1;
  7195. }
  7196. meta_command_exit:
  7197. if( p->outCount ){
  7198. p->outCount--;
  7199. if( p->outCount==0 ) output_reset(p);
  7200. }
  7201. return rc;
  7202. }
  7203. /*
  7204. ** Return TRUE if a semicolon occurs anywhere in the first N characters
  7205. ** of string z[].
  7206. */
  7207. static int line_contains_semicolon(const char *z, int N){
  7208. int i;
  7209. for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
  7210. return 0;
  7211. }
  7212. /*
  7213. ** Test to see if a line consists entirely of whitespace.
  7214. */
  7215. static int _all_whitespace(const char *z){
  7216. for(; *z; z++){
  7217. if( IsSpace(z[0]) ) continue;
  7218. if( *z=='/' && z[1]=='*' ){
  7219. z += 2;
  7220. while( *z && (*z!='*' || z[1]!='/') ){ z++; }
  7221. if( *z==0 ) return 0;
  7222. z++;
  7223. continue;
  7224. }
  7225. if( *z=='-' && z[1]=='-' ){
  7226. z += 2;
  7227. while( *z && *z!='\n' ){ z++; }
  7228. if( *z==0 ) return 1;
  7229. continue;
  7230. }
  7231. return 0;
  7232. }
  7233. return 1;
  7234. }
  7235. /*
  7236. ** Return TRUE if the line typed in is an SQL command terminator other
  7237. ** than a semi-colon. The SQL Server style "go" command is understood
  7238. ** as is the Oracle "/".
  7239. */
  7240. static int line_is_command_terminator(const char *zLine){
  7241. while( IsSpace(zLine[0]) ){ zLine++; };
  7242. if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
  7243. return 1; /* Oracle */
  7244. }
  7245. if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
  7246. && _all_whitespace(&zLine[2]) ){
  7247. return 1; /* SQL Server */
  7248. }
  7249. return 0;
  7250. }
  7251. /*
  7252. ** Return true if zSql is a complete SQL statement. Return false if it
  7253. ** ends in the middle of a string literal or C-style comment.
  7254. */
  7255. static int line_is_complete(char *zSql, int nSql){
  7256. int rc;
  7257. if( zSql==0 ) return 1;
  7258. zSql[nSql] = ';';
  7259. zSql[nSql+1] = 0;
  7260. rc = sqlite3_complete(zSql);
  7261. zSql[nSql] = 0;
  7262. return rc;
  7263. }
  7264. /*
  7265. ** Run a single line of SQL
  7266. */
  7267. static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
  7268. int rc;
  7269. char *zErrMsg = 0;
  7270. open_db(p, 0);
  7271. if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
  7272. BEGIN_TIMER;
  7273. rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
  7274. END_TIMER;
  7275. if( rc || zErrMsg ){
  7276. char zPrefix[100];
  7277. if( in!=0 || !stdin_is_interactive ){
  7278. sqlite3_snprintf(sizeof(zPrefix), zPrefix,
  7279. "Error: near line %d:", startline);
  7280. }else{
  7281. sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
  7282. }
  7283. if( zErrMsg!=0 ){
  7284. utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
  7285. sqlite3_free(zErrMsg);
  7286. zErrMsg = 0;
  7287. }else{
  7288. utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
  7289. }
  7290. return 1;
  7291. }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
  7292. raw_printf(p->out, "changes: %3d total_changes: %d\n",
  7293. sqlite3_changes(p->db), sqlite3_total_changes(p->db));
  7294. }
  7295. return 0;
  7296. }
  7297. /*
  7298. ** Read input from *in and process it. If *in==0 then input
  7299. ** is interactive - the user is typing it it. Otherwise, input
  7300. ** is coming from a file or device. A prompt is issued and history
  7301. ** is saved only if input is interactive. An interrupt signal will
  7302. ** cause this routine to exit immediately, unless input is interactive.
  7303. **
  7304. ** Return the number of errors.
  7305. */
  7306. static int process_input(ShellState *p, FILE *in){
  7307. char *zLine = 0; /* A single input line */
  7308. char *zSql = 0; /* Accumulated SQL text */
  7309. int nLine; /* Length of current line */
  7310. int nSql = 0; /* Bytes of zSql[] used */
  7311. int nAlloc = 0; /* Allocated zSql[] space */
  7312. int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
  7313. int rc; /* Error code */
  7314. int errCnt = 0; /* Number of errors seen */
  7315. int lineno = 0; /* Current line number */
  7316. int startline = 0; /* Line number for start of current input */
  7317. while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
  7318. fflush(p->out);
  7319. zLine = one_input_line(in, zLine, nSql>0);
  7320. if( zLine==0 ){
  7321. /* End of input */
  7322. if( in==0 && stdin_is_interactive ) printf("\n");
  7323. break;
  7324. }
  7325. if( seenInterrupt ){
  7326. if( in!=0 ) break;
  7327. seenInterrupt = 0;
  7328. }
  7329. lineno++;
  7330. if( nSql==0 && _all_whitespace(zLine) ){
  7331. if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
  7332. continue;
  7333. }
  7334. if( zLine && zLine[0]=='.' && nSql==0 ){
  7335. if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
  7336. rc = do_meta_command(zLine, p);
  7337. if( rc==2 ){ /* exit requested */
  7338. break;
  7339. }else if( rc ){
  7340. errCnt++;
  7341. }
  7342. continue;
  7343. }
  7344. if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
  7345. memcpy(zLine,";",2);
  7346. }
  7347. nLine = strlen30(zLine);
  7348. if( nSql+nLine+2>=nAlloc ){
  7349. nAlloc = nSql+nLine+100;
  7350. zSql = realloc(zSql, nAlloc);
  7351. if( zSql==0 ){
  7352. raw_printf(stderr, "Error: out of memory\n");
  7353. exit(1);
  7354. }
  7355. }
  7356. nSqlPrior = nSql;
  7357. if( nSql==0 ){
  7358. int i;
  7359. for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
  7360. assert( nAlloc>0 && zSql!=0 );
  7361. memcpy(zSql, zLine+i, nLine+1-i);
  7362. startline = lineno;
  7363. nSql = nLine-i;
  7364. }else{
  7365. zSql[nSql++] = '\n';
  7366. memcpy(zSql+nSql, zLine, nLine+1);
  7367. nSql += nLine;
  7368. }
  7369. if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  7370. && sqlite3_complete(zSql) ){
  7371. errCnt += runOneSqlLine(p, zSql, in, startline);
  7372. nSql = 0;
  7373. if( p->outCount ){
  7374. output_reset(p);
  7375. p->outCount = 0;
  7376. }
  7377. }else if( nSql && _all_whitespace(zSql) ){
  7378. if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
  7379. nSql = 0;
  7380. }
  7381. }
  7382. if( nSql && !_all_whitespace(zSql) ){
  7383. runOneSqlLine(p, zSql, in, startline);
  7384. }
  7385. free(zSql);
  7386. free(zLine);
  7387. return errCnt>0;
  7388. }
  7389. /*
  7390. ** Return a pathname which is the user's home directory. A
  7391. ** 0 return indicates an error of some kind.
  7392. */
  7393. static char *find_home_dir(int clearFlag){
  7394. static char *home_dir = NULL;
  7395. if( clearFlag ){
  7396. free(home_dir);
  7397. home_dir = 0;
  7398. return 0;
  7399. }
  7400. if( home_dir ) return home_dir;
  7401. #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
  7402. && !defined(__RTP__) && !defined(_WRS_KERNEL)
  7403. {
  7404. struct passwd *pwent;
  7405. uid_t uid = getuid();
  7406. if( (pwent=getpwuid(uid)) != NULL) {
  7407. home_dir = pwent->pw_dir;
  7408. }
  7409. }
  7410. #endif
  7411. #if defined(_WIN32_WCE)
  7412. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  7413. */
  7414. home_dir = "/";
  7415. #else
  7416. #if defined(_WIN32) || defined(WIN32)
  7417. if (!home_dir) {
  7418. home_dir = getenv("USERPROFILE");
  7419. }
  7420. #endif
  7421. if (!home_dir) {
  7422. home_dir = getenv("HOME");
  7423. }
  7424. #if defined(_WIN32) || defined(WIN32)
  7425. if (!home_dir) {
  7426. char *zDrive, *zPath;
  7427. int n;
  7428. zDrive = getenv("HOMEDRIVE");
  7429. zPath = getenv("HOMEPATH");
  7430. if( zDrive && zPath ){
  7431. n = strlen30(zDrive) + strlen30(zPath) + 1;
  7432. home_dir = malloc( n );
  7433. if( home_dir==0 ) return 0;
  7434. sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  7435. return home_dir;
  7436. }
  7437. home_dir = "c:\\";
  7438. }
  7439. #endif
  7440. #endif /* !_WIN32_WCE */
  7441. if( home_dir ){
  7442. int n = strlen30(home_dir) + 1;
  7443. char *z = malloc( n );
  7444. if( z ) memcpy(z, home_dir, n);
  7445. home_dir = z;
  7446. }
  7447. return home_dir;
  7448. }
  7449. /*
  7450. ** Read input from the file given by sqliterc_override. Or if that
  7451. ** parameter is NULL, take input from ~/.sqliterc
  7452. **
  7453. ** Returns the number of errors.
  7454. */
  7455. static void process_sqliterc(
  7456. ShellState *p, /* Configuration data */
  7457. const char *sqliterc_override /* Name of config file. NULL to use default */
  7458. ){
  7459. char *home_dir = NULL;
  7460. const char *sqliterc = sqliterc_override;
  7461. char *zBuf = 0;
  7462. FILE *in = NULL;
  7463. if (sqliterc == NULL) {
  7464. home_dir = find_home_dir(0);
  7465. if( home_dir==0 ){
  7466. raw_printf(stderr, "-- warning: cannot find home directory;"
  7467. " cannot read ~/.sqliterc\n");
  7468. return;
  7469. }
  7470. sqlite3_initialize();
  7471. zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
  7472. sqliterc = zBuf;
  7473. }
  7474. in = fopen(sqliterc,"rb");
  7475. if( in ){
  7476. if( stdin_is_interactive ){
  7477. utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
  7478. }
  7479. process_input(p,in);
  7480. fclose(in);
  7481. }
  7482. sqlite3_free(zBuf);
  7483. }
  7484. /*
  7485. ** Show available command line options
  7486. */
  7487. static const char zOptions[] =
  7488. " -ascii set output mode to 'ascii'\n"
  7489. " -bail stop after hitting an error\n"
  7490. " -batch force batch I/O\n"
  7491. " -column set output mode to 'column'\n"
  7492. " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
  7493. " -csv set output mode to 'csv'\n"
  7494. " -echo print commands before execution\n"
  7495. " -init FILENAME read/process named file\n"
  7496. " -[no]header turn headers on or off\n"
  7497. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  7498. " -heap SIZE Size of heap for memsys3 or memsys5\n"
  7499. #endif
  7500. " -help show this message\n"
  7501. " -html set output mode to HTML\n"
  7502. " -interactive force interactive I/O\n"
  7503. " -line set output mode to 'line'\n"
  7504. " -list set output mode to 'list'\n"
  7505. " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
  7506. " -mmap N default mmap size set to N\n"
  7507. #ifdef SQLITE_ENABLE_MULTIPLEX
  7508. " -multiplex enable the multiplexor VFS\n"
  7509. #endif
  7510. " -newline SEP set output row separator. Default: '\\n'\n"
  7511. " -nullvalue TEXT set text string for NULL values. Default ''\n"
  7512. " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
  7513. " -quote set output mode to 'quote'\n"
  7514. " -separator SEP set output column separator. Default: '|'\n"
  7515. " -stats print memory stats before each finalize\n"
  7516. " -version show SQLite version\n"
  7517. " -vfs NAME use NAME as the default VFS\n"
  7518. #ifdef SQLITE_ENABLE_VFSTRACE
  7519. " -vfstrace enable tracing of all VFS calls\n"
  7520. #endif
  7521. ;
  7522. static void usage(int showDetail){
  7523. utf8_printf(stderr,
  7524. "Usage: %s [OPTIONS] FILENAME [SQL]\n"
  7525. "FILENAME is the name of an SQLite database. A new database is created\n"
  7526. "if the file does not previously exist.\n", Argv0);
  7527. if( showDetail ){
  7528. utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
  7529. }else{
  7530. raw_printf(stderr, "Use the -help option for additional information\n");
  7531. }
  7532. exit(1);
  7533. }
  7534. /*
  7535. ** Initialize the state information in data
  7536. */
  7537. static void main_init(ShellState *data) {
  7538. memset(data, 0, sizeof(*data));
  7539. data->normalMode = data->cMode = data->mode = MODE_List;
  7540. data->autoExplain = 1;
  7541. memcpy(data->colSeparator,SEP_Column, 2);
  7542. memcpy(data->rowSeparator,SEP_Row, 2);
  7543. data->showHeader = 0;
  7544. data->shellFlgs = SHFLG_Lookaside;
  7545. sqlite3_config(SQLITE_CONFIG_URI, 1);
  7546. sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
  7547. sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
  7548. sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  7549. sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
  7550. }
  7551. /*
  7552. ** Output text to the console in a font that attracts extra attention.
  7553. */
  7554. #ifdef _WIN32
  7555. static void printBold(const char *zText){
  7556. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  7557. CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
  7558. GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
  7559. SetConsoleTextAttribute(out,
  7560. FOREGROUND_RED|FOREGROUND_INTENSITY
  7561. );
  7562. printf("%s", zText);
  7563. SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
  7564. }
  7565. #else
  7566. static void printBold(const char *zText){
  7567. printf("\033[1m%s\033[0m", zText);
  7568. }
  7569. #endif
  7570. /*
  7571. ** Get the argument to an --option. Throw an error and die if no argument
  7572. ** is available.
  7573. */
  7574. static char *cmdline_option_value(int argc, char **argv, int i){
  7575. if( i==argc ){
  7576. utf8_printf(stderr, "%s: Error: missing argument to %s\n",
  7577. argv[0], argv[argc-1]);
  7578. exit(1);
  7579. }
  7580. return argv[i];
  7581. }
  7582. #ifndef SQLITE_SHELL_IS_UTF8
  7583. # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
  7584. # define SQLITE_SHELL_IS_UTF8 (0)
  7585. # else
  7586. # define SQLITE_SHELL_IS_UTF8 (1)
  7587. # endif
  7588. #endif
  7589. #if SQLITE_SHELL_IS_UTF8
  7590. int SQLITE_CDECL main(int argc, char **argv){
  7591. #else
  7592. int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
  7593. char **argv;
  7594. #endif
  7595. char *zErrMsg = 0;
  7596. ShellState data;
  7597. const char *zInitFile = 0;
  7598. int i;
  7599. int rc = 0;
  7600. int warnInmemoryDb = 0;
  7601. int readStdin = 1;
  7602. int nCmd = 0;
  7603. char **azCmd = 0;
  7604. setBinaryMode(stdin, 0);
  7605. setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
  7606. stdin_is_interactive = isatty(0);
  7607. stdout_is_console = isatty(1);
  7608. #if USE_SYSTEM_SQLITE+0!=1
  7609. if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
  7610. utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
  7611. sqlite3_sourceid(), SQLITE_SOURCE_ID);
  7612. exit(1);
  7613. }
  7614. #endif
  7615. main_init(&data);
  7616. #if !SQLITE_SHELL_IS_UTF8
  7617. sqlite3_initialize();
  7618. argv = sqlite3_malloc64(sizeof(argv[0])*argc);
  7619. if( argv==0 ){
  7620. raw_printf(stderr, "out of memory\n");
  7621. exit(1);
  7622. }
  7623. for(i=0; i<argc; i++){
  7624. argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
  7625. if( argv[i]==0 ){
  7626. raw_printf(stderr, "out of memory\n");
  7627. exit(1);
  7628. }
  7629. }
  7630. #endif
  7631. assert( argc>=1 && argv && argv[0] );
  7632. Argv0 = argv[0];
  7633. /* Make sure we have a valid signal handler early, before anything
  7634. ** else is done.
  7635. */
  7636. #ifdef SIGINT
  7637. signal(SIGINT, interrupt_handler);
  7638. #endif
  7639. #ifdef SQLITE_SHELL_DBNAME_PROC
  7640. {
  7641. /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
  7642. ** of a C-function that will provide the name of the database file. Use
  7643. ** this compile-time option to embed this shell program in larger
  7644. ** applications. */
  7645. extern void SQLITE_SHELL_DBNAME_PROC(const char**);
  7646. SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
  7647. warnInmemoryDb = 0;
  7648. }
  7649. #endif
  7650. /* Do an initial pass through the command-line argument to locate
  7651. ** the name of the database file, the name of the initialization file,
  7652. ** the size of the alternative malloc heap,
  7653. ** and the first command to execute.
  7654. */
  7655. for(i=1; i<argc; i++){
  7656. char *z;
  7657. z = argv[i];
  7658. if( z[0]!='-' ){
  7659. if( data.zDbFilename==0 ){
  7660. data.zDbFilename = z;
  7661. }else{
  7662. /* Excesss arguments are interpreted as SQL (or dot-commands) and
  7663. ** mean that nothing is read from stdin */
  7664. readStdin = 0;
  7665. nCmd++;
  7666. azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
  7667. if( azCmd==0 ){
  7668. raw_printf(stderr, "out of memory\n");
  7669. exit(1);
  7670. }
  7671. azCmd[nCmd-1] = z;
  7672. }
  7673. }
  7674. if( z[1]=='-' ) z++;
  7675. if( strcmp(z,"-separator")==0
  7676. || strcmp(z,"-nullvalue")==0
  7677. || strcmp(z,"-newline")==0
  7678. || strcmp(z,"-cmd")==0
  7679. ){
  7680. (void)cmdline_option_value(argc, argv, ++i);
  7681. }else if( strcmp(z,"-init")==0 ){
  7682. zInitFile = cmdline_option_value(argc, argv, ++i);
  7683. }else if( strcmp(z,"-batch")==0 ){
  7684. /* Need to check for batch mode here to so we can avoid printing
  7685. ** informational messages (like from process_sqliterc) before
  7686. ** we do the actual processing of arguments later in a second pass.
  7687. */
  7688. stdin_is_interactive = 0;
  7689. }else if( strcmp(z,"-heap")==0 ){
  7690. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  7691. const char *zSize;
  7692. sqlite3_int64 szHeap;
  7693. zSize = cmdline_option_value(argc, argv, ++i);
  7694. szHeap = integerValue(zSize);
  7695. if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
  7696. sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
  7697. #else
  7698. (void)cmdline_option_value(argc, argv, ++i);
  7699. #endif
  7700. }else if( strcmp(z,"-pagecache")==0 ){
  7701. int n, sz;
  7702. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  7703. if( sz>70000 ) sz = 70000;
  7704. if( sz<0 ) sz = 0;
  7705. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  7706. sqlite3_config(SQLITE_CONFIG_PAGECACHE,
  7707. (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
  7708. data.shellFlgs |= SHFLG_Pagecache;
  7709. }else if( strcmp(z,"-lookaside")==0 ){
  7710. int n, sz;
  7711. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  7712. if( sz<0 ) sz = 0;
  7713. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  7714. if( n<0 ) n = 0;
  7715. sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
  7716. if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
  7717. #ifdef SQLITE_ENABLE_VFSTRACE
  7718. }else if( strcmp(z,"-vfstrace")==0 ){
  7719. extern int vfstrace_register(
  7720. const char *zTraceName,
  7721. const char *zOldVfsName,
  7722. int (*xOut)(const char*,void*),
  7723. void *pOutArg,
  7724. int makeDefault
  7725. );
  7726. vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
  7727. #endif
  7728. #ifdef SQLITE_ENABLE_MULTIPLEX
  7729. }else if( strcmp(z,"-multiplex")==0 ){
  7730. extern int sqlite3_multiple_initialize(const char*,int);
  7731. sqlite3_multiplex_initialize(0, 1);
  7732. #endif
  7733. }else if( strcmp(z,"-mmap")==0 ){
  7734. sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  7735. sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
  7736. }else if( strcmp(z,"-vfs")==0 ){
  7737. sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
  7738. if( pVfs ){
  7739. sqlite3_vfs_register(pVfs, 1);
  7740. }else{
  7741. utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
  7742. exit(1);
  7743. }
  7744. }
  7745. }
  7746. if( data.zDbFilename==0 ){
  7747. #ifndef SQLITE_OMIT_MEMORYDB
  7748. data.zDbFilename = ":memory:";
  7749. warnInmemoryDb = argc==1;
  7750. #else
  7751. utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
  7752. return 1;
  7753. #endif
  7754. }
  7755. data.out = stdout;
  7756. /* Go ahead and open the database file if it already exists. If the
  7757. ** file does not exist, delay opening it. This prevents empty database
  7758. ** files from being created if a user mistypes the database name argument
  7759. ** to the sqlite command-line tool.
  7760. */
  7761. if( access(data.zDbFilename, 0)==0 ){
  7762. open_db(&data, 0);
  7763. }
  7764. /* Process the initialization file if there is one. If no -init option
  7765. ** is given on the command line, look for a file named ~/.sqliterc and
  7766. ** try to process it.
  7767. */
  7768. process_sqliterc(&data,zInitFile);
  7769. /* Make a second pass through the command-line argument and set
  7770. ** options. This second pass is delayed until after the initialization
  7771. ** file is processed so that the command-line arguments will override
  7772. ** settings in the initialization file.
  7773. */
  7774. for(i=1; i<argc; i++){
  7775. char *z = argv[i];
  7776. if( z[0]!='-' ) continue;
  7777. if( z[1]=='-' ){ z++; }
  7778. if( strcmp(z,"-init")==0 ){
  7779. i++;
  7780. }else if( strcmp(z,"-html")==0 ){
  7781. data.mode = MODE_Html;
  7782. }else if( strcmp(z,"-list")==0 ){
  7783. data.mode = MODE_List;
  7784. }else if( strcmp(z,"-quote")==0 ){
  7785. data.mode = MODE_Quote;
  7786. }else if( strcmp(z,"-line")==0 ){
  7787. data.mode = MODE_Line;
  7788. }else if( strcmp(z,"-column")==0 ){
  7789. data.mode = MODE_Column;
  7790. }else if( strcmp(z,"-csv")==0 ){
  7791. data.mode = MODE_Csv;
  7792. memcpy(data.colSeparator,",",2);
  7793. }else if( strcmp(z,"-ascii")==0 ){
  7794. data.mode = MODE_Ascii;
  7795. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  7796. SEP_Unit);
  7797. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  7798. SEP_Record);
  7799. }else if( strcmp(z,"-separator")==0 ){
  7800. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  7801. "%s",cmdline_option_value(argc,argv,++i));
  7802. }else if( strcmp(z,"-newline")==0 ){
  7803. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  7804. "%s",cmdline_option_value(argc,argv,++i));
  7805. }else if( strcmp(z,"-nullvalue")==0 ){
  7806. sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
  7807. "%s",cmdline_option_value(argc,argv,++i));
  7808. }else if( strcmp(z,"-header")==0 ){
  7809. data.showHeader = 1;
  7810. }else if( strcmp(z,"-noheader")==0 ){
  7811. data.showHeader = 0;
  7812. }else if( strcmp(z,"-echo")==0 ){
  7813. ShellSetFlag(&data, SHFLG_Echo);
  7814. }else if( strcmp(z,"-eqp")==0 ){
  7815. data.autoEQP = 1;
  7816. }else if( strcmp(z,"-eqpfull")==0 ){
  7817. data.autoEQP = 2;
  7818. }else if( strcmp(z,"-stats")==0 ){
  7819. data.statsOn = 1;
  7820. }else if( strcmp(z,"-scanstats")==0 ){
  7821. data.scanstatsOn = 1;
  7822. }else if( strcmp(z,"-backslash")==0 ){
  7823. /* Undocumented command-line option: -backslash
  7824. ** Causes C-style backslash escapes to be evaluated in SQL statements
  7825. ** prior to sending the SQL into SQLite. Useful for injecting
  7826. ** crazy bytes in the middle of SQL statements for testing and debugging.
  7827. */
  7828. ShellSetFlag(&data, SHFLG_Backslash);
  7829. }else if( strcmp(z,"-bail")==0 ){
  7830. bail_on_error = 1;
  7831. }else if( strcmp(z,"-version")==0 ){
  7832. printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
  7833. return 0;
  7834. }else if( strcmp(z,"-interactive")==0 ){
  7835. stdin_is_interactive = 1;
  7836. }else if( strcmp(z,"-batch")==0 ){
  7837. stdin_is_interactive = 0;
  7838. }else if( strcmp(z,"-heap")==0 ){
  7839. i++;
  7840. }else if( strcmp(z,"-pagecache")==0 ){
  7841. i+=2;
  7842. }else if( strcmp(z,"-lookaside")==0 ){
  7843. i+=2;
  7844. }else if( strcmp(z,"-mmap")==0 ){
  7845. i++;
  7846. }else if( strcmp(z,"-vfs")==0 ){
  7847. i++;
  7848. #ifdef SQLITE_ENABLE_VFSTRACE
  7849. }else if( strcmp(z,"-vfstrace")==0 ){
  7850. i++;
  7851. #endif
  7852. #ifdef SQLITE_ENABLE_MULTIPLEX
  7853. }else if( strcmp(z,"-multiplex")==0 ){
  7854. i++;
  7855. #endif
  7856. }else if( strcmp(z,"-help")==0 ){
  7857. usage(1);
  7858. }else if( strcmp(z,"-cmd")==0 ){
  7859. /* Run commands that follow -cmd first and separately from commands
  7860. ** that simply appear on the command-line. This seems goofy. It would
  7861. ** be better if all commands ran in the order that they appear. But
  7862. ** we retain the goofy behavior for historical compatibility. */
  7863. if( i==argc-1 ) break;
  7864. z = cmdline_option_value(argc,argv,++i);
  7865. if( z[0]=='.' ){
  7866. rc = do_meta_command(z, &data);
  7867. if( rc && bail_on_error ) return rc==2 ? 0 : rc;
  7868. }else{
  7869. open_db(&data, 0);
  7870. rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
  7871. if( zErrMsg!=0 ){
  7872. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  7873. if( bail_on_error ) return rc!=0 ? rc : 1;
  7874. }else if( rc!=0 ){
  7875. utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
  7876. if( bail_on_error ) return rc;
  7877. }
  7878. }
  7879. }else{
  7880. utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
  7881. raw_printf(stderr,"Use -help for a list of options.\n");
  7882. return 1;
  7883. }
  7884. data.cMode = data.mode;
  7885. }
  7886. if( !readStdin ){
  7887. /* Run all arguments that do not begin with '-' as if they were separate
  7888. ** command-line inputs, except for the argToSkip argument which contains
  7889. ** the database filename.
  7890. */
  7891. for(i=0; i<nCmd; i++){
  7892. if( azCmd[i][0]=='.' ){
  7893. rc = do_meta_command(azCmd[i], &data);
  7894. if( rc ) return rc==2 ? 0 : rc;
  7895. }else{
  7896. open_db(&data, 0);
  7897. rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
  7898. if( zErrMsg!=0 ){
  7899. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  7900. return rc!=0 ? rc : 1;
  7901. }else if( rc!=0 ){
  7902. utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
  7903. return rc;
  7904. }
  7905. }
  7906. }
  7907. free(azCmd);
  7908. }else{
  7909. /* Run commands received from standard input
  7910. */
  7911. if( stdin_is_interactive ){
  7912. char *zHome;
  7913. char *zHistory = 0;
  7914. int nHistory;
  7915. printf(
  7916. "SQLite version %s %.19s\n" /*extra-version-info*/
  7917. "Enter \".help\" for usage hints.\n",
  7918. sqlite3_libversion(), sqlite3_sourceid()
  7919. );
  7920. if( warnInmemoryDb ){
  7921. printf("Connected to a ");
  7922. printBold("transient in-memory database");
  7923. printf(".\nUse \".open FILENAME\" to reopen on a "
  7924. "persistent database.\n");
  7925. }
  7926. zHome = find_home_dir(0);
  7927. if( zHome ){
  7928. nHistory = strlen30(zHome) + 20;
  7929. if( (zHistory = malloc(nHistory))!=0 ){
  7930. sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  7931. }
  7932. }
  7933. if( zHistory ){ shell_read_history(zHistory); }
  7934. #if HAVE_READLINE || HAVE_EDITLINE
  7935. rl_attempted_completion_function = readline_completion;
  7936. #elif HAVE_LINENOISE
  7937. linenoiseSetCompletionCallback(linenoise_completion);
  7938. #endif
  7939. rc = process_input(&data, 0);
  7940. if( zHistory ){
  7941. shell_stifle_history(2000);
  7942. shell_write_history(zHistory);
  7943. free(zHistory);
  7944. }
  7945. }else{
  7946. rc = process_input(&data, stdin);
  7947. }
  7948. }
  7949. set_table_name(&data, 0);
  7950. if( data.db ){
  7951. session_close_all(&data);
  7952. sqlite3_close(data.db);
  7953. }
  7954. sqlite3_free(data.zFreeOnClose);
  7955. find_home_dir(1);
  7956. #if !SQLITE_SHELL_IS_UTF8
  7957. for(i=0; i<argc; i++) sqlite3_free(argv[i]);
  7958. sqlite3_free(argv);
  7959. #endif
  7960. return rc;
  7961. }