shell.c 516 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203
  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. typedef sqlite3_int64 i64;
  79. typedef sqlite3_uint64 u64;
  80. typedef unsigned char u8;
  81. #if SQLITE_USER_AUTHENTICATION
  82. # include "sqlite3userauth.h"
  83. #endif
  84. #include <ctype.h>
  85. #include <stdarg.h>
  86. #if !defined(_WIN32) && !defined(WIN32)
  87. # include <signal.h>
  88. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  89. # include <pwd.h>
  90. # endif
  91. #endif
  92. #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
  93. # include <unistd.h>
  94. # include <dirent.h>
  95. # define GETPID getpid
  96. # if defined(__MINGW32__)
  97. # define DIRENT dirent
  98. # ifndef S_ISLNK
  99. # define S_ISLNK(mode) (0)
  100. # endif
  101. # endif
  102. #else
  103. # define GETPID (int)GetCurrentProcessId
  104. #endif
  105. #include <sys/types.h>
  106. #include <sys/stat.h>
  107. #if HAVE_READLINE
  108. # include <readline/readline.h>
  109. # include <readline/history.h>
  110. #endif
  111. #if HAVE_EDITLINE
  112. # include <editline/readline.h>
  113. #endif
  114. #if HAVE_EDITLINE || HAVE_READLINE
  115. # define shell_add_history(X) add_history(X)
  116. # define shell_read_history(X) read_history(X)
  117. # define shell_write_history(X) write_history(X)
  118. # define shell_stifle_history(X) stifle_history(X)
  119. # define shell_readline(X) readline(X)
  120. #elif HAVE_LINENOISE
  121. # include "linenoise.h"
  122. # define shell_add_history(X) linenoiseHistoryAdd(X)
  123. # define shell_read_history(X) linenoiseHistoryLoad(X)
  124. # define shell_write_history(X) linenoiseHistorySave(X)
  125. # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
  126. # define shell_readline(X) linenoise(X)
  127. #else
  128. # define shell_read_history(X)
  129. # define shell_write_history(X)
  130. # define shell_stifle_history(X)
  131. # define SHELL_USE_LOCAL_GETLINE 1
  132. #endif
  133. #if defined(_WIN32) || defined(WIN32)
  134. # include <io.h>
  135. # include <fcntl.h>
  136. # define isatty(h) _isatty(h)
  137. # ifndef access
  138. # define access(f,m) _access((f),(m))
  139. # endif
  140. # ifndef unlink
  141. # define unlink _unlink
  142. # endif
  143. # ifndef strdup
  144. # define strdup _strdup
  145. # endif
  146. # undef popen
  147. # define popen _popen
  148. # undef pclose
  149. # define pclose _pclose
  150. #else
  151. /* Make sure isatty() has a prototype. */
  152. extern int isatty(int);
  153. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  154. /* popen and pclose are not C89 functions and so are
  155. ** sometimes omitted from the <stdio.h> header */
  156. extern FILE *popen(const char*,const char*);
  157. extern int pclose(FILE*);
  158. # else
  159. # define SQLITE_OMIT_POPEN 1
  160. # endif
  161. #endif
  162. #if defined(_WIN32_WCE)
  163. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
  164. * thus we always assume that we have a console. That can be
  165. * overridden with the -batch command line option.
  166. */
  167. #define isatty(x) 1
  168. #endif
  169. /* ctype macros that work with signed characters */
  170. #define IsSpace(X) isspace((unsigned char)X)
  171. #define IsDigit(X) isdigit((unsigned char)X)
  172. #define ToLower(X) (char)tolower((unsigned char)X)
  173. #if defined(_WIN32) || defined(WIN32)
  174. #include <windows.h>
  175. /* string conversion routines only needed on Win32 */
  176. extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
  177. extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
  178. extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
  179. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
  180. #endif
  181. /* On Windows, we normally run with output mode of TEXT so that \n characters
  182. ** are automatically translated into \r\n. However, this behavior needs
  183. ** to be disabled in some cases (ex: when generating CSV output and when
  184. ** rendering quoted strings that contain \n characters). The following
  185. ** routines take care of that.
  186. */
  187. #if defined(_WIN32) || defined(WIN32)
  188. static void setBinaryMode(FILE *file, int isOutput){
  189. if( isOutput ) fflush(file);
  190. _setmode(_fileno(file), _O_BINARY);
  191. }
  192. static void setTextMode(FILE *file, int isOutput){
  193. if( isOutput ) fflush(file);
  194. _setmode(_fileno(file), _O_TEXT);
  195. }
  196. #else
  197. # define setBinaryMode(X,Y)
  198. # define setTextMode(X,Y)
  199. #endif
  200. /* True if the timer is enabled */
  201. static int enableTimer = 0;
  202. /* Return the current wall-clock time */
  203. static sqlite3_int64 timeOfDay(void){
  204. static sqlite3_vfs *clockVfs = 0;
  205. sqlite3_int64 t;
  206. if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
  207. if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
  208. clockVfs->xCurrentTimeInt64(clockVfs, &t);
  209. }else{
  210. double r;
  211. clockVfs->xCurrentTime(clockVfs, &r);
  212. t = (sqlite3_int64)(r*86400000.0);
  213. }
  214. return t;
  215. }
  216. #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
  217. #include <sys/time.h>
  218. #include <sys/resource.h>
  219. /* VxWorks does not support getrusage() as far as we can determine */
  220. #if defined(_WRS_KERNEL) || defined(__RTP__)
  221. struct rusage {
  222. struct timeval ru_utime; /* user CPU time used */
  223. struct timeval ru_stime; /* system CPU time used */
  224. };
  225. #define getrusage(A,B) memset(B,0,sizeof(*B))
  226. #endif
  227. /* Saved resource information for the beginning of an operation */
  228. static struct rusage sBegin; /* CPU time at start */
  229. static sqlite3_int64 iBegin; /* Wall-clock time at start */
  230. /*
  231. ** Begin timing an operation
  232. */
  233. static void beginTimer(void){
  234. if( enableTimer ){
  235. getrusage(RUSAGE_SELF, &sBegin);
  236. iBegin = timeOfDay();
  237. }
  238. }
  239. /* Return the difference of two time_structs in seconds */
  240. static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  241. return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
  242. (double)(pEnd->tv_sec - pStart->tv_sec);
  243. }
  244. /*
  245. ** Print the timing results.
  246. */
  247. static void endTimer(void){
  248. if( enableTimer ){
  249. sqlite3_int64 iEnd = timeOfDay();
  250. struct rusage sEnd;
  251. getrusage(RUSAGE_SELF, &sEnd);
  252. printf("Run Time: real %.3f user %f sys %f\n",
  253. (iEnd - iBegin)*0.001,
  254. timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
  255. timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  256. }
  257. }
  258. #define BEGIN_TIMER beginTimer()
  259. #define END_TIMER endTimer()
  260. #define HAS_TIMER 1
  261. #elif (defined(_WIN32) || defined(WIN32))
  262. /* Saved resource information for the beginning of an operation */
  263. static HANDLE hProcess;
  264. static FILETIME ftKernelBegin;
  265. static FILETIME ftUserBegin;
  266. static sqlite3_int64 ftWallBegin;
  267. typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
  268. LPFILETIME, LPFILETIME);
  269. static GETPROCTIMES getProcessTimesAddr = NULL;
  270. /*
  271. ** Check to see if we have timer support. Return 1 if necessary
  272. ** support found (or found previously).
  273. */
  274. static int hasTimer(void){
  275. if( getProcessTimesAddr ){
  276. return 1;
  277. } else {
  278. /* GetProcessTimes() isn't supported in WIN95 and some other Windows
  279. ** versions. See if the version we are running on has it, and if it
  280. ** does, save off a pointer to it and the current process handle.
  281. */
  282. hProcess = GetCurrentProcess();
  283. if( hProcess ){
  284. HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
  285. if( NULL != hinstLib ){
  286. getProcessTimesAddr =
  287. (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
  288. if( NULL != getProcessTimesAddr ){
  289. return 1;
  290. }
  291. FreeLibrary(hinstLib);
  292. }
  293. }
  294. }
  295. return 0;
  296. }
  297. /*
  298. ** Begin timing an operation
  299. */
  300. static void beginTimer(void){
  301. if( enableTimer && getProcessTimesAddr ){
  302. FILETIME ftCreation, ftExit;
  303. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
  304. &ftKernelBegin,&ftUserBegin);
  305. ftWallBegin = timeOfDay();
  306. }
  307. }
  308. /* Return the difference of two FILETIME structs in seconds */
  309. static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
  310. sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
  311. sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
  312. return (double) ((i64End - i64Start) / 10000000.0);
  313. }
  314. /*
  315. ** Print the timing results.
  316. */
  317. static void endTimer(void){
  318. if( enableTimer && getProcessTimesAddr){
  319. FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
  320. sqlite3_int64 ftWallEnd = timeOfDay();
  321. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
  322. printf("Run Time: real %.3f user %f sys %f\n",
  323. (ftWallEnd - ftWallBegin)*0.001,
  324. timeDiff(&ftUserBegin, &ftUserEnd),
  325. timeDiff(&ftKernelBegin, &ftKernelEnd));
  326. }
  327. }
  328. #define BEGIN_TIMER beginTimer()
  329. #define END_TIMER endTimer()
  330. #define HAS_TIMER hasTimer()
  331. #else
  332. #define BEGIN_TIMER
  333. #define END_TIMER
  334. #define HAS_TIMER 0
  335. #endif
  336. /*
  337. ** Used to prevent warnings about unused parameters
  338. */
  339. #define UNUSED_PARAMETER(x) (void)(x)
  340. /*
  341. ** Number of elements in an array
  342. */
  343. #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
  344. /*
  345. ** If the following flag is set, then command execution stops
  346. ** at an error if we are not interactive.
  347. */
  348. static int bail_on_error = 0;
  349. /*
  350. ** Threat stdin as an interactive input if the following variable
  351. ** is true. Otherwise, assume stdin is connected to a file or pipe.
  352. */
  353. static int stdin_is_interactive = 1;
  354. /*
  355. ** On Windows systems we have to know if standard output is a console
  356. ** in order to translate UTF-8 into MBCS. The following variable is
  357. ** true if translation is required.
  358. */
  359. static int stdout_is_console = 1;
  360. /*
  361. ** The following is the open SQLite database. We make a pointer
  362. ** to this database a static variable so that it can be accessed
  363. ** by the SIGINT handler to interrupt database processing.
  364. */
  365. static sqlite3 *globalDb = 0;
  366. /*
  367. ** True if an interrupt (Control-C) has been received.
  368. */
  369. static volatile int seenInterrupt = 0;
  370. /*
  371. ** This is the name of our program. It is set in main(), used
  372. ** in a number of other places, mostly for error messages.
  373. */
  374. static char *Argv0;
  375. /*
  376. ** Prompt strings. Initialized in main. Settable with
  377. ** .prompt main continue
  378. */
  379. static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
  380. static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
  381. /*
  382. ** Render output like fprintf(). Except, if the output is going to the
  383. ** console and if this is running on a Windows machine, translate the
  384. ** output from UTF-8 into MBCS.
  385. */
  386. #if defined(_WIN32) || defined(WIN32)
  387. void utf8_printf(FILE *out, const char *zFormat, ...){
  388. va_list ap;
  389. va_start(ap, zFormat);
  390. if( stdout_is_console && (out==stdout || out==stderr) ){
  391. char *z1 = sqlite3_vmprintf(zFormat, ap);
  392. char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
  393. sqlite3_free(z1);
  394. fputs(z2, out);
  395. sqlite3_free(z2);
  396. }else{
  397. vfprintf(out, zFormat, ap);
  398. }
  399. va_end(ap);
  400. }
  401. #elif !defined(utf8_printf)
  402. # define utf8_printf fprintf
  403. #endif
  404. /*
  405. ** Render output like fprintf(). This should not be used on anything that
  406. ** includes string formatting (e.g. "%s").
  407. */
  408. #if !defined(raw_printf)
  409. # define raw_printf fprintf
  410. #endif
  411. /* Indicate out-of-memory and exit. */
  412. static void shell_out_of_memory(void){
  413. raw_printf(stderr,"Error: out of memory\n");
  414. exit(1);
  415. }
  416. /*
  417. ** Write I/O traces to the following stream.
  418. */
  419. #ifdef SQLITE_ENABLE_IOTRACE
  420. static FILE *iotrace = 0;
  421. #endif
  422. /*
  423. ** This routine works like printf in that its first argument is a
  424. ** format string and subsequent arguments are values to be substituted
  425. ** in place of % fields. The result of formatting this string
  426. ** is written to iotrace.
  427. */
  428. #ifdef SQLITE_ENABLE_IOTRACE
  429. static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
  430. va_list ap;
  431. char *z;
  432. if( iotrace==0 ) return;
  433. va_start(ap, zFormat);
  434. z = sqlite3_vmprintf(zFormat, ap);
  435. va_end(ap);
  436. utf8_printf(iotrace, "%s", z);
  437. sqlite3_free(z);
  438. }
  439. #endif
  440. /*
  441. ** Output string zUtf to stream pOut as w characters. If w is negative,
  442. ** then right-justify the text. W is the width in UTF-8 characters, not
  443. ** in bytes. This is different from the %*.*s specification in printf
  444. ** since with %*.*s the width is measured in bytes, not characters.
  445. */
  446. static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
  447. int i;
  448. int n;
  449. int aw = w<0 ? -w : w;
  450. char zBuf[1000];
  451. if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
  452. for(i=n=0; zUtf[i]; i++){
  453. if( (zUtf[i]&0xc0)!=0x80 ){
  454. n++;
  455. if( n==aw ){
  456. do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
  457. break;
  458. }
  459. }
  460. }
  461. if( n>=aw ){
  462. utf8_printf(pOut, "%.*s", i, zUtf);
  463. }else if( w<0 ){
  464. utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
  465. }else{
  466. utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
  467. }
  468. }
  469. /*
  470. ** Determines if a string is a number of not.
  471. */
  472. static int isNumber(const char *z, int *realnum){
  473. if( *z=='-' || *z=='+' ) z++;
  474. if( !IsDigit(*z) ){
  475. return 0;
  476. }
  477. z++;
  478. if( realnum ) *realnum = 0;
  479. while( IsDigit(*z) ){ z++; }
  480. if( *z=='.' ){
  481. z++;
  482. if( !IsDigit(*z) ) return 0;
  483. while( IsDigit(*z) ){ z++; }
  484. if( realnum ) *realnum = 1;
  485. }
  486. if( *z=='e' || *z=='E' ){
  487. z++;
  488. if( *z=='+' || *z=='-' ) z++;
  489. if( !IsDigit(*z) ) return 0;
  490. while( IsDigit(*z) ){ z++; }
  491. if( realnum ) *realnum = 1;
  492. }
  493. return *z==0;
  494. }
  495. /*
  496. ** Compute a string length that is limited to what can be stored in
  497. ** lower 30 bits of a 32-bit signed integer.
  498. */
  499. static int strlen30(const char *z){
  500. const char *z2 = z;
  501. while( *z2 ){ z2++; }
  502. return 0x3fffffff & (int)(z2 - z);
  503. }
  504. /*
  505. ** Return the length of a string in characters. Multibyte UTF8 characters
  506. ** count as a single character.
  507. */
  508. static int strlenChar(const char *z){
  509. int n = 0;
  510. while( *z ){
  511. if( (0xc0&*(z++))!=0x80 ) n++;
  512. }
  513. return n;
  514. }
  515. /*
  516. ** This routine reads a line of text from FILE in, stores
  517. ** the text in memory obtained from malloc() and returns a pointer
  518. ** to the text. NULL is returned at end of file, or if malloc()
  519. ** fails.
  520. **
  521. ** If zLine is not NULL then it is a malloced buffer returned from
  522. ** a previous call to this routine that may be reused.
  523. */
  524. static char *local_getline(char *zLine, FILE *in){
  525. int nLine = zLine==0 ? 0 : 100;
  526. int n = 0;
  527. while( 1 ){
  528. if( n+100>nLine ){
  529. nLine = nLine*2 + 100;
  530. zLine = realloc(zLine, nLine);
  531. if( zLine==0 ) shell_out_of_memory();
  532. }
  533. if( fgets(&zLine[n], nLine - n, in)==0 ){
  534. if( n==0 ){
  535. free(zLine);
  536. return 0;
  537. }
  538. zLine[n] = 0;
  539. break;
  540. }
  541. while( zLine[n] ) n++;
  542. if( n>0 && zLine[n-1]=='\n' ){
  543. n--;
  544. if( n>0 && zLine[n-1]=='\r' ) n--;
  545. zLine[n] = 0;
  546. break;
  547. }
  548. }
  549. #if defined(_WIN32) || defined(WIN32)
  550. /* For interactive input on Windows systems, translate the
  551. ** multi-byte characterset characters into UTF-8. */
  552. if( stdin_is_interactive && in==stdin ){
  553. char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
  554. if( zTrans ){
  555. int nTrans = strlen30(zTrans)+1;
  556. if( nTrans>nLine ){
  557. zLine = realloc(zLine, nTrans);
  558. if( zLine==0 ) shell_out_of_memory();
  559. }
  560. memcpy(zLine, zTrans, nTrans);
  561. sqlite3_free(zTrans);
  562. }
  563. }
  564. #endif /* defined(_WIN32) || defined(WIN32) */
  565. return zLine;
  566. }
  567. /*
  568. ** Retrieve a single line of input text.
  569. **
  570. ** If in==0 then read from standard input and prompt before each line.
  571. ** If isContinuation is true, then a continuation prompt is appropriate.
  572. ** If isContinuation is zero, then the main prompt should be used.
  573. **
  574. ** If zPrior is not NULL then it is a buffer from a prior call to this
  575. ** routine that can be reused.
  576. **
  577. ** The result is stored in space obtained from malloc() and must either
  578. ** be freed by the caller or else passed back into this routine via the
  579. ** zPrior argument for reuse.
  580. */
  581. static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
  582. char *zPrompt;
  583. char *zResult;
  584. if( in!=0 ){
  585. zResult = local_getline(zPrior, in);
  586. }else{
  587. zPrompt = isContinuation ? continuePrompt : mainPrompt;
  588. #if SHELL_USE_LOCAL_GETLINE
  589. printf("%s", zPrompt);
  590. fflush(stdout);
  591. zResult = local_getline(zPrior, stdin);
  592. #else
  593. free(zPrior);
  594. zResult = shell_readline(zPrompt);
  595. if( zResult && *zResult ) shell_add_history(zResult);
  596. #endif
  597. }
  598. return zResult;
  599. }
  600. /*
  601. ** Return the value of a hexadecimal digit. Return -1 if the input
  602. ** is not a hex digit.
  603. */
  604. static int hexDigitValue(char c){
  605. if( c>='0' && c<='9' ) return c - '0';
  606. if( c>='a' && c<='f' ) return c - 'a' + 10;
  607. if( c>='A' && c<='F' ) return c - 'A' + 10;
  608. return -1;
  609. }
  610. /*
  611. ** Interpret zArg as an integer value, possibly with suffixes.
  612. */
  613. static sqlite3_int64 integerValue(const char *zArg){
  614. sqlite3_int64 v = 0;
  615. static const struct { char *zSuffix; int iMult; } aMult[] = {
  616. { "KiB", 1024 },
  617. { "MiB", 1024*1024 },
  618. { "GiB", 1024*1024*1024 },
  619. { "KB", 1000 },
  620. { "MB", 1000000 },
  621. { "GB", 1000000000 },
  622. { "K", 1000 },
  623. { "M", 1000000 },
  624. { "G", 1000000000 },
  625. };
  626. int i;
  627. int isNeg = 0;
  628. if( zArg[0]=='-' ){
  629. isNeg = 1;
  630. zArg++;
  631. }else if( zArg[0]=='+' ){
  632. zArg++;
  633. }
  634. if( zArg[0]=='0' && zArg[1]=='x' ){
  635. int x;
  636. zArg += 2;
  637. while( (x = hexDigitValue(zArg[0]))>=0 ){
  638. v = (v<<4) + x;
  639. zArg++;
  640. }
  641. }else{
  642. while( IsDigit(zArg[0]) ){
  643. v = v*10 + zArg[0] - '0';
  644. zArg++;
  645. }
  646. }
  647. for(i=0; i<ArraySize(aMult); i++){
  648. if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
  649. v *= aMult[i].iMult;
  650. break;
  651. }
  652. }
  653. return isNeg? -v : v;
  654. }
  655. /*
  656. ** A variable length string to which one can append text.
  657. */
  658. typedef struct ShellText ShellText;
  659. struct ShellText {
  660. char *z;
  661. int n;
  662. int nAlloc;
  663. };
  664. /*
  665. ** Initialize and destroy a ShellText object
  666. */
  667. static void initText(ShellText *p){
  668. memset(p, 0, sizeof(*p));
  669. }
  670. static void freeText(ShellText *p){
  671. free(p->z);
  672. initText(p);
  673. }
  674. /* zIn is either a pointer to a NULL-terminated string in memory obtained
  675. ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  676. ** added to zIn, and the result returned in memory obtained from malloc().
  677. ** zIn, if it was not NULL, is freed.
  678. **
  679. ** If the third argument, quote, is not '\0', then it is used as a
  680. ** quote character for zAppend.
  681. */
  682. static void appendText(ShellText *p, char const *zAppend, char quote){
  683. int len;
  684. int i;
  685. int nAppend = strlen30(zAppend);
  686. len = nAppend+p->n+1;
  687. if( quote ){
  688. len += 2;
  689. for(i=0; i<nAppend; i++){
  690. if( zAppend[i]==quote ) len++;
  691. }
  692. }
  693. if( p->n+len>=p->nAlloc ){
  694. p->nAlloc = p->nAlloc*2 + len + 20;
  695. p->z = realloc(p->z, p->nAlloc);
  696. if( p->z==0 ) shell_out_of_memory();
  697. }
  698. if( quote ){
  699. char *zCsr = p->z+p->n;
  700. *zCsr++ = quote;
  701. for(i=0; i<nAppend; i++){
  702. *zCsr++ = zAppend[i];
  703. if( zAppend[i]==quote ) *zCsr++ = quote;
  704. }
  705. *zCsr++ = quote;
  706. p->n = (int)(zCsr - p->z);
  707. *zCsr = '\0';
  708. }else{
  709. memcpy(p->z+p->n, zAppend, nAppend);
  710. p->n += nAppend;
  711. p->z[p->n] = '\0';
  712. }
  713. }
  714. /*
  715. ** Attempt to determine if identifier zName needs to be quoted, either
  716. ** because it contains non-alphanumeric characters, or because it is an
  717. ** SQLite keyword. Be conservative in this estimate: When in doubt assume
  718. ** that quoting is required.
  719. **
  720. ** Return '"' if quoting is required. Return 0 if no quoting is required.
  721. */
  722. static char quoteChar(const char *zName){
  723. int i;
  724. if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
  725. for(i=0; zName[i]; i++){
  726. if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
  727. }
  728. return sqlite3_keyword_check(zName, i) ? '"' : 0;
  729. }
  730. /*
  731. ** Construct a fake object name and column list to describe the structure
  732. ** of the view, virtual table, or table valued function zSchema.zName.
  733. */
  734. static char *shellFakeSchema(
  735. sqlite3 *db, /* The database connection containing the vtab */
  736. const char *zSchema, /* Schema of the database holding the vtab */
  737. const char *zName /* The name of the virtual table */
  738. ){
  739. sqlite3_stmt *pStmt = 0;
  740. char *zSql;
  741. ShellText s;
  742. char cQuote;
  743. char *zDiv = "(";
  744. int nRow = 0;
  745. zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
  746. zSchema ? zSchema : "main", zName);
  747. sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  748. sqlite3_free(zSql);
  749. initText(&s);
  750. if( zSchema ){
  751. cQuote = quoteChar(zSchema);
  752. if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
  753. appendText(&s, zSchema, cQuote);
  754. appendText(&s, ".", 0);
  755. }
  756. cQuote = quoteChar(zName);
  757. appendText(&s, zName, cQuote);
  758. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  759. const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
  760. nRow++;
  761. appendText(&s, zDiv, 0);
  762. zDiv = ",";
  763. cQuote = quoteChar(zCol);
  764. appendText(&s, zCol, cQuote);
  765. }
  766. appendText(&s, ")", 0);
  767. sqlite3_finalize(pStmt);
  768. if( nRow==0 ){
  769. freeText(&s);
  770. s.z = 0;
  771. }
  772. return s.z;
  773. }
  774. /*
  775. ** SQL function: shell_module_schema(X)
  776. **
  777. ** Return a fake schema for the table-valued function or eponymous virtual
  778. ** table X.
  779. */
  780. static void shellModuleSchema(
  781. sqlite3_context *pCtx,
  782. int nVal,
  783. sqlite3_value **apVal
  784. ){
  785. const char *zName = (const char*)sqlite3_value_text(apVal[0]);
  786. char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
  787. UNUSED_PARAMETER(nVal);
  788. if( zFake ){
  789. sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
  790. -1, sqlite3_free);
  791. free(zFake);
  792. }
  793. }
  794. /*
  795. ** SQL function: shell_add_schema(S,X)
  796. **
  797. ** Add the schema name X to the CREATE statement in S and return the result.
  798. ** Examples:
  799. **
  800. ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
  801. **
  802. ** Also works on
  803. **
  804. ** CREATE INDEX
  805. ** CREATE UNIQUE INDEX
  806. ** CREATE VIEW
  807. ** CREATE TRIGGER
  808. ** CREATE VIRTUAL TABLE
  809. **
  810. ** This UDF is used by the .schema command to insert the schema name of
  811. ** attached databases into the middle of the sqlite_master.sql field.
  812. */
  813. static void shellAddSchemaName(
  814. sqlite3_context *pCtx,
  815. int nVal,
  816. sqlite3_value **apVal
  817. ){
  818. static const char *aPrefix[] = {
  819. "TABLE",
  820. "INDEX",
  821. "UNIQUE INDEX",
  822. "VIEW",
  823. "TRIGGER",
  824. "VIRTUAL TABLE"
  825. };
  826. int i = 0;
  827. const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
  828. const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
  829. const char *zName = (const char*)sqlite3_value_text(apVal[2]);
  830. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  831. UNUSED_PARAMETER(nVal);
  832. if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
  833. for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
  834. int n = strlen30(aPrefix[i]);
  835. if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
  836. char *z = 0;
  837. char *zFake = 0;
  838. if( zSchema ){
  839. char cQuote = quoteChar(zSchema);
  840. if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
  841. z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
  842. }else{
  843. z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
  844. }
  845. }
  846. if( zName
  847. && aPrefix[i][0]=='V'
  848. && (zFake = shellFakeSchema(db, zSchema, zName))!=0
  849. ){
  850. if( z==0 ){
  851. z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
  852. }else{
  853. z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
  854. }
  855. free(zFake);
  856. }
  857. if( z ){
  858. sqlite3_result_text(pCtx, z, -1, sqlite3_free);
  859. return;
  860. }
  861. }
  862. }
  863. }
  864. sqlite3_result_value(pCtx, apVal[0]);
  865. }
  866. /*
  867. ** The source code for several run-time loadable extensions is inserted
  868. ** below by the ../tool/mkshellc.tcl script. Before processing that included
  869. ** code, we need to override some macros to make the included program code
  870. ** work here in the middle of this regular program.
  871. */
  872. #define SQLITE_EXTENSION_INIT1
  873. #define SQLITE_EXTENSION_INIT2(X) (void)(X)
  874. #if defined(_WIN32) && defined(_MSC_VER)
  875. /************************* Begin test_windirent.h ******************/
  876. /*
  877. ** 2015 November 30
  878. **
  879. ** The author disclaims copyright to this source code. In place of
  880. ** a legal notice, here is a blessing:
  881. **
  882. ** May you do good and not evil.
  883. ** May you find forgiveness for yourself and forgive others.
  884. ** May you share freely, never taking more than you give.
  885. **
  886. *************************************************************************
  887. ** This file contains declarations for most of the opendir() family of
  888. ** POSIX functions on Win32 using the MSVCRT.
  889. */
  890. #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
  891. #define SQLITE_WINDIRENT_H
  892. /*
  893. ** We need several data types from the Windows SDK header.
  894. */
  895. #ifndef WIN32_LEAN_AND_MEAN
  896. #define WIN32_LEAN_AND_MEAN
  897. #endif
  898. #include "windows.h"
  899. /*
  900. ** We need several support functions from the SQLite core.
  901. */
  902. /*
  903. ** We need several things from the ANSI and MSVCRT headers.
  904. */
  905. #include <stdio.h>
  906. #include <stdlib.h>
  907. #include <errno.h>
  908. #include <io.h>
  909. #include <limits.h>
  910. #include <sys/types.h>
  911. #include <sys/stat.h>
  912. /*
  913. ** We may need several defines that should have been in "sys/stat.h".
  914. */
  915. #ifndef S_ISREG
  916. #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
  917. #endif
  918. #ifndef S_ISDIR
  919. #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
  920. #endif
  921. #ifndef S_ISLNK
  922. #define S_ISLNK(mode) (0)
  923. #endif
  924. /*
  925. ** We may need to provide the "mode_t" type.
  926. */
  927. #ifndef MODE_T_DEFINED
  928. #define MODE_T_DEFINED
  929. typedef unsigned short mode_t;
  930. #endif
  931. /*
  932. ** We may need to provide the "ino_t" type.
  933. */
  934. #ifndef INO_T_DEFINED
  935. #define INO_T_DEFINED
  936. typedef unsigned short ino_t;
  937. #endif
  938. /*
  939. ** We need to define "NAME_MAX" if it was not present in "limits.h".
  940. */
  941. #ifndef NAME_MAX
  942. # ifdef FILENAME_MAX
  943. # define NAME_MAX (FILENAME_MAX)
  944. # else
  945. # define NAME_MAX (260)
  946. # endif
  947. #endif
  948. /*
  949. ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
  950. */
  951. #ifndef NULL_INTPTR_T
  952. # define NULL_INTPTR_T ((intptr_t)(0))
  953. #endif
  954. #ifndef BAD_INTPTR_T
  955. # define BAD_INTPTR_T ((intptr_t)(-1))
  956. #endif
  957. /*
  958. ** We need to provide the necessary structures and related types.
  959. */
  960. #ifndef DIRENT_DEFINED
  961. #define DIRENT_DEFINED
  962. typedef struct DIRENT DIRENT;
  963. typedef DIRENT *LPDIRENT;
  964. struct DIRENT {
  965. ino_t d_ino; /* Sequence number, do not use. */
  966. unsigned d_attributes; /* Win32 file attributes. */
  967. char d_name[NAME_MAX + 1]; /* Name within the directory. */
  968. };
  969. #endif
  970. #ifndef DIR_DEFINED
  971. #define DIR_DEFINED
  972. typedef struct DIR DIR;
  973. typedef DIR *LPDIR;
  974. struct DIR {
  975. intptr_t d_handle; /* Value returned by "_findfirst". */
  976. DIRENT d_first; /* DIRENT constructed based on "_findfirst". */
  977. DIRENT d_next; /* DIRENT constructed based on "_findnext". */
  978. };
  979. #endif
  980. /*
  981. ** Provide a macro, for use by the implementation, to determine if a
  982. ** particular directory entry should be skipped over when searching for
  983. ** the next directory entry that should be returned by the readdir() or
  984. ** readdir_r() functions.
  985. */
  986. #ifndef is_filtered
  987. # define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
  988. #endif
  989. /*
  990. ** Provide the function prototype for the POSIX compatiable getenv()
  991. ** function. This function is not thread-safe.
  992. */
  993. extern const char *windirent_getenv(const char *name);
  994. /*
  995. ** Finally, we can provide the function prototypes for the opendir(),
  996. ** readdir(), readdir_r(), and closedir() POSIX functions.
  997. */
  998. extern LPDIR opendir(const char *dirname);
  999. extern LPDIRENT readdir(LPDIR dirp);
  1000. extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
  1001. extern INT closedir(LPDIR dirp);
  1002. #endif /* defined(WIN32) && defined(_MSC_VER) */
  1003. /************************* End test_windirent.h ********************/
  1004. /************************* Begin test_windirent.c ******************/
  1005. /*
  1006. ** 2015 November 30
  1007. **
  1008. ** The author disclaims copyright to this source code. In place of
  1009. ** a legal notice, here is a blessing:
  1010. **
  1011. ** May you do good and not evil.
  1012. ** May you find forgiveness for yourself and forgive others.
  1013. ** May you share freely, never taking more than you give.
  1014. **
  1015. *************************************************************************
  1016. ** This file contains code to implement most of the opendir() family of
  1017. ** POSIX functions on Win32 using the MSVCRT.
  1018. */
  1019. #if defined(_WIN32) && defined(_MSC_VER)
  1020. /* #include "test_windirent.h" */
  1021. /*
  1022. ** Implementation of the POSIX getenv() function using the Win32 API.
  1023. ** This function is not thread-safe.
  1024. */
  1025. const char *windirent_getenv(
  1026. const char *name
  1027. ){
  1028. static char value[32768]; /* Maximum length, per MSDN */
  1029. DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
  1030. DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
  1031. memset(value, 0, sizeof(value));
  1032. dwRet = GetEnvironmentVariableA(name, value, dwSize);
  1033. if( dwRet==0 || dwRet>dwSize ){
  1034. /*
  1035. ** The function call to GetEnvironmentVariableA() failed -OR-
  1036. ** the buffer is not large enough. Either way, return NULL.
  1037. */
  1038. return 0;
  1039. }else{
  1040. /*
  1041. ** The function call to GetEnvironmentVariableA() succeeded
  1042. ** -AND- the buffer contains the entire value.
  1043. */
  1044. return value;
  1045. }
  1046. }
  1047. /*
  1048. ** Implementation of the POSIX opendir() function using the MSVCRT.
  1049. */
  1050. LPDIR opendir(
  1051. const char *dirname
  1052. ){
  1053. struct _finddata_t data;
  1054. LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
  1055. SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
  1056. if( dirp==NULL ) return NULL;
  1057. memset(dirp, 0, sizeof(DIR));
  1058. /* TODO: Remove this if Unix-style root paths are not used. */
  1059. if( sqlite3_stricmp(dirname, "/")==0 ){
  1060. dirname = windirent_getenv("SystemDrive");
  1061. }
  1062. memset(&data, 0, sizeof(struct _finddata_t));
  1063. _snprintf(data.name, namesize, "%s\\*", dirname);
  1064. dirp->d_handle = _findfirst(data.name, &data);
  1065. if( dirp->d_handle==BAD_INTPTR_T ){
  1066. closedir(dirp);
  1067. return NULL;
  1068. }
  1069. /* TODO: Remove this block to allow hidden and/or system files. */
  1070. if( is_filtered(data) ){
  1071. next:
  1072. memset(&data, 0, sizeof(struct _finddata_t));
  1073. if( _findnext(dirp->d_handle, &data)==-1 ){
  1074. closedir(dirp);
  1075. return NULL;
  1076. }
  1077. /* TODO: Remove this block to allow hidden and/or system files. */
  1078. if( is_filtered(data) ) goto next;
  1079. }
  1080. dirp->d_first.d_attributes = data.attrib;
  1081. strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
  1082. dirp->d_first.d_name[NAME_MAX] = '\0';
  1083. return dirp;
  1084. }
  1085. /*
  1086. ** Implementation of the POSIX readdir() function using the MSVCRT.
  1087. */
  1088. LPDIRENT readdir(
  1089. LPDIR dirp
  1090. ){
  1091. struct _finddata_t data;
  1092. if( dirp==NULL ) return NULL;
  1093. if( dirp->d_first.d_ino==0 ){
  1094. dirp->d_first.d_ino++;
  1095. dirp->d_next.d_ino++;
  1096. return &dirp->d_first;
  1097. }
  1098. next:
  1099. memset(&data, 0, sizeof(struct _finddata_t));
  1100. if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
  1101. /* TODO: Remove this block to allow hidden and/or system files. */
  1102. if( is_filtered(data) ) goto next;
  1103. dirp->d_next.d_ino++;
  1104. dirp->d_next.d_attributes = data.attrib;
  1105. strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
  1106. dirp->d_next.d_name[NAME_MAX] = '\0';
  1107. return &dirp->d_next;
  1108. }
  1109. /*
  1110. ** Implementation of the POSIX readdir_r() function using the MSVCRT.
  1111. */
  1112. INT readdir_r(
  1113. LPDIR dirp,
  1114. LPDIRENT entry,
  1115. LPDIRENT *result
  1116. ){
  1117. struct _finddata_t data;
  1118. if( dirp==NULL ) return EBADF;
  1119. if( dirp->d_first.d_ino==0 ){
  1120. dirp->d_first.d_ino++;
  1121. dirp->d_next.d_ino++;
  1122. entry->d_ino = dirp->d_first.d_ino;
  1123. entry->d_attributes = dirp->d_first.d_attributes;
  1124. strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
  1125. entry->d_name[NAME_MAX] = '\0';
  1126. *result = entry;
  1127. return 0;
  1128. }
  1129. next:
  1130. memset(&data, 0, sizeof(struct _finddata_t));
  1131. if( _findnext(dirp->d_handle, &data)==-1 ){
  1132. *result = NULL;
  1133. return ENOENT;
  1134. }
  1135. /* TODO: Remove this block to allow hidden and/or system files. */
  1136. if( is_filtered(data) ) goto next;
  1137. entry->d_ino = (ino_t)-1; /* not available */
  1138. entry->d_attributes = data.attrib;
  1139. strncpy(entry->d_name, data.name, NAME_MAX);
  1140. entry->d_name[NAME_MAX] = '\0';
  1141. *result = entry;
  1142. return 0;
  1143. }
  1144. /*
  1145. ** Implementation of the POSIX closedir() function using the MSVCRT.
  1146. */
  1147. INT closedir(
  1148. LPDIR dirp
  1149. ){
  1150. INT result = 0;
  1151. if( dirp==NULL ) return EINVAL;
  1152. if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
  1153. result = _findclose(dirp->d_handle);
  1154. }
  1155. sqlite3_free(dirp);
  1156. return result;
  1157. }
  1158. #endif /* defined(WIN32) && defined(_MSC_VER) */
  1159. /************************* End test_windirent.c ********************/
  1160. #define dirent DIRENT
  1161. #endif
  1162. /************************* Begin ../ext/misc/shathree.c ******************/
  1163. /*
  1164. ** 2017-03-08
  1165. **
  1166. ** The author disclaims copyright to this source code. In place of
  1167. ** a legal notice, here is a blessing:
  1168. **
  1169. ** May you do good and not evil.
  1170. ** May you find forgiveness for yourself and forgive others.
  1171. ** May you share freely, never taking more than you give.
  1172. **
  1173. ******************************************************************************
  1174. **
  1175. ** This SQLite extension implements functions that compute SHA3 hashes.
  1176. ** Two SQL functions are implemented:
  1177. **
  1178. ** sha3(X,SIZE)
  1179. ** sha3_query(Y,SIZE)
  1180. **
  1181. ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
  1182. ** X is NULL.
  1183. **
  1184. ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
  1185. ** and returns a hash of their results.
  1186. **
  1187. ** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm
  1188. ** is used. If SIZE is included it must be one of the integers 224, 256,
  1189. ** 384, or 512, to determine SHA3 hash variant that is computed.
  1190. */
  1191. SQLITE_EXTENSION_INIT1
  1192. #include <assert.h>
  1193. #include <string.h>
  1194. #include <stdarg.h>
  1195. /* typedef sqlite3_uint64 u64; */
  1196. /******************************************************************************
  1197. ** The Hash Engine
  1198. */
  1199. /*
  1200. ** Macros to determine whether the machine is big or little endian,
  1201. ** and whether or not that determination is run-time or compile-time.
  1202. **
  1203. ** For best performance, an attempt is made to guess at the byte-order
  1204. ** using C-preprocessor macros. If that is unsuccessful, or if
  1205. ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
  1206. ** at run-time.
  1207. */
  1208. #ifndef SHA3_BYTEORDER
  1209. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  1210. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  1211. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  1212. defined(__arm__)
  1213. # define SHA3_BYTEORDER 1234
  1214. # elif defined(sparc) || defined(__ppc__)
  1215. # define SHA3_BYTEORDER 4321
  1216. # else
  1217. # define SHA3_BYTEORDER 0
  1218. # endif
  1219. #endif
  1220. /*
  1221. ** State structure for a SHA3 hash in progress
  1222. */
  1223. typedef struct SHA3Context SHA3Context;
  1224. struct SHA3Context {
  1225. union {
  1226. u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
  1227. unsigned char x[1600]; /* ... or 1600 bytes */
  1228. } u;
  1229. unsigned nRate; /* Bytes of input accepted per Keccak iteration */
  1230. unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
  1231. unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
  1232. };
  1233. /*
  1234. ** A single step of the Keccak mixing function for a 1600-bit state
  1235. */
  1236. static void KeccakF1600Step(SHA3Context *p){
  1237. int i;
  1238. u64 b0, b1, b2, b3, b4;
  1239. u64 c0, c1, c2, c3, c4;
  1240. u64 d0, d1, d2, d3, d4;
  1241. static const u64 RC[] = {
  1242. 0x0000000000000001ULL, 0x0000000000008082ULL,
  1243. 0x800000000000808aULL, 0x8000000080008000ULL,
  1244. 0x000000000000808bULL, 0x0000000080000001ULL,
  1245. 0x8000000080008081ULL, 0x8000000000008009ULL,
  1246. 0x000000000000008aULL, 0x0000000000000088ULL,
  1247. 0x0000000080008009ULL, 0x000000008000000aULL,
  1248. 0x000000008000808bULL, 0x800000000000008bULL,
  1249. 0x8000000000008089ULL, 0x8000000000008003ULL,
  1250. 0x8000000000008002ULL, 0x8000000000000080ULL,
  1251. 0x000000000000800aULL, 0x800000008000000aULL,
  1252. 0x8000000080008081ULL, 0x8000000000008080ULL,
  1253. 0x0000000080000001ULL, 0x8000000080008008ULL
  1254. };
  1255. # define a00 (p->u.s[0])
  1256. # define a01 (p->u.s[1])
  1257. # define a02 (p->u.s[2])
  1258. # define a03 (p->u.s[3])
  1259. # define a04 (p->u.s[4])
  1260. # define a10 (p->u.s[5])
  1261. # define a11 (p->u.s[6])
  1262. # define a12 (p->u.s[7])
  1263. # define a13 (p->u.s[8])
  1264. # define a14 (p->u.s[9])
  1265. # define a20 (p->u.s[10])
  1266. # define a21 (p->u.s[11])
  1267. # define a22 (p->u.s[12])
  1268. # define a23 (p->u.s[13])
  1269. # define a24 (p->u.s[14])
  1270. # define a30 (p->u.s[15])
  1271. # define a31 (p->u.s[16])
  1272. # define a32 (p->u.s[17])
  1273. # define a33 (p->u.s[18])
  1274. # define a34 (p->u.s[19])
  1275. # define a40 (p->u.s[20])
  1276. # define a41 (p->u.s[21])
  1277. # define a42 (p->u.s[22])
  1278. # define a43 (p->u.s[23])
  1279. # define a44 (p->u.s[24])
  1280. # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
  1281. for(i=0; i<24; i+=4){
  1282. c0 = a00^a10^a20^a30^a40;
  1283. c1 = a01^a11^a21^a31^a41;
  1284. c2 = a02^a12^a22^a32^a42;
  1285. c3 = a03^a13^a23^a33^a43;
  1286. c4 = a04^a14^a24^a34^a44;
  1287. d0 = c4^ROL64(c1, 1);
  1288. d1 = c0^ROL64(c2, 1);
  1289. d2 = c1^ROL64(c3, 1);
  1290. d3 = c2^ROL64(c4, 1);
  1291. d4 = c3^ROL64(c0, 1);
  1292. b0 = (a00^d0);
  1293. b1 = ROL64((a11^d1), 44);
  1294. b2 = ROL64((a22^d2), 43);
  1295. b3 = ROL64((a33^d3), 21);
  1296. b4 = ROL64((a44^d4), 14);
  1297. a00 = b0 ^((~b1)& b2 );
  1298. a00 ^= RC[i];
  1299. a11 = b1 ^((~b2)& b3 );
  1300. a22 = b2 ^((~b3)& b4 );
  1301. a33 = b3 ^((~b4)& b0 );
  1302. a44 = b4 ^((~b0)& b1 );
  1303. b2 = ROL64((a20^d0), 3);
  1304. b3 = ROL64((a31^d1), 45);
  1305. b4 = ROL64((a42^d2), 61);
  1306. b0 = ROL64((a03^d3), 28);
  1307. b1 = ROL64((a14^d4), 20);
  1308. a20 = b0 ^((~b1)& b2 );
  1309. a31 = b1 ^((~b2)& b3 );
  1310. a42 = b2 ^((~b3)& b4 );
  1311. a03 = b3 ^((~b4)& b0 );
  1312. a14 = b4 ^((~b0)& b1 );
  1313. b4 = ROL64((a40^d0), 18);
  1314. b0 = ROL64((a01^d1), 1);
  1315. b1 = ROL64((a12^d2), 6);
  1316. b2 = ROL64((a23^d3), 25);
  1317. b3 = ROL64((a34^d4), 8);
  1318. a40 = b0 ^((~b1)& b2 );
  1319. a01 = b1 ^((~b2)& b3 );
  1320. a12 = b2 ^((~b3)& b4 );
  1321. a23 = b3 ^((~b4)& b0 );
  1322. a34 = b4 ^((~b0)& b1 );
  1323. b1 = ROL64((a10^d0), 36);
  1324. b2 = ROL64((a21^d1), 10);
  1325. b3 = ROL64((a32^d2), 15);
  1326. b4 = ROL64((a43^d3), 56);
  1327. b0 = ROL64((a04^d4), 27);
  1328. a10 = b0 ^((~b1)& b2 );
  1329. a21 = b1 ^((~b2)& b3 );
  1330. a32 = b2 ^((~b3)& b4 );
  1331. a43 = b3 ^((~b4)& b0 );
  1332. a04 = b4 ^((~b0)& b1 );
  1333. b3 = ROL64((a30^d0), 41);
  1334. b4 = ROL64((a41^d1), 2);
  1335. b0 = ROL64((a02^d2), 62);
  1336. b1 = ROL64((a13^d3), 55);
  1337. b2 = ROL64((a24^d4), 39);
  1338. a30 = b0 ^((~b1)& b2 );
  1339. a41 = b1 ^((~b2)& b3 );
  1340. a02 = b2 ^((~b3)& b4 );
  1341. a13 = b3 ^((~b4)& b0 );
  1342. a24 = b4 ^((~b0)& b1 );
  1343. c0 = a00^a20^a40^a10^a30;
  1344. c1 = a11^a31^a01^a21^a41;
  1345. c2 = a22^a42^a12^a32^a02;
  1346. c3 = a33^a03^a23^a43^a13;
  1347. c4 = a44^a14^a34^a04^a24;
  1348. d0 = c4^ROL64(c1, 1);
  1349. d1 = c0^ROL64(c2, 1);
  1350. d2 = c1^ROL64(c3, 1);
  1351. d3 = c2^ROL64(c4, 1);
  1352. d4 = c3^ROL64(c0, 1);
  1353. b0 = (a00^d0);
  1354. b1 = ROL64((a31^d1), 44);
  1355. b2 = ROL64((a12^d2), 43);
  1356. b3 = ROL64((a43^d3), 21);
  1357. b4 = ROL64((a24^d4), 14);
  1358. a00 = b0 ^((~b1)& b2 );
  1359. a00 ^= RC[i+1];
  1360. a31 = b1 ^((~b2)& b3 );
  1361. a12 = b2 ^((~b3)& b4 );
  1362. a43 = b3 ^((~b4)& b0 );
  1363. a24 = b4 ^((~b0)& b1 );
  1364. b2 = ROL64((a40^d0), 3);
  1365. b3 = ROL64((a21^d1), 45);
  1366. b4 = ROL64((a02^d2), 61);
  1367. b0 = ROL64((a33^d3), 28);
  1368. b1 = ROL64((a14^d4), 20);
  1369. a40 = b0 ^((~b1)& b2 );
  1370. a21 = b1 ^((~b2)& b3 );
  1371. a02 = b2 ^((~b3)& b4 );
  1372. a33 = b3 ^((~b4)& b0 );
  1373. a14 = b4 ^((~b0)& b1 );
  1374. b4 = ROL64((a30^d0), 18);
  1375. b0 = ROL64((a11^d1), 1);
  1376. b1 = ROL64((a42^d2), 6);
  1377. b2 = ROL64((a23^d3), 25);
  1378. b3 = ROL64((a04^d4), 8);
  1379. a30 = b0 ^((~b1)& b2 );
  1380. a11 = b1 ^((~b2)& b3 );
  1381. a42 = b2 ^((~b3)& b4 );
  1382. a23 = b3 ^((~b4)& b0 );
  1383. a04 = b4 ^((~b0)& b1 );
  1384. b1 = ROL64((a20^d0), 36);
  1385. b2 = ROL64((a01^d1), 10);
  1386. b3 = ROL64((a32^d2), 15);
  1387. b4 = ROL64((a13^d3), 56);
  1388. b0 = ROL64((a44^d4), 27);
  1389. a20 = b0 ^((~b1)& b2 );
  1390. a01 = b1 ^((~b2)& b3 );
  1391. a32 = b2 ^((~b3)& b4 );
  1392. a13 = b3 ^((~b4)& b0 );
  1393. a44 = b4 ^((~b0)& b1 );
  1394. b3 = ROL64((a10^d0), 41);
  1395. b4 = ROL64((a41^d1), 2);
  1396. b0 = ROL64((a22^d2), 62);
  1397. b1 = ROL64((a03^d3), 55);
  1398. b2 = ROL64((a34^d4), 39);
  1399. a10 = b0 ^((~b1)& b2 );
  1400. a41 = b1 ^((~b2)& b3 );
  1401. a22 = b2 ^((~b3)& b4 );
  1402. a03 = b3 ^((~b4)& b0 );
  1403. a34 = b4 ^((~b0)& b1 );
  1404. c0 = a00^a40^a30^a20^a10;
  1405. c1 = a31^a21^a11^a01^a41;
  1406. c2 = a12^a02^a42^a32^a22;
  1407. c3 = a43^a33^a23^a13^a03;
  1408. c4 = a24^a14^a04^a44^a34;
  1409. d0 = c4^ROL64(c1, 1);
  1410. d1 = c0^ROL64(c2, 1);
  1411. d2 = c1^ROL64(c3, 1);
  1412. d3 = c2^ROL64(c4, 1);
  1413. d4 = c3^ROL64(c0, 1);
  1414. b0 = (a00^d0);
  1415. b1 = ROL64((a21^d1), 44);
  1416. b2 = ROL64((a42^d2), 43);
  1417. b3 = ROL64((a13^d3), 21);
  1418. b4 = ROL64((a34^d4), 14);
  1419. a00 = b0 ^((~b1)& b2 );
  1420. a00 ^= RC[i+2];
  1421. a21 = b1 ^((~b2)& b3 );
  1422. a42 = b2 ^((~b3)& b4 );
  1423. a13 = b3 ^((~b4)& b0 );
  1424. a34 = b4 ^((~b0)& b1 );
  1425. b2 = ROL64((a30^d0), 3);
  1426. b3 = ROL64((a01^d1), 45);
  1427. b4 = ROL64((a22^d2), 61);
  1428. b0 = ROL64((a43^d3), 28);
  1429. b1 = ROL64((a14^d4), 20);
  1430. a30 = b0 ^((~b1)& b2 );
  1431. a01 = b1 ^((~b2)& b3 );
  1432. a22 = b2 ^((~b3)& b4 );
  1433. a43 = b3 ^((~b4)& b0 );
  1434. a14 = b4 ^((~b0)& b1 );
  1435. b4 = ROL64((a10^d0), 18);
  1436. b0 = ROL64((a31^d1), 1);
  1437. b1 = ROL64((a02^d2), 6);
  1438. b2 = ROL64((a23^d3), 25);
  1439. b3 = ROL64((a44^d4), 8);
  1440. a10 = b0 ^((~b1)& b2 );
  1441. a31 = b1 ^((~b2)& b3 );
  1442. a02 = b2 ^((~b3)& b4 );
  1443. a23 = b3 ^((~b4)& b0 );
  1444. a44 = b4 ^((~b0)& b1 );
  1445. b1 = ROL64((a40^d0), 36);
  1446. b2 = ROL64((a11^d1), 10);
  1447. b3 = ROL64((a32^d2), 15);
  1448. b4 = ROL64((a03^d3), 56);
  1449. b0 = ROL64((a24^d4), 27);
  1450. a40 = b0 ^((~b1)& b2 );
  1451. a11 = b1 ^((~b2)& b3 );
  1452. a32 = b2 ^((~b3)& b4 );
  1453. a03 = b3 ^((~b4)& b0 );
  1454. a24 = b4 ^((~b0)& b1 );
  1455. b3 = ROL64((a20^d0), 41);
  1456. b4 = ROL64((a41^d1), 2);
  1457. b0 = ROL64((a12^d2), 62);
  1458. b1 = ROL64((a33^d3), 55);
  1459. b2 = ROL64((a04^d4), 39);
  1460. a20 = b0 ^((~b1)& b2 );
  1461. a41 = b1 ^((~b2)& b3 );
  1462. a12 = b2 ^((~b3)& b4 );
  1463. a33 = b3 ^((~b4)& b0 );
  1464. a04 = b4 ^((~b0)& b1 );
  1465. c0 = a00^a30^a10^a40^a20;
  1466. c1 = a21^a01^a31^a11^a41;
  1467. c2 = a42^a22^a02^a32^a12;
  1468. c3 = a13^a43^a23^a03^a33;
  1469. c4 = a34^a14^a44^a24^a04;
  1470. d0 = c4^ROL64(c1, 1);
  1471. d1 = c0^ROL64(c2, 1);
  1472. d2 = c1^ROL64(c3, 1);
  1473. d3 = c2^ROL64(c4, 1);
  1474. d4 = c3^ROL64(c0, 1);
  1475. b0 = (a00^d0);
  1476. b1 = ROL64((a01^d1), 44);
  1477. b2 = ROL64((a02^d2), 43);
  1478. b3 = ROL64((a03^d3), 21);
  1479. b4 = ROL64((a04^d4), 14);
  1480. a00 = b0 ^((~b1)& b2 );
  1481. a00 ^= RC[i+3];
  1482. a01 = b1 ^((~b2)& b3 );
  1483. a02 = b2 ^((~b3)& b4 );
  1484. a03 = b3 ^((~b4)& b0 );
  1485. a04 = b4 ^((~b0)& b1 );
  1486. b2 = ROL64((a10^d0), 3);
  1487. b3 = ROL64((a11^d1), 45);
  1488. b4 = ROL64((a12^d2), 61);
  1489. b0 = ROL64((a13^d3), 28);
  1490. b1 = ROL64((a14^d4), 20);
  1491. a10 = b0 ^((~b1)& b2 );
  1492. a11 = b1 ^((~b2)& b3 );
  1493. a12 = b2 ^((~b3)& b4 );
  1494. a13 = b3 ^((~b4)& b0 );
  1495. a14 = b4 ^((~b0)& b1 );
  1496. b4 = ROL64((a20^d0), 18);
  1497. b0 = ROL64((a21^d1), 1);
  1498. b1 = ROL64((a22^d2), 6);
  1499. b2 = ROL64((a23^d3), 25);
  1500. b3 = ROL64((a24^d4), 8);
  1501. a20 = b0 ^((~b1)& b2 );
  1502. a21 = b1 ^((~b2)& b3 );
  1503. a22 = b2 ^((~b3)& b4 );
  1504. a23 = b3 ^((~b4)& b0 );
  1505. a24 = b4 ^((~b0)& b1 );
  1506. b1 = ROL64((a30^d0), 36);
  1507. b2 = ROL64((a31^d1), 10);
  1508. b3 = ROL64((a32^d2), 15);
  1509. b4 = ROL64((a33^d3), 56);
  1510. b0 = ROL64((a34^d4), 27);
  1511. a30 = b0 ^((~b1)& b2 );
  1512. a31 = b1 ^((~b2)& b3 );
  1513. a32 = b2 ^((~b3)& b4 );
  1514. a33 = b3 ^((~b4)& b0 );
  1515. a34 = b4 ^((~b0)& b1 );
  1516. b3 = ROL64((a40^d0), 41);
  1517. b4 = ROL64((a41^d1), 2);
  1518. b0 = ROL64((a42^d2), 62);
  1519. b1 = ROL64((a43^d3), 55);
  1520. b2 = ROL64((a44^d4), 39);
  1521. a40 = b0 ^((~b1)& b2 );
  1522. a41 = b1 ^((~b2)& b3 );
  1523. a42 = b2 ^((~b3)& b4 );
  1524. a43 = b3 ^((~b4)& b0 );
  1525. a44 = b4 ^((~b0)& b1 );
  1526. }
  1527. }
  1528. /*
  1529. ** Initialize a new hash. iSize determines the size of the hash
  1530. ** in bits and should be one of 224, 256, 384, or 512. Or iSize
  1531. ** can be zero to use the default hash size of 256 bits.
  1532. */
  1533. static void SHA3Init(SHA3Context *p, int iSize){
  1534. memset(p, 0, sizeof(*p));
  1535. if( iSize>=128 && iSize<=512 ){
  1536. p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
  1537. }else{
  1538. p->nRate = (1600 - 2*256)/8;
  1539. }
  1540. #if SHA3_BYTEORDER==1234
  1541. /* Known to be little-endian at compile-time. No-op */
  1542. #elif SHA3_BYTEORDER==4321
  1543. p->ixMask = 7; /* Big-endian */
  1544. #else
  1545. {
  1546. static unsigned int one = 1;
  1547. if( 1==*(unsigned char*)&one ){
  1548. /* Little endian. No byte swapping. */
  1549. p->ixMask = 0;
  1550. }else{
  1551. /* Big endian. Byte swap. */
  1552. p->ixMask = 7;
  1553. }
  1554. }
  1555. #endif
  1556. }
  1557. /*
  1558. ** Make consecutive calls to the SHA3Update function to add new content
  1559. ** to the hash
  1560. */
  1561. static void SHA3Update(
  1562. SHA3Context *p,
  1563. const unsigned char *aData,
  1564. unsigned int nData
  1565. ){
  1566. unsigned int i = 0;
  1567. #if SHA3_BYTEORDER==1234
  1568. if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
  1569. for(; i+7<nData; i+=8){
  1570. p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
  1571. p->nLoaded += 8;
  1572. if( p->nLoaded>=p->nRate ){
  1573. KeccakF1600Step(p);
  1574. p->nLoaded = 0;
  1575. }
  1576. }
  1577. }
  1578. #endif
  1579. for(; i<nData; i++){
  1580. #if SHA3_BYTEORDER==1234
  1581. p->u.x[p->nLoaded] ^= aData[i];
  1582. #elif SHA3_BYTEORDER==4321
  1583. p->u.x[p->nLoaded^0x07] ^= aData[i];
  1584. #else
  1585. p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
  1586. #endif
  1587. p->nLoaded++;
  1588. if( p->nLoaded==p->nRate ){
  1589. KeccakF1600Step(p);
  1590. p->nLoaded = 0;
  1591. }
  1592. }
  1593. }
  1594. /*
  1595. ** After all content has been added, invoke SHA3Final() to compute
  1596. ** the final hash. The function returns a pointer to the binary
  1597. ** hash value.
  1598. */
  1599. static unsigned char *SHA3Final(SHA3Context *p){
  1600. unsigned int i;
  1601. if( p->nLoaded==p->nRate-1 ){
  1602. const unsigned char c1 = 0x86;
  1603. SHA3Update(p, &c1, 1);
  1604. }else{
  1605. const unsigned char c2 = 0x06;
  1606. const unsigned char c3 = 0x80;
  1607. SHA3Update(p, &c2, 1);
  1608. p->nLoaded = p->nRate - 1;
  1609. SHA3Update(p, &c3, 1);
  1610. }
  1611. for(i=0; i<p->nRate; i++){
  1612. p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
  1613. }
  1614. return &p->u.x[p->nRate];
  1615. }
  1616. /* End of the hashing logic
  1617. *****************************************************************************/
  1618. /*
  1619. ** Implementation of the sha3(X,SIZE) function.
  1620. **
  1621. ** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
  1622. ** size is 256. If X is a BLOB, it is hashed as is.
  1623. ** For all other non-NULL types of input, X is converted into a UTF-8 string
  1624. ** and the string is hashed without the trailing 0x00 terminator. The hash
  1625. ** of a NULL value is NULL.
  1626. */
  1627. static void sha3Func(
  1628. sqlite3_context *context,
  1629. int argc,
  1630. sqlite3_value **argv
  1631. ){
  1632. SHA3Context cx;
  1633. int eType = sqlite3_value_type(argv[0]);
  1634. int nByte = sqlite3_value_bytes(argv[0]);
  1635. int iSize;
  1636. if( argc==1 ){
  1637. iSize = 256;
  1638. }else{
  1639. iSize = sqlite3_value_int(argv[1]);
  1640. if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
  1641. sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
  1642. "384 512", -1);
  1643. return;
  1644. }
  1645. }
  1646. if( eType==SQLITE_NULL ) return;
  1647. SHA3Init(&cx, iSize);
  1648. if( eType==SQLITE_BLOB ){
  1649. SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
  1650. }else{
  1651. SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
  1652. }
  1653. sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
  1654. }
  1655. /* Compute a string using sqlite3_vsnprintf() with a maximum length
  1656. ** of 50 bytes and add it to the hash.
  1657. */
  1658. static void hash_step_vformat(
  1659. SHA3Context *p, /* Add content to this context */
  1660. const char *zFormat,
  1661. ...
  1662. ){
  1663. va_list ap;
  1664. int n;
  1665. char zBuf[50];
  1666. va_start(ap, zFormat);
  1667. sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
  1668. va_end(ap);
  1669. n = (int)strlen(zBuf);
  1670. SHA3Update(p, (unsigned char*)zBuf, n);
  1671. }
  1672. /*
  1673. ** Implementation of the sha3_query(SQL,SIZE) function.
  1674. **
  1675. ** This function compiles and runs the SQL statement(s) given in the
  1676. ** argument. The results are hashed using a SIZE-bit SHA3. The default
  1677. ** size is 256.
  1678. **
  1679. ** The format of the byte stream that is hashed is summarized as follows:
  1680. **
  1681. ** S<n>:<sql>
  1682. ** R
  1683. ** N
  1684. ** I<int>
  1685. ** F<ieee-float>
  1686. ** B<size>:<bytes>
  1687. ** T<size>:<text>
  1688. **
  1689. ** <sql> is the original SQL text for each statement run and <n> is
  1690. ** the size of that text. The SQL text is UTF-8. A single R character
  1691. ** occurs before the start of each row. N means a NULL value.
  1692. ** I mean an 8-byte little-endian integer <int>. F is a floating point
  1693. ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
  1694. ** B means blobs of <size> bytes. T means text rendered as <size>
  1695. ** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
  1696. ** text integers.
  1697. **
  1698. ** For each SQL statement in the X input, there is one S segment. Each
  1699. ** S segment is followed by zero or more R segments, one for each row in the
  1700. ** result set. After each R, there are one or more N, I, F, B, or T segments,
  1701. ** one for each column in the result set. Segments are concatentated directly
  1702. ** with no delimiters of any kind.
  1703. */
  1704. static void sha3QueryFunc(
  1705. sqlite3_context *context,
  1706. int argc,
  1707. sqlite3_value **argv
  1708. ){
  1709. sqlite3 *db = sqlite3_context_db_handle(context);
  1710. const char *zSql = (const char*)sqlite3_value_text(argv[0]);
  1711. sqlite3_stmt *pStmt = 0;
  1712. int nCol; /* Number of columns in the result set */
  1713. int i; /* Loop counter */
  1714. int rc;
  1715. int n;
  1716. const char *z;
  1717. SHA3Context cx;
  1718. int iSize;
  1719. if( argc==1 ){
  1720. iSize = 256;
  1721. }else{
  1722. iSize = sqlite3_value_int(argv[1]);
  1723. if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
  1724. sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
  1725. "384 512", -1);
  1726. return;
  1727. }
  1728. }
  1729. if( zSql==0 ) return;
  1730. SHA3Init(&cx, iSize);
  1731. while( zSql[0] ){
  1732. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
  1733. if( rc ){
  1734. char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
  1735. zSql, sqlite3_errmsg(db));
  1736. sqlite3_finalize(pStmt);
  1737. sqlite3_result_error(context, zMsg, -1);
  1738. sqlite3_free(zMsg);
  1739. return;
  1740. }
  1741. if( !sqlite3_stmt_readonly(pStmt) ){
  1742. char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
  1743. sqlite3_finalize(pStmt);
  1744. sqlite3_result_error(context, zMsg, -1);
  1745. sqlite3_free(zMsg);
  1746. return;
  1747. }
  1748. nCol = sqlite3_column_count(pStmt);
  1749. z = sqlite3_sql(pStmt);
  1750. n = (int)strlen(z);
  1751. hash_step_vformat(&cx,"S%d:",n);
  1752. SHA3Update(&cx,(unsigned char*)z,n);
  1753. /* Compute a hash over the result of the query */
  1754. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  1755. SHA3Update(&cx,(const unsigned char*)"R",1);
  1756. for(i=0; i<nCol; i++){
  1757. switch( sqlite3_column_type(pStmt,i) ){
  1758. case SQLITE_NULL: {
  1759. SHA3Update(&cx, (const unsigned char*)"N",1);
  1760. break;
  1761. }
  1762. case SQLITE_INTEGER: {
  1763. sqlite3_uint64 u;
  1764. int j;
  1765. unsigned char x[9];
  1766. sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
  1767. memcpy(&u, &v, 8);
  1768. for(j=8; j>=1; j--){
  1769. x[j] = u & 0xff;
  1770. u >>= 8;
  1771. }
  1772. x[0] = 'I';
  1773. SHA3Update(&cx, x, 9);
  1774. break;
  1775. }
  1776. case SQLITE_FLOAT: {
  1777. sqlite3_uint64 u;
  1778. int j;
  1779. unsigned char x[9];
  1780. double r = sqlite3_column_double(pStmt,i);
  1781. memcpy(&u, &r, 8);
  1782. for(j=8; j>=1; j--){
  1783. x[j] = u & 0xff;
  1784. u >>= 8;
  1785. }
  1786. x[0] = 'F';
  1787. SHA3Update(&cx,x,9);
  1788. break;
  1789. }
  1790. case SQLITE_TEXT: {
  1791. int n2 = sqlite3_column_bytes(pStmt, i);
  1792. const unsigned char *z2 = sqlite3_column_text(pStmt, i);
  1793. hash_step_vformat(&cx,"T%d:",n2);
  1794. SHA3Update(&cx, z2, n2);
  1795. break;
  1796. }
  1797. case SQLITE_BLOB: {
  1798. int n2 = sqlite3_column_bytes(pStmt, i);
  1799. const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
  1800. hash_step_vformat(&cx,"B%d:",n2);
  1801. SHA3Update(&cx, z2, n2);
  1802. break;
  1803. }
  1804. }
  1805. }
  1806. }
  1807. sqlite3_finalize(pStmt);
  1808. }
  1809. sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
  1810. }
  1811. #ifdef _WIN32
  1812. #endif
  1813. int sqlite3_shathree_init(
  1814. sqlite3 *db,
  1815. char **pzErrMsg,
  1816. const sqlite3_api_routines *pApi
  1817. ){
  1818. int rc = SQLITE_OK;
  1819. SQLITE_EXTENSION_INIT2(pApi);
  1820. (void)pzErrMsg; /* Unused parameter */
  1821. rc = sqlite3_create_function(db, "sha3", 1, SQLITE_UTF8, 0,
  1822. sha3Func, 0, 0);
  1823. if( rc==SQLITE_OK ){
  1824. rc = sqlite3_create_function(db, "sha3", 2, SQLITE_UTF8, 0,
  1825. sha3Func, 0, 0);
  1826. }
  1827. if( rc==SQLITE_OK ){
  1828. rc = sqlite3_create_function(db, "sha3_query", 1, SQLITE_UTF8, 0,
  1829. sha3QueryFunc, 0, 0);
  1830. }
  1831. if( rc==SQLITE_OK ){
  1832. rc = sqlite3_create_function(db, "sha3_query", 2, SQLITE_UTF8, 0,
  1833. sha3QueryFunc, 0, 0);
  1834. }
  1835. return rc;
  1836. }
  1837. /************************* End ../ext/misc/shathree.c ********************/
  1838. /************************* Begin ../ext/misc/fileio.c ******************/
  1839. /*
  1840. ** 2014-06-13
  1841. **
  1842. ** The author disclaims copyright to this source code. In place of
  1843. ** a legal notice, here is a blessing:
  1844. **
  1845. ** May you do good and not evil.
  1846. ** May you find forgiveness for yourself and forgive others.
  1847. ** May you share freely, never taking more than you give.
  1848. **
  1849. ******************************************************************************
  1850. **
  1851. ** This SQLite extension implements SQL functions readfile() and
  1852. ** writefile(), and eponymous virtual type "fsdir".
  1853. **
  1854. ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
  1855. **
  1856. ** If neither of the optional arguments is present, then this UDF
  1857. ** function writes blob DATA to file FILE. If successful, the number
  1858. ** of bytes written is returned. If an error occurs, NULL is returned.
  1859. **
  1860. ** If the first option argument - MODE - is present, then it must
  1861. ** be passed an integer value that corresponds to a POSIX mode
  1862. ** value (file type + permissions, as returned in the stat.st_mode
  1863. ** field by the stat() system call). Three types of files may
  1864. ** be written/created:
  1865. **
  1866. ** regular files: (mode & 0170000)==0100000
  1867. ** symbolic links: (mode & 0170000)==0120000
  1868. ** directories: (mode & 0170000)==0040000
  1869. **
  1870. ** For a directory, the DATA is ignored. For a symbolic link, it is
  1871. ** interpreted as text and used as the target of the link. For a
  1872. ** regular file, it is interpreted as a blob and written into the
  1873. ** named file. Regardless of the type of file, its permissions are
  1874. ** set to (mode & 0777) before returning.
  1875. **
  1876. ** If the optional MTIME argument is present, then it is interpreted
  1877. ** as an integer - the number of seconds since the unix epoch. The
  1878. ** modification-time of the target file is set to this value before
  1879. ** returning.
  1880. **
  1881. ** If three or more arguments are passed to this function and an
  1882. ** error is encountered, an exception is raised.
  1883. **
  1884. ** READFILE(FILE):
  1885. **
  1886. ** Read and return the contents of file FILE (type blob) from disk.
  1887. **
  1888. ** FSDIR:
  1889. **
  1890. ** Used as follows:
  1891. **
  1892. ** SELECT * FROM fsdir($path [, $dir]);
  1893. **
  1894. ** Parameter $path is an absolute or relative pathname. If the file that it
  1895. ** refers to does not exist, it is an error. If the path refers to a regular
  1896. ** file or symbolic link, it returns a single row. Or, if the path refers
  1897. ** to a directory, it returns one row for the directory, and one row for each
  1898. ** file within the hierarchy rooted at $path.
  1899. **
  1900. ** Each row has the following columns:
  1901. **
  1902. ** name: Path to file or directory (text value).
  1903. ** mode: Value of stat.st_mode for directory entry (an integer).
  1904. ** mtime: Value of stat.st_mtime for directory entry (an integer).
  1905. ** data: For a regular file, a blob containing the file data. For a
  1906. ** symlink, a text value containing the text of the link. For a
  1907. ** directory, NULL.
  1908. **
  1909. ** If a non-NULL value is specified for the optional $dir parameter and
  1910. ** $path is a relative path, then $path is interpreted relative to $dir.
  1911. ** And the paths returned in the "name" column of the table are also
  1912. ** relative to directory $dir.
  1913. */
  1914. SQLITE_EXTENSION_INIT1
  1915. #include <stdio.h>
  1916. #include <string.h>
  1917. #include <assert.h>
  1918. #include <sys/types.h>
  1919. #include <sys/stat.h>
  1920. #include <fcntl.h>
  1921. #if !defined(_WIN32) && !defined(WIN32)
  1922. # include <unistd.h>
  1923. # include <dirent.h>
  1924. # include <utime.h>
  1925. # include <sys/time.h>
  1926. #else
  1927. # include "windows.h"
  1928. # include <io.h>
  1929. # include <direct.h>
  1930. /* # include "test_windirent.h" */
  1931. # define dirent DIRENT
  1932. # ifndef chmod
  1933. # define chmod _chmod
  1934. # endif
  1935. # ifndef stat
  1936. # define stat _stat
  1937. # endif
  1938. # define mkdir(path,mode) _mkdir(path)
  1939. # define lstat(path,buf) stat(path,buf)
  1940. #endif
  1941. #include <time.h>
  1942. #include <errno.h>
  1943. /*
  1944. ** Structure of the fsdir() table-valued function
  1945. */
  1946. /* 0 1 2 3 4 5 */
  1947. #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
  1948. #define FSDIR_COLUMN_NAME 0 /* Name of the file */
  1949. #define FSDIR_COLUMN_MODE 1 /* Access mode */
  1950. #define FSDIR_COLUMN_MTIME 2 /* Last modification time */
  1951. #define FSDIR_COLUMN_DATA 3 /* File content */
  1952. #define FSDIR_COLUMN_PATH 4 /* Path to top of search */
  1953. #define FSDIR_COLUMN_DIR 5 /* Path is relative to this directory */
  1954. /*
  1955. ** Set the result stored by context ctx to a blob containing the
  1956. ** contents of file zName. Or, leave the result unchanged (NULL)
  1957. ** if the file does not exist or is unreadable.
  1958. **
  1959. ** If the file exceeds the SQLite blob size limit, through an
  1960. ** SQLITE_TOOBIG error.
  1961. **
  1962. ** Throw an SQLITE_IOERR if there are difficulties pulling the file
  1963. ** off of disk.
  1964. */
  1965. static void readFileContents(sqlite3_context *ctx, const char *zName){
  1966. FILE *in;
  1967. sqlite3_int64 nIn;
  1968. void *pBuf;
  1969. sqlite3 *db;
  1970. int mxBlob;
  1971. in = fopen(zName, "rb");
  1972. if( in==0 ){
  1973. /* File does not exist or is unreadable. Leave the result set to NULL. */
  1974. return;
  1975. }
  1976. fseek(in, 0, SEEK_END);
  1977. nIn = ftell(in);
  1978. rewind(in);
  1979. db = sqlite3_context_db_handle(ctx);
  1980. mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
  1981. if( nIn>mxBlob ){
  1982. sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
  1983. fclose(in);
  1984. return;
  1985. }
  1986. pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
  1987. if( pBuf==0 ){
  1988. sqlite3_result_error_nomem(ctx);
  1989. fclose(in);
  1990. return;
  1991. }
  1992. if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
  1993. sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
  1994. }else{
  1995. sqlite3_result_error_code(ctx, SQLITE_IOERR);
  1996. sqlite3_free(pBuf);
  1997. }
  1998. fclose(in);
  1999. }
  2000. /*
  2001. ** Implementation of the "readfile(X)" SQL function. The entire content
  2002. ** of the file named X is read and returned as a BLOB. NULL is returned
  2003. ** if the file does not exist or is unreadable.
  2004. */
  2005. static void readfileFunc(
  2006. sqlite3_context *context,
  2007. int argc,
  2008. sqlite3_value **argv
  2009. ){
  2010. const char *zName;
  2011. (void)(argc); /* Unused parameter */
  2012. zName = (const char*)sqlite3_value_text(argv[0]);
  2013. if( zName==0 ) return;
  2014. readFileContents(context, zName);
  2015. }
  2016. /*
  2017. ** Set the error message contained in context ctx to the results of
  2018. ** vprintf(zFmt, ...).
  2019. */
  2020. static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
  2021. char *zMsg = 0;
  2022. va_list ap;
  2023. va_start(ap, zFmt);
  2024. zMsg = sqlite3_vmprintf(zFmt, ap);
  2025. sqlite3_result_error(ctx, zMsg, -1);
  2026. sqlite3_free(zMsg);
  2027. va_end(ap);
  2028. }
  2029. #if defined(_WIN32)
  2030. /*
  2031. ** This function is designed to convert a Win32 FILETIME structure into the
  2032. ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
  2033. */
  2034. static sqlite3_uint64 fileTimeToUnixTime(
  2035. LPFILETIME pFileTime
  2036. ){
  2037. SYSTEMTIME epochSystemTime;
  2038. ULARGE_INTEGER epochIntervals;
  2039. FILETIME epochFileTime;
  2040. ULARGE_INTEGER fileIntervals;
  2041. memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
  2042. epochSystemTime.wYear = 1970;
  2043. epochSystemTime.wMonth = 1;
  2044. epochSystemTime.wDay = 1;
  2045. SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
  2046. epochIntervals.LowPart = epochFileTime.dwLowDateTime;
  2047. epochIntervals.HighPart = epochFileTime.dwHighDateTime;
  2048. fileIntervals.LowPart = pFileTime->dwLowDateTime;
  2049. fileIntervals.HighPart = pFileTime->dwHighDateTime;
  2050. return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
  2051. }
  2052. /*
  2053. ** This function attempts to normalize the time values found in the stat()
  2054. ** buffer to UTC. This is necessary on Win32, where the runtime library
  2055. ** appears to return these values as local times.
  2056. */
  2057. static void statTimesToUtc(
  2058. const char *zPath,
  2059. struct stat *pStatBuf
  2060. ){
  2061. HANDLE hFindFile;
  2062. WIN32_FIND_DATAW fd;
  2063. LPWSTR zUnicodeName;
  2064. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
  2065. zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
  2066. if( zUnicodeName ){
  2067. memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
  2068. hFindFile = FindFirstFileW(zUnicodeName, &fd);
  2069. if( hFindFile!=NULL ){
  2070. pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
  2071. pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
  2072. pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
  2073. FindClose(hFindFile);
  2074. }
  2075. sqlite3_free(zUnicodeName);
  2076. }
  2077. }
  2078. #endif
  2079. /*
  2080. ** This function is used in place of stat(). On Windows, special handling
  2081. ** is required in order for the included time to be returned as UTC. On all
  2082. ** other systems, this function simply calls stat().
  2083. */
  2084. static int fileStat(
  2085. const char *zPath,
  2086. struct stat *pStatBuf
  2087. ){
  2088. #if defined(_WIN32)
  2089. int rc = stat(zPath, pStatBuf);
  2090. if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
  2091. return rc;
  2092. #else
  2093. return stat(zPath, pStatBuf);
  2094. #endif
  2095. }
  2096. /*
  2097. ** This function is used in place of lstat(). On Windows, special handling
  2098. ** is required in order for the included time to be returned as UTC. On all
  2099. ** other systems, this function simply calls lstat().
  2100. */
  2101. static int fileLinkStat(
  2102. const char *zPath,
  2103. struct stat *pStatBuf
  2104. ){
  2105. #if defined(_WIN32)
  2106. int rc = lstat(zPath, pStatBuf);
  2107. if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
  2108. return rc;
  2109. #else
  2110. return lstat(zPath, pStatBuf);
  2111. #endif
  2112. }
  2113. /*
  2114. ** Argument zFile is the name of a file that will be created and/or written
  2115. ** by SQL function writefile(). This function ensures that the directory
  2116. ** zFile will be written to exists, creating it if required. The permissions
  2117. ** for any path components created by this function are set in accordance
  2118. ** with the current umask.
  2119. **
  2120. ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
  2121. ** SQLITE_OK is returned if the directory is successfully created, or
  2122. ** SQLITE_ERROR otherwise.
  2123. */
  2124. static int makeDirectory(
  2125. const char *zFile
  2126. ){
  2127. char *zCopy = sqlite3_mprintf("%s", zFile);
  2128. int rc = SQLITE_OK;
  2129. if( zCopy==0 ){
  2130. rc = SQLITE_NOMEM;
  2131. }else{
  2132. int nCopy = (int)strlen(zCopy);
  2133. int i = 1;
  2134. while( rc==SQLITE_OK ){
  2135. struct stat sStat;
  2136. int rc2;
  2137. for(; zCopy[i]!='/' && i<nCopy; i++);
  2138. if( i==nCopy ) break;
  2139. zCopy[i] = '\0';
  2140. rc2 = fileStat(zCopy, &sStat);
  2141. if( rc2!=0 ){
  2142. if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
  2143. }else{
  2144. if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
  2145. }
  2146. zCopy[i] = '/';
  2147. i++;
  2148. }
  2149. sqlite3_free(zCopy);
  2150. }
  2151. return rc;
  2152. }
  2153. /*
  2154. ** This function does the work for the writefile() UDF. Refer to
  2155. ** header comments at the top of this file for details.
  2156. */
  2157. static int writeFile(
  2158. sqlite3_context *pCtx, /* Context to return bytes written in */
  2159. const char *zFile, /* File to write */
  2160. sqlite3_value *pData, /* Data to write */
  2161. mode_t mode, /* MODE parameter passed to writefile() */
  2162. sqlite3_int64 mtime /* MTIME parameter (or -1 to not set time) */
  2163. ){
  2164. #if !defined(_WIN32) && !defined(WIN32)
  2165. if( S_ISLNK(mode) ){
  2166. const char *zTo = (const char*)sqlite3_value_text(pData);
  2167. if( symlink(zTo, zFile)<0 ) return 1;
  2168. }else
  2169. #endif
  2170. {
  2171. if( S_ISDIR(mode) ){
  2172. if( mkdir(zFile, mode) ){
  2173. /* The mkdir() call to create the directory failed. This might not
  2174. ** be an error though - if there is already a directory at the same
  2175. ** path and either the permissions already match or can be changed
  2176. ** to do so using chmod(), it is not an error. */
  2177. struct stat sStat;
  2178. if( errno!=EEXIST
  2179. || 0!=fileStat(zFile, &sStat)
  2180. || !S_ISDIR(sStat.st_mode)
  2181. || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
  2182. ){
  2183. return 1;
  2184. }
  2185. }
  2186. }else{
  2187. sqlite3_int64 nWrite = 0;
  2188. const char *z;
  2189. int rc = 0;
  2190. FILE *out = fopen(zFile, "wb");
  2191. if( out==0 ) return 1;
  2192. z = (const char*)sqlite3_value_blob(pData);
  2193. if( z ){
  2194. sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
  2195. nWrite = sqlite3_value_bytes(pData);
  2196. if( nWrite!=n ){
  2197. rc = 1;
  2198. }
  2199. }
  2200. fclose(out);
  2201. if( rc==0 && mode && chmod(zFile, mode & 0777) ){
  2202. rc = 1;
  2203. }
  2204. if( rc ) return 2;
  2205. sqlite3_result_int64(pCtx, nWrite);
  2206. }
  2207. }
  2208. if( mtime>=0 ){
  2209. #if defined(_WIN32)
  2210. /* Windows */
  2211. FILETIME lastAccess;
  2212. FILETIME lastWrite;
  2213. SYSTEMTIME currentTime;
  2214. LONGLONG intervals;
  2215. HANDLE hFile;
  2216. LPWSTR zUnicodeName;
  2217. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
  2218. GetSystemTime(&currentTime);
  2219. SystemTimeToFileTime(&currentTime, &lastAccess);
  2220. intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
  2221. lastWrite.dwLowDateTime = (DWORD)intervals;
  2222. lastWrite.dwHighDateTime = intervals >> 32;
  2223. zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
  2224. if( zUnicodeName==0 ){
  2225. return 1;
  2226. }
  2227. hFile = CreateFileW(
  2228. zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
  2229. FILE_FLAG_BACKUP_SEMANTICS, NULL
  2230. );
  2231. sqlite3_free(zUnicodeName);
  2232. if( hFile!=INVALID_HANDLE_VALUE ){
  2233. BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
  2234. CloseHandle(hFile);
  2235. return !bResult;
  2236. }else{
  2237. return 1;
  2238. }
  2239. #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
  2240. /* Recent unix */
  2241. struct timespec times[2];
  2242. times[0].tv_nsec = times[1].tv_nsec = 0;
  2243. times[0].tv_sec = time(0);
  2244. times[1].tv_sec = mtime;
  2245. if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
  2246. return 1;
  2247. }
  2248. #else
  2249. /* Legacy unix */
  2250. struct timeval times[2];
  2251. times[0].tv_usec = times[1].tv_usec = 0;
  2252. times[0].tv_sec = time(0);
  2253. times[1].tv_sec = mtime;
  2254. if( utimes(zFile, times) ){
  2255. return 1;
  2256. }
  2257. #endif
  2258. }
  2259. return 0;
  2260. }
  2261. /*
  2262. ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
  2263. ** Refer to header comments at the top of this file for details.
  2264. */
  2265. static void writefileFunc(
  2266. sqlite3_context *context,
  2267. int argc,
  2268. sqlite3_value **argv
  2269. ){
  2270. const char *zFile;
  2271. mode_t mode = 0;
  2272. int res;
  2273. sqlite3_int64 mtime = -1;
  2274. if( argc<2 || argc>4 ){
  2275. sqlite3_result_error(context,
  2276. "wrong number of arguments to function writefile()", -1
  2277. );
  2278. return;
  2279. }
  2280. zFile = (const char*)sqlite3_value_text(argv[0]);
  2281. if( zFile==0 ) return;
  2282. if( argc>=3 ){
  2283. mode = (mode_t)sqlite3_value_int(argv[2]);
  2284. }
  2285. if( argc==4 ){
  2286. mtime = sqlite3_value_int64(argv[3]);
  2287. }
  2288. res = writeFile(context, zFile, argv[1], mode, mtime);
  2289. if( res==1 && errno==ENOENT ){
  2290. if( makeDirectory(zFile)==SQLITE_OK ){
  2291. res = writeFile(context, zFile, argv[1], mode, mtime);
  2292. }
  2293. }
  2294. if( argc>2 && res!=0 ){
  2295. if( S_ISLNK(mode) ){
  2296. ctxErrorMsg(context, "failed to create symlink: %s", zFile);
  2297. }else if( S_ISDIR(mode) ){
  2298. ctxErrorMsg(context, "failed to create directory: %s", zFile);
  2299. }else{
  2300. ctxErrorMsg(context, "failed to write file: %s", zFile);
  2301. }
  2302. }
  2303. }
  2304. /*
  2305. ** SQL function: lsmode(MODE)
  2306. **
  2307. ** Given a numberic st_mode from stat(), convert it into a human-readable
  2308. ** text string in the style of "ls -l".
  2309. */
  2310. static void lsModeFunc(
  2311. sqlite3_context *context,
  2312. int argc,
  2313. sqlite3_value **argv
  2314. ){
  2315. int i;
  2316. int iMode = sqlite3_value_int(argv[0]);
  2317. char z[16];
  2318. (void)argc;
  2319. if( S_ISLNK(iMode) ){
  2320. z[0] = 'l';
  2321. }else if( S_ISREG(iMode) ){
  2322. z[0] = '-';
  2323. }else if( S_ISDIR(iMode) ){
  2324. z[0] = 'd';
  2325. }else{
  2326. z[0] = '?';
  2327. }
  2328. for(i=0; i<3; i++){
  2329. int m = (iMode >> ((2-i)*3));
  2330. char *a = &z[1 + i*3];
  2331. a[0] = (m & 0x4) ? 'r' : '-';
  2332. a[1] = (m & 0x2) ? 'w' : '-';
  2333. a[2] = (m & 0x1) ? 'x' : '-';
  2334. }
  2335. z[10] = '\0';
  2336. sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
  2337. }
  2338. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2339. /*
  2340. ** Cursor type for recursively iterating through a directory structure.
  2341. */
  2342. typedef struct fsdir_cursor fsdir_cursor;
  2343. typedef struct FsdirLevel FsdirLevel;
  2344. struct FsdirLevel {
  2345. DIR *pDir; /* From opendir() */
  2346. char *zDir; /* Name of directory (nul-terminated) */
  2347. };
  2348. struct fsdir_cursor {
  2349. sqlite3_vtab_cursor base; /* Base class - must be first */
  2350. int nLvl; /* Number of entries in aLvl[] array */
  2351. int iLvl; /* Index of current entry */
  2352. FsdirLevel *aLvl; /* Hierarchy of directories being traversed */
  2353. const char *zBase;
  2354. int nBase;
  2355. struct stat sStat; /* Current lstat() results */
  2356. char *zPath; /* Path to current entry */
  2357. sqlite3_int64 iRowid; /* Current rowid */
  2358. };
  2359. typedef struct fsdir_tab fsdir_tab;
  2360. struct fsdir_tab {
  2361. sqlite3_vtab base; /* Base class - must be first */
  2362. };
  2363. /*
  2364. ** Construct a new fsdir virtual table object.
  2365. */
  2366. static int fsdirConnect(
  2367. sqlite3 *db,
  2368. void *pAux,
  2369. int argc, const char *const*argv,
  2370. sqlite3_vtab **ppVtab,
  2371. char **pzErr
  2372. ){
  2373. fsdir_tab *pNew = 0;
  2374. int rc;
  2375. (void)pAux;
  2376. (void)argc;
  2377. (void)argv;
  2378. (void)pzErr;
  2379. rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
  2380. if( rc==SQLITE_OK ){
  2381. pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
  2382. if( pNew==0 ) return SQLITE_NOMEM;
  2383. memset(pNew, 0, sizeof(*pNew));
  2384. }
  2385. *ppVtab = (sqlite3_vtab*)pNew;
  2386. return rc;
  2387. }
  2388. /*
  2389. ** This method is the destructor for fsdir vtab objects.
  2390. */
  2391. static int fsdirDisconnect(sqlite3_vtab *pVtab){
  2392. sqlite3_free(pVtab);
  2393. return SQLITE_OK;
  2394. }
  2395. /*
  2396. ** Constructor for a new fsdir_cursor object.
  2397. */
  2398. static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  2399. fsdir_cursor *pCur;
  2400. (void)p;
  2401. pCur = sqlite3_malloc( sizeof(*pCur) );
  2402. if( pCur==0 ) return SQLITE_NOMEM;
  2403. memset(pCur, 0, sizeof(*pCur));
  2404. pCur->iLvl = -1;
  2405. *ppCursor = &pCur->base;
  2406. return SQLITE_OK;
  2407. }
  2408. /*
  2409. ** Reset a cursor back to the state it was in when first returned
  2410. ** by fsdirOpen().
  2411. */
  2412. static void fsdirResetCursor(fsdir_cursor *pCur){
  2413. int i;
  2414. for(i=0; i<=pCur->iLvl; i++){
  2415. FsdirLevel *pLvl = &pCur->aLvl[i];
  2416. if( pLvl->pDir ) closedir(pLvl->pDir);
  2417. sqlite3_free(pLvl->zDir);
  2418. }
  2419. sqlite3_free(pCur->zPath);
  2420. sqlite3_free(pCur->aLvl);
  2421. pCur->aLvl = 0;
  2422. pCur->zPath = 0;
  2423. pCur->zBase = 0;
  2424. pCur->nBase = 0;
  2425. pCur->nLvl = 0;
  2426. pCur->iLvl = -1;
  2427. pCur->iRowid = 1;
  2428. }
  2429. /*
  2430. ** Destructor for an fsdir_cursor.
  2431. */
  2432. static int fsdirClose(sqlite3_vtab_cursor *cur){
  2433. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2434. fsdirResetCursor(pCur);
  2435. sqlite3_free(pCur);
  2436. return SQLITE_OK;
  2437. }
  2438. /*
  2439. ** Set the error message for the virtual table associated with cursor
  2440. ** pCur to the results of vprintf(zFmt, ...).
  2441. */
  2442. static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
  2443. va_list ap;
  2444. va_start(ap, zFmt);
  2445. pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
  2446. va_end(ap);
  2447. }
  2448. /*
  2449. ** Advance an fsdir_cursor to its next row of output.
  2450. */
  2451. static int fsdirNext(sqlite3_vtab_cursor *cur){
  2452. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2453. mode_t m = pCur->sStat.st_mode;
  2454. pCur->iRowid++;
  2455. if( S_ISDIR(m) ){
  2456. /* Descend into this directory */
  2457. int iNew = pCur->iLvl + 1;
  2458. FsdirLevel *pLvl;
  2459. if( iNew>=pCur->nLvl ){
  2460. int nNew = iNew+1;
  2461. sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
  2462. FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
  2463. if( aNew==0 ) return SQLITE_NOMEM;
  2464. memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
  2465. pCur->aLvl = aNew;
  2466. pCur->nLvl = nNew;
  2467. }
  2468. pCur->iLvl = iNew;
  2469. pLvl = &pCur->aLvl[iNew];
  2470. pLvl->zDir = pCur->zPath;
  2471. pCur->zPath = 0;
  2472. pLvl->pDir = opendir(pLvl->zDir);
  2473. if( pLvl->pDir==0 ){
  2474. fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
  2475. return SQLITE_ERROR;
  2476. }
  2477. }
  2478. while( pCur->iLvl>=0 ){
  2479. FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
  2480. struct dirent *pEntry = readdir(pLvl->pDir);
  2481. if( pEntry ){
  2482. if( pEntry->d_name[0]=='.' ){
  2483. if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
  2484. if( pEntry->d_name[1]=='\0' ) continue;
  2485. }
  2486. sqlite3_free(pCur->zPath);
  2487. pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
  2488. if( pCur->zPath==0 ) return SQLITE_NOMEM;
  2489. if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
  2490. fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
  2491. return SQLITE_ERROR;
  2492. }
  2493. return SQLITE_OK;
  2494. }
  2495. closedir(pLvl->pDir);
  2496. sqlite3_free(pLvl->zDir);
  2497. pLvl->pDir = 0;
  2498. pLvl->zDir = 0;
  2499. pCur->iLvl--;
  2500. }
  2501. /* EOF */
  2502. sqlite3_free(pCur->zPath);
  2503. pCur->zPath = 0;
  2504. return SQLITE_OK;
  2505. }
  2506. /*
  2507. ** Return values of columns for the row at which the series_cursor
  2508. ** is currently pointing.
  2509. */
  2510. static int fsdirColumn(
  2511. sqlite3_vtab_cursor *cur, /* The cursor */
  2512. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  2513. int i /* Which column to return */
  2514. ){
  2515. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2516. switch( i ){
  2517. case FSDIR_COLUMN_NAME: {
  2518. sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
  2519. break;
  2520. }
  2521. case FSDIR_COLUMN_MODE:
  2522. sqlite3_result_int64(ctx, pCur->sStat.st_mode);
  2523. break;
  2524. case FSDIR_COLUMN_MTIME:
  2525. sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
  2526. break;
  2527. case FSDIR_COLUMN_DATA: {
  2528. mode_t m = pCur->sStat.st_mode;
  2529. if( S_ISDIR(m) ){
  2530. sqlite3_result_null(ctx);
  2531. #if !defined(_WIN32) && !defined(WIN32)
  2532. }else if( S_ISLNK(m) ){
  2533. char aStatic[64];
  2534. char *aBuf = aStatic;
  2535. sqlite3_int64 nBuf = 64;
  2536. int n;
  2537. while( 1 ){
  2538. n = readlink(pCur->zPath, aBuf, nBuf);
  2539. if( n<nBuf ) break;
  2540. if( aBuf!=aStatic ) sqlite3_free(aBuf);
  2541. nBuf = nBuf*2;
  2542. aBuf = sqlite3_malloc64(nBuf);
  2543. if( aBuf==0 ){
  2544. sqlite3_result_error_nomem(ctx);
  2545. return SQLITE_NOMEM;
  2546. }
  2547. }
  2548. sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
  2549. if( aBuf!=aStatic ) sqlite3_free(aBuf);
  2550. #endif
  2551. }else{
  2552. readFileContents(ctx, pCur->zPath);
  2553. }
  2554. }
  2555. case FSDIR_COLUMN_PATH:
  2556. default: {
  2557. /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
  2558. ** always return their values as NULL */
  2559. break;
  2560. }
  2561. }
  2562. return SQLITE_OK;
  2563. }
  2564. /*
  2565. ** Return the rowid for the current row. In this implementation, the
  2566. ** first row returned is assigned rowid value 1, and each subsequent
  2567. ** row a value 1 more than that of the previous.
  2568. */
  2569. static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  2570. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2571. *pRowid = pCur->iRowid;
  2572. return SQLITE_OK;
  2573. }
  2574. /*
  2575. ** Return TRUE if the cursor has been moved off of the last
  2576. ** row of output.
  2577. */
  2578. static int fsdirEof(sqlite3_vtab_cursor *cur){
  2579. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2580. return (pCur->zPath==0);
  2581. }
  2582. /*
  2583. ** xFilter callback.
  2584. **
  2585. ** idxNum==1 PATH parameter only
  2586. ** idxNum==2 Both PATH and DIR supplied
  2587. */
  2588. static int fsdirFilter(
  2589. sqlite3_vtab_cursor *cur,
  2590. int idxNum, const char *idxStr,
  2591. int argc, sqlite3_value **argv
  2592. ){
  2593. const char *zDir = 0;
  2594. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2595. (void)idxStr;
  2596. fsdirResetCursor(pCur);
  2597. if( idxNum==0 ){
  2598. fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
  2599. return SQLITE_ERROR;
  2600. }
  2601. assert( argc==idxNum && (argc==1 || argc==2) );
  2602. zDir = (const char*)sqlite3_value_text(argv[0]);
  2603. if( zDir==0 ){
  2604. fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
  2605. return SQLITE_ERROR;
  2606. }
  2607. if( argc==2 ){
  2608. pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
  2609. }
  2610. if( pCur->zBase ){
  2611. pCur->nBase = (int)strlen(pCur->zBase)+1;
  2612. pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
  2613. }else{
  2614. pCur->zPath = sqlite3_mprintf("%s", zDir);
  2615. }
  2616. if( pCur->zPath==0 ){
  2617. return SQLITE_NOMEM;
  2618. }
  2619. if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
  2620. fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
  2621. return SQLITE_ERROR;
  2622. }
  2623. return SQLITE_OK;
  2624. }
  2625. /*
  2626. ** SQLite will invoke this method one or more times while planning a query
  2627. ** that uses the generate_series virtual table. This routine needs to create
  2628. ** a query plan for each invocation and compute an estimated cost for that
  2629. ** plan.
  2630. **
  2631. ** In this implementation idxNum is used to represent the
  2632. ** query plan. idxStr is unused.
  2633. **
  2634. ** The query plan is represented by values of idxNum:
  2635. **
  2636. ** (1) The path value is supplied by argv[0]
  2637. ** (2) Path is in argv[0] and dir is in argv[1]
  2638. */
  2639. static int fsdirBestIndex(
  2640. sqlite3_vtab *tab,
  2641. sqlite3_index_info *pIdxInfo
  2642. ){
  2643. int i; /* Loop over constraints */
  2644. int idxPath = -1; /* Index in pIdxInfo->aConstraint of PATH= */
  2645. int idxDir = -1; /* Index in pIdxInfo->aConstraint of DIR= */
  2646. int seenPath = 0; /* True if an unusable PATH= constraint is seen */
  2647. int seenDir = 0; /* True if an unusable DIR= constraint is seen */
  2648. const struct sqlite3_index_constraint *pConstraint;
  2649. (void)tab;
  2650. pConstraint = pIdxInfo->aConstraint;
  2651. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  2652. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  2653. switch( pConstraint->iColumn ){
  2654. case FSDIR_COLUMN_PATH: {
  2655. if( pConstraint->usable ){
  2656. idxPath = i;
  2657. seenPath = 0;
  2658. }else if( idxPath<0 ){
  2659. seenPath = 1;
  2660. }
  2661. break;
  2662. }
  2663. case FSDIR_COLUMN_DIR: {
  2664. if( pConstraint->usable ){
  2665. idxDir = i;
  2666. seenDir = 0;
  2667. }else if( idxDir<0 ){
  2668. seenDir = 1;
  2669. }
  2670. break;
  2671. }
  2672. }
  2673. }
  2674. if( seenPath || seenDir ){
  2675. /* If input parameters are unusable, disallow this plan */
  2676. return SQLITE_CONSTRAINT;
  2677. }
  2678. if( idxPath<0 ){
  2679. pIdxInfo->idxNum = 0;
  2680. /* The pIdxInfo->estimatedCost should have been initialized to a huge
  2681. ** number. Leave it unchanged. */
  2682. pIdxInfo->estimatedRows = 0x7fffffff;
  2683. }else{
  2684. pIdxInfo->aConstraintUsage[idxPath].omit = 1;
  2685. pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
  2686. if( idxDir>=0 ){
  2687. pIdxInfo->aConstraintUsage[idxDir].omit = 1;
  2688. pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
  2689. pIdxInfo->idxNum = 2;
  2690. pIdxInfo->estimatedCost = 10.0;
  2691. }else{
  2692. pIdxInfo->idxNum = 1;
  2693. pIdxInfo->estimatedCost = 100.0;
  2694. }
  2695. }
  2696. return SQLITE_OK;
  2697. }
  2698. /*
  2699. ** Register the "fsdir" virtual table.
  2700. */
  2701. static int fsdirRegister(sqlite3 *db){
  2702. static sqlite3_module fsdirModule = {
  2703. 0, /* iVersion */
  2704. 0, /* xCreate */
  2705. fsdirConnect, /* xConnect */
  2706. fsdirBestIndex, /* xBestIndex */
  2707. fsdirDisconnect, /* xDisconnect */
  2708. 0, /* xDestroy */
  2709. fsdirOpen, /* xOpen - open a cursor */
  2710. fsdirClose, /* xClose - close a cursor */
  2711. fsdirFilter, /* xFilter - configure scan constraints */
  2712. fsdirNext, /* xNext - advance a cursor */
  2713. fsdirEof, /* xEof - check for end of scan */
  2714. fsdirColumn, /* xColumn - read data */
  2715. fsdirRowid, /* xRowid - read data */
  2716. 0, /* xUpdate */
  2717. 0, /* xBegin */
  2718. 0, /* xSync */
  2719. 0, /* xCommit */
  2720. 0, /* xRollback */
  2721. 0, /* xFindMethod */
  2722. 0, /* xRename */
  2723. 0, /* xSavepoint */
  2724. 0, /* xRelease */
  2725. 0, /* xRollbackTo */
  2726. 0, /* xShadowName */
  2727. };
  2728. int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
  2729. return rc;
  2730. }
  2731. #else /* SQLITE_OMIT_VIRTUALTABLE */
  2732. # define fsdirRegister(x) SQLITE_OK
  2733. #endif
  2734. #ifdef _WIN32
  2735. #endif
  2736. int sqlite3_fileio_init(
  2737. sqlite3 *db,
  2738. char **pzErrMsg,
  2739. const sqlite3_api_routines *pApi
  2740. ){
  2741. int rc = SQLITE_OK;
  2742. SQLITE_EXTENSION_INIT2(pApi);
  2743. (void)pzErrMsg; /* Unused parameter */
  2744. rc = sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
  2745. readfileFunc, 0, 0);
  2746. if( rc==SQLITE_OK ){
  2747. rc = sqlite3_create_function(db, "writefile", -1, SQLITE_UTF8, 0,
  2748. writefileFunc, 0, 0);
  2749. }
  2750. if( rc==SQLITE_OK ){
  2751. rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
  2752. lsModeFunc, 0, 0);
  2753. }
  2754. if( rc==SQLITE_OK ){
  2755. rc = fsdirRegister(db);
  2756. }
  2757. return rc;
  2758. }
  2759. /************************* End ../ext/misc/fileio.c ********************/
  2760. /************************* Begin ../ext/misc/completion.c ******************/
  2761. /*
  2762. ** 2017-07-10
  2763. **
  2764. ** The author disclaims copyright to this source code. In place of
  2765. ** a legal notice, here is a blessing:
  2766. **
  2767. ** May you do good and not evil.
  2768. ** May you find forgiveness for yourself and forgive others.
  2769. ** May you share freely, never taking more than you give.
  2770. **
  2771. *************************************************************************
  2772. **
  2773. ** This file implements an eponymous virtual table that returns suggested
  2774. ** completions for a partial SQL input.
  2775. **
  2776. ** Suggested usage:
  2777. **
  2778. ** SELECT DISTINCT candidate COLLATE nocase
  2779. ** FROM completion($prefix,$wholeline)
  2780. ** ORDER BY 1;
  2781. **
  2782. ** The two query parameters are optional. $prefix is the text of the
  2783. ** current word being typed and that is to be completed. $wholeline is
  2784. ** the complete input line, used for context.
  2785. **
  2786. ** The raw completion() table might return the same candidate multiple
  2787. ** times, for example if the same column name is used to two or more
  2788. ** tables. And the candidates are returned in an arbitrary order. Hence,
  2789. ** the DISTINCT and ORDER BY are recommended.
  2790. **
  2791. ** This virtual table operates at the speed of human typing, and so there
  2792. ** is no attempt to make it fast. Even a slow implementation will be much
  2793. ** faster than any human can type.
  2794. **
  2795. */
  2796. SQLITE_EXTENSION_INIT1
  2797. #include <assert.h>
  2798. #include <string.h>
  2799. #include <ctype.h>
  2800. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2801. /* completion_vtab is a subclass of sqlite3_vtab which will
  2802. ** serve as the underlying representation of a completion virtual table
  2803. */
  2804. typedef struct completion_vtab completion_vtab;
  2805. struct completion_vtab {
  2806. sqlite3_vtab base; /* Base class - must be first */
  2807. sqlite3 *db; /* Database connection for this completion vtab */
  2808. };
  2809. /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
  2810. ** serve as the underlying representation of a cursor that scans
  2811. ** over rows of the result
  2812. */
  2813. typedef struct completion_cursor completion_cursor;
  2814. struct completion_cursor {
  2815. sqlite3_vtab_cursor base; /* Base class - must be first */
  2816. sqlite3 *db; /* Database connection for this cursor */
  2817. int nPrefix, nLine; /* Number of bytes in zPrefix and zLine */
  2818. char *zPrefix; /* The prefix for the word we want to complete */
  2819. char *zLine; /* The whole that we want to complete */
  2820. const char *zCurrentRow; /* Current output row */
  2821. int szRow; /* Length of the zCurrentRow string */
  2822. sqlite3_stmt *pStmt; /* Current statement */
  2823. sqlite3_int64 iRowid; /* The rowid */
  2824. int ePhase; /* Current phase */
  2825. int j; /* inter-phase counter */
  2826. };
  2827. /* Values for ePhase:
  2828. */
  2829. #define COMPLETION_FIRST_PHASE 1
  2830. #define COMPLETION_KEYWORDS 1
  2831. #define COMPLETION_PRAGMAS 2
  2832. #define COMPLETION_FUNCTIONS 3
  2833. #define COMPLETION_COLLATIONS 4
  2834. #define COMPLETION_INDEXES 5
  2835. #define COMPLETION_TRIGGERS 6
  2836. #define COMPLETION_DATABASES 7
  2837. #define COMPLETION_TABLES 8 /* Also VIEWs and TRIGGERs */
  2838. #define COMPLETION_COLUMNS 9
  2839. #define COMPLETION_MODULES 10
  2840. #define COMPLETION_EOF 11
  2841. /*
  2842. ** The completionConnect() method is invoked to create a new
  2843. ** completion_vtab that describes the completion virtual table.
  2844. **
  2845. ** Think of this routine as the constructor for completion_vtab objects.
  2846. **
  2847. ** All this routine needs to do is:
  2848. **
  2849. ** (1) Allocate the completion_vtab object and initialize all fields.
  2850. **
  2851. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  2852. ** result set of queries against completion will look like.
  2853. */
  2854. static int completionConnect(
  2855. sqlite3 *db,
  2856. void *pAux,
  2857. int argc, const char *const*argv,
  2858. sqlite3_vtab **ppVtab,
  2859. char **pzErr
  2860. ){
  2861. completion_vtab *pNew;
  2862. int rc;
  2863. (void)(pAux); /* Unused parameter */
  2864. (void)(argc); /* Unused parameter */
  2865. (void)(argv); /* Unused parameter */
  2866. (void)(pzErr); /* Unused parameter */
  2867. /* Column numbers */
  2868. #define COMPLETION_COLUMN_CANDIDATE 0 /* Suggested completion of the input */
  2869. #define COMPLETION_COLUMN_PREFIX 1 /* Prefix of the word to be completed */
  2870. #define COMPLETION_COLUMN_WHOLELINE 2 /* Entire line seen so far */
  2871. #define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */
  2872. rc = sqlite3_declare_vtab(db,
  2873. "CREATE TABLE x("
  2874. " candidate TEXT,"
  2875. " prefix TEXT HIDDEN,"
  2876. " wholeline TEXT HIDDEN,"
  2877. " phase INT HIDDEN" /* Used for debugging only */
  2878. ")");
  2879. if( rc==SQLITE_OK ){
  2880. pNew = sqlite3_malloc( sizeof(*pNew) );
  2881. *ppVtab = (sqlite3_vtab*)pNew;
  2882. if( pNew==0 ) return SQLITE_NOMEM;
  2883. memset(pNew, 0, sizeof(*pNew));
  2884. pNew->db = db;
  2885. }
  2886. return rc;
  2887. }
  2888. /*
  2889. ** This method is the destructor for completion_cursor objects.
  2890. */
  2891. static int completionDisconnect(sqlite3_vtab *pVtab){
  2892. sqlite3_free(pVtab);
  2893. return SQLITE_OK;
  2894. }
  2895. /*
  2896. ** Constructor for a new completion_cursor object.
  2897. */
  2898. static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  2899. completion_cursor *pCur;
  2900. pCur = sqlite3_malloc( sizeof(*pCur) );
  2901. if( pCur==0 ) return SQLITE_NOMEM;
  2902. memset(pCur, 0, sizeof(*pCur));
  2903. pCur->db = ((completion_vtab*)p)->db;
  2904. *ppCursor = &pCur->base;
  2905. return SQLITE_OK;
  2906. }
  2907. /*
  2908. ** Reset the completion_cursor.
  2909. */
  2910. static void completionCursorReset(completion_cursor *pCur){
  2911. sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0;
  2912. sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0;
  2913. sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
  2914. pCur->j = 0;
  2915. }
  2916. /*
  2917. ** Destructor for a completion_cursor.
  2918. */
  2919. static int completionClose(sqlite3_vtab_cursor *cur){
  2920. completionCursorReset((completion_cursor*)cur);
  2921. sqlite3_free(cur);
  2922. return SQLITE_OK;
  2923. }
  2924. /*
  2925. ** Advance a completion_cursor to its next row of output.
  2926. **
  2927. ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
  2928. ** record the current state of the scan. This routine sets ->zCurrentRow
  2929. ** to the current row of output and then returns. If no more rows remain,
  2930. ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
  2931. ** table that has reached the end of its scan.
  2932. **
  2933. ** The current implementation just lists potential identifiers and
  2934. ** keywords and filters them by zPrefix. Future enhancements should
  2935. ** take zLine into account to try to restrict the set of identifiers and
  2936. ** keywords based on what would be legal at the current point of input.
  2937. */
  2938. static int completionNext(sqlite3_vtab_cursor *cur){
  2939. completion_cursor *pCur = (completion_cursor*)cur;
  2940. int eNextPhase = 0; /* Next phase to try if current phase reaches end */
  2941. int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */
  2942. pCur->iRowid++;
  2943. while( pCur->ePhase!=COMPLETION_EOF ){
  2944. switch( pCur->ePhase ){
  2945. case COMPLETION_KEYWORDS: {
  2946. if( pCur->j >= sqlite3_keyword_count() ){
  2947. pCur->zCurrentRow = 0;
  2948. pCur->ePhase = COMPLETION_DATABASES;
  2949. }else{
  2950. sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
  2951. }
  2952. iCol = -1;
  2953. break;
  2954. }
  2955. case COMPLETION_DATABASES: {
  2956. if( pCur->pStmt==0 ){
  2957. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
  2958. &pCur->pStmt, 0);
  2959. }
  2960. iCol = 1;
  2961. eNextPhase = COMPLETION_TABLES;
  2962. break;
  2963. }
  2964. case COMPLETION_TABLES: {
  2965. if( pCur->pStmt==0 ){
  2966. sqlite3_stmt *pS2;
  2967. char *zSql = 0;
  2968. const char *zSep = "";
  2969. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
  2970. while( sqlite3_step(pS2)==SQLITE_ROW ){
  2971. const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
  2972. zSql = sqlite3_mprintf(
  2973. "%z%s"
  2974. "SELECT name FROM \"%w\".sqlite_master",
  2975. zSql, zSep, zDb
  2976. );
  2977. if( zSql==0 ) return SQLITE_NOMEM;
  2978. zSep = " UNION ";
  2979. }
  2980. sqlite3_finalize(pS2);
  2981. sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
  2982. sqlite3_free(zSql);
  2983. }
  2984. iCol = 0;
  2985. eNextPhase = COMPLETION_COLUMNS;
  2986. break;
  2987. }
  2988. case COMPLETION_COLUMNS: {
  2989. if( pCur->pStmt==0 ){
  2990. sqlite3_stmt *pS2;
  2991. char *zSql = 0;
  2992. const char *zSep = "";
  2993. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
  2994. while( sqlite3_step(pS2)==SQLITE_ROW ){
  2995. const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
  2996. zSql = sqlite3_mprintf(
  2997. "%z%s"
  2998. "SELECT pti.name FROM \"%w\".sqlite_master AS sm"
  2999. " JOIN pragma_table_info(sm.name,%Q) AS pti"
  3000. " WHERE sm.type='table'",
  3001. zSql, zSep, zDb, zDb
  3002. );
  3003. if( zSql==0 ) return SQLITE_NOMEM;
  3004. zSep = " UNION ";
  3005. }
  3006. sqlite3_finalize(pS2);
  3007. sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
  3008. sqlite3_free(zSql);
  3009. }
  3010. iCol = 0;
  3011. eNextPhase = COMPLETION_EOF;
  3012. break;
  3013. }
  3014. }
  3015. if( iCol<0 ){
  3016. /* This case is when the phase presets zCurrentRow */
  3017. if( pCur->zCurrentRow==0 ) continue;
  3018. }else{
  3019. if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
  3020. /* Extract the next row of content */
  3021. pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
  3022. pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
  3023. }else{
  3024. /* When all rows are finished, advance to the next phase */
  3025. sqlite3_finalize(pCur->pStmt);
  3026. pCur->pStmt = 0;
  3027. pCur->ePhase = eNextPhase;
  3028. continue;
  3029. }
  3030. }
  3031. if( pCur->nPrefix==0 ) break;
  3032. if( pCur->nPrefix<=pCur->szRow
  3033. && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
  3034. ){
  3035. break;
  3036. }
  3037. }
  3038. return SQLITE_OK;
  3039. }
  3040. /*
  3041. ** Return values of columns for the row at which the completion_cursor
  3042. ** is currently pointing.
  3043. */
  3044. static int completionColumn(
  3045. sqlite3_vtab_cursor *cur, /* The cursor */
  3046. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  3047. int i /* Which column to return */
  3048. ){
  3049. completion_cursor *pCur = (completion_cursor*)cur;
  3050. switch( i ){
  3051. case COMPLETION_COLUMN_CANDIDATE: {
  3052. sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
  3053. break;
  3054. }
  3055. case COMPLETION_COLUMN_PREFIX: {
  3056. sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
  3057. break;
  3058. }
  3059. case COMPLETION_COLUMN_WHOLELINE: {
  3060. sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
  3061. break;
  3062. }
  3063. case COMPLETION_COLUMN_PHASE: {
  3064. sqlite3_result_int(ctx, pCur->ePhase);
  3065. break;
  3066. }
  3067. }
  3068. return SQLITE_OK;
  3069. }
  3070. /*
  3071. ** Return the rowid for the current row. In this implementation, the
  3072. ** rowid is the same as the output value.
  3073. */
  3074. static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  3075. completion_cursor *pCur = (completion_cursor*)cur;
  3076. *pRowid = pCur->iRowid;
  3077. return SQLITE_OK;
  3078. }
  3079. /*
  3080. ** Return TRUE if the cursor has been moved off of the last
  3081. ** row of output.
  3082. */
  3083. static int completionEof(sqlite3_vtab_cursor *cur){
  3084. completion_cursor *pCur = (completion_cursor*)cur;
  3085. return pCur->ePhase >= COMPLETION_EOF;
  3086. }
  3087. /*
  3088. ** This method is called to "rewind" the completion_cursor object back
  3089. ** to the first row of output. This method is always called at least
  3090. ** once prior to any call to completionColumn() or completionRowid() or
  3091. ** completionEof().
  3092. */
  3093. static int completionFilter(
  3094. sqlite3_vtab_cursor *pVtabCursor,
  3095. int idxNum, const char *idxStr,
  3096. int argc, sqlite3_value **argv
  3097. ){
  3098. completion_cursor *pCur = (completion_cursor *)pVtabCursor;
  3099. int iArg = 0;
  3100. (void)(idxStr); /* Unused parameter */
  3101. (void)(argc); /* Unused parameter */
  3102. completionCursorReset(pCur);
  3103. if( idxNum & 1 ){
  3104. pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
  3105. if( pCur->nPrefix>0 ){
  3106. pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
  3107. if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
  3108. }
  3109. iArg = 1;
  3110. }
  3111. if( idxNum & 2 ){
  3112. pCur->nLine = sqlite3_value_bytes(argv[iArg]);
  3113. if( pCur->nLine>0 ){
  3114. pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
  3115. if( pCur->zLine==0 ) return SQLITE_NOMEM;
  3116. }
  3117. }
  3118. if( pCur->zLine!=0 && pCur->zPrefix==0 ){
  3119. int i = pCur->nLine;
  3120. while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
  3121. i--;
  3122. }
  3123. pCur->nPrefix = pCur->nLine - i;
  3124. if( pCur->nPrefix>0 ){
  3125. pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
  3126. if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
  3127. }
  3128. }
  3129. pCur->iRowid = 0;
  3130. pCur->ePhase = COMPLETION_FIRST_PHASE;
  3131. return completionNext(pVtabCursor);
  3132. }
  3133. /*
  3134. ** SQLite will invoke this method one or more times while planning a query
  3135. ** that uses the completion virtual table. This routine needs to create
  3136. ** a query plan for each invocation and compute an estimated cost for that
  3137. ** plan.
  3138. **
  3139. ** There are two hidden parameters that act as arguments to the table-valued
  3140. ** function: "prefix" and "wholeline". Bit 0 of idxNum is set if "prefix"
  3141. ** is available and bit 1 is set if "wholeline" is available.
  3142. */
  3143. static int completionBestIndex(
  3144. sqlite3_vtab *tab,
  3145. sqlite3_index_info *pIdxInfo
  3146. ){
  3147. int i; /* Loop over constraints */
  3148. int idxNum = 0; /* The query plan bitmask */
  3149. int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */
  3150. int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
  3151. int nArg = 0; /* Number of arguments that completeFilter() expects */
  3152. const struct sqlite3_index_constraint *pConstraint;
  3153. (void)(tab); /* Unused parameter */
  3154. pConstraint = pIdxInfo->aConstraint;
  3155. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  3156. if( pConstraint->usable==0 ) continue;
  3157. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  3158. switch( pConstraint->iColumn ){
  3159. case COMPLETION_COLUMN_PREFIX:
  3160. prefixIdx = i;
  3161. idxNum |= 1;
  3162. break;
  3163. case COMPLETION_COLUMN_WHOLELINE:
  3164. wholelineIdx = i;
  3165. idxNum |= 2;
  3166. break;
  3167. }
  3168. }
  3169. if( prefixIdx>=0 ){
  3170. pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
  3171. pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
  3172. }
  3173. if( wholelineIdx>=0 ){
  3174. pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
  3175. pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
  3176. }
  3177. pIdxInfo->idxNum = idxNum;
  3178. pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
  3179. pIdxInfo->estimatedRows = 500 - 100*nArg;
  3180. return SQLITE_OK;
  3181. }
  3182. /*
  3183. ** This following structure defines all the methods for the
  3184. ** completion virtual table.
  3185. */
  3186. static sqlite3_module completionModule = {
  3187. 0, /* iVersion */
  3188. 0, /* xCreate */
  3189. completionConnect, /* xConnect */
  3190. completionBestIndex, /* xBestIndex */
  3191. completionDisconnect, /* xDisconnect */
  3192. 0, /* xDestroy */
  3193. completionOpen, /* xOpen - open a cursor */
  3194. completionClose, /* xClose - close a cursor */
  3195. completionFilter, /* xFilter - configure scan constraints */
  3196. completionNext, /* xNext - advance a cursor */
  3197. completionEof, /* xEof - check for end of scan */
  3198. completionColumn, /* xColumn - read data */
  3199. completionRowid, /* xRowid - read data */
  3200. 0, /* xUpdate */
  3201. 0, /* xBegin */
  3202. 0, /* xSync */
  3203. 0, /* xCommit */
  3204. 0, /* xRollback */
  3205. 0, /* xFindMethod */
  3206. 0, /* xRename */
  3207. 0, /* xSavepoint */
  3208. 0, /* xRelease */
  3209. 0, /* xRollbackTo */
  3210. 0 /* xShadowName */
  3211. };
  3212. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  3213. int sqlite3CompletionVtabInit(sqlite3 *db){
  3214. int rc = SQLITE_OK;
  3215. #ifndef SQLITE_OMIT_VIRTUALTABLE
  3216. rc = sqlite3_create_module(db, "completion", &completionModule, 0);
  3217. #endif
  3218. return rc;
  3219. }
  3220. #ifdef _WIN32
  3221. #endif
  3222. int sqlite3_completion_init(
  3223. sqlite3 *db,
  3224. char **pzErrMsg,
  3225. const sqlite3_api_routines *pApi
  3226. ){
  3227. int rc = SQLITE_OK;
  3228. SQLITE_EXTENSION_INIT2(pApi);
  3229. (void)(pzErrMsg); /* Unused parameter */
  3230. #ifndef SQLITE_OMIT_VIRTUALTABLE
  3231. rc = sqlite3CompletionVtabInit(db);
  3232. #endif
  3233. return rc;
  3234. }
  3235. /************************* End ../ext/misc/completion.c ********************/
  3236. /************************* Begin ../ext/misc/appendvfs.c ******************/
  3237. /*
  3238. ** 2017-10-20
  3239. **
  3240. ** The author disclaims copyright to this source code. In place of
  3241. ** a legal notice, here is a blessing:
  3242. **
  3243. ** May you do good and not evil.
  3244. ** May you find forgiveness for yourself and forgive others.
  3245. ** May you share freely, never taking more than you give.
  3246. **
  3247. ******************************************************************************
  3248. **
  3249. ** This file implements a VFS shim that allows an SQLite database to be
  3250. ** appended onto the end of some other file, such as an executable.
  3251. **
  3252. ** A special record must appear at the end of the file that identifies the
  3253. ** file as an appended database and provides an offset to page 1. For
  3254. ** best performance page 1 should be located at a disk page boundary, though
  3255. ** that is not required.
  3256. **
  3257. ** When opening a database using this VFS, the connection might treat
  3258. ** the file as an ordinary SQLite database, or it might treat is as a
  3259. ** database appended onto some other file. Here are the rules:
  3260. **
  3261. ** (1) When opening a new empty file, that file is treated as an ordinary
  3262. ** database.
  3263. **
  3264. ** (2) When opening a file that begins with the standard SQLite prefix
  3265. ** string "SQLite format 3", that file is treated as an ordinary
  3266. ** database.
  3267. **
  3268. ** (3) When opening a file that ends with the appendvfs trailer string
  3269. ** "Start-Of-SQLite3-NNNNNNNN" that file is treated as an appended
  3270. ** database.
  3271. **
  3272. ** (4) If none of the above apply and the SQLITE_OPEN_CREATE flag is
  3273. ** set, then a new database is appended to the already existing file.
  3274. **
  3275. ** (5) Otherwise, SQLITE_CANTOPEN is returned.
  3276. **
  3277. ** To avoid unnecessary complications with the PENDING_BYTE, the size of
  3278. ** the file containing the database is limited to 1GB. This VFS will refuse
  3279. ** to read or write past the 1GB mark. This restriction might be lifted in
  3280. ** future versions. For now, if you need a large database, then keep the
  3281. ** database in a separate file.
  3282. **
  3283. ** If the file being opened is not an appended database, then this shim is
  3284. ** a pass-through into the default underlying VFS.
  3285. **/
  3286. SQLITE_EXTENSION_INIT1
  3287. #include <string.h>
  3288. #include <assert.h>
  3289. /* The append mark at the end of the database is:
  3290. **
  3291. ** Start-Of-SQLite3-NNNNNNNN
  3292. ** 123456789 123456789 12345
  3293. **
  3294. ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
  3295. ** the offset to page 1.
  3296. */
  3297. #define APND_MARK_PREFIX "Start-Of-SQLite3-"
  3298. #define APND_MARK_PREFIX_SZ 17
  3299. #define APND_MARK_SIZE 25
  3300. /*
  3301. ** Maximum size of the combined prefix + database + append-mark. This
  3302. ** must be less than 0x40000000 to avoid locking issues on Windows.
  3303. */
  3304. #define APND_MAX_SIZE (65536*15259)
  3305. /*
  3306. ** Forward declaration of objects used by this utility
  3307. */
  3308. typedef struct sqlite3_vfs ApndVfs;
  3309. typedef struct ApndFile ApndFile;
  3310. /* Access to a lower-level VFS that (might) implement dynamic loading,
  3311. ** access to randomness, etc.
  3312. */
  3313. #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
  3314. #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
  3315. /* An open file */
  3316. struct ApndFile {
  3317. sqlite3_file base; /* IO methods */
  3318. sqlite3_int64 iPgOne; /* File offset to page 1 */
  3319. sqlite3_int64 iMark; /* Start of the append-mark */
  3320. };
  3321. /*
  3322. ** Methods for ApndFile
  3323. */
  3324. static int apndClose(sqlite3_file*);
  3325. static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  3326. static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
  3327. static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
  3328. static int apndSync(sqlite3_file*, int flags);
  3329. static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
  3330. static int apndLock(sqlite3_file*, int);
  3331. static int apndUnlock(sqlite3_file*, int);
  3332. static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
  3333. static int apndFileControl(sqlite3_file*, int op, void *pArg);
  3334. static int apndSectorSize(sqlite3_file*);
  3335. static int apndDeviceCharacteristics(sqlite3_file*);
  3336. static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  3337. static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
  3338. static void apndShmBarrier(sqlite3_file*);
  3339. static int apndShmUnmap(sqlite3_file*, int deleteFlag);
  3340. static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  3341. static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  3342. /*
  3343. ** Methods for ApndVfs
  3344. */
  3345. static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
  3346. static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
  3347. static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
  3348. static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
  3349. static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
  3350. static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
  3351. static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
  3352. static void apndDlClose(sqlite3_vfs*, void*);
  3353. static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
  3354. static int apndSleep(sqlite3_vfs*, int microseconds);
  3355. static int apndCurrentTime(sqlite3_vfs*, double*);
  3356. static int apndGetLastError(sqlite3_vfs*, int, char *);
  3357. static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
  3358. static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
  3359. static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
  3360. static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
  3361. static sqlite3_vfs apnd_vfs = {
  3362. 3, /* iVersion (set when registered) */
  3363. 0, /* szOsFile (set when registered) */
  3364. 1024, /* mxPathname */
  3365. 0, /* pNext */
  3366. "apndvfs", /* zName */
  3367. 0, /* pAppData (set when registered) */
  3368. apndOpen, /* xOpen */
  3369. apndDelete, /* xDelete */
  3370. apndAccess, /* xAccess */
  3371. apndFullPathname, /* xFullPathname */
  3372. apndDlOpen, /* xDlOpen */
  3373. apndDlError, /* xDlError */
  3374. apndDlSym, /* xDlSym */
  3375. apndDlClose, /* xDlClose */
  3376. apndRandomness, /* xRandomness */
  3377. apndSleep, /* xSleep */
  3378. apndCurrentTime, /* xCurrentTime */
  3379. apndGetLastError, /* xGetLastError */
  3380. apndCurrentTimeInt64, /* xCurrentTimeInt64 */
  3381. apndSetSystemCall, /* xSetSystemCall */
  3382. apndGetSystemCall, /* xGetSystemCall */
  3383. apndNextSystemCall /* xNextSystemCall */
  3384. };
  3385. static const sqlite3_io_methods apnd_io_methods = {
  3386. 3, /* iVersion */
  3387. apndClose, /* xClose */
  3388. apndRead, /* xRead */
  3389. apndWrite, /* xWrite */
  3390. apndTruncate, /* xTruncate */
  3391. apndSync, /* xSync */
  3392. apndFileSize, /* xFileSize */
  3393. apndLock, /* xLock */
  3394. apndUnlock, /* xUnlock */
  3395. apndCheckReservedLock, /* xCheckReservedLock */
  3396. apndFileControl, /* xFileControl */
  3397. apndSectorSize, /* xSectorSize */
  3398. apndDeviceCharacteristics, /* xDeviceCharacteristics */
  3399. apndShmMap, /* xShmMap */
  3400. apndShmLock, /* xShmLock */
  3401. apndShmBarrier, /* xShmBarrier */
  3402. apndShmUnmap, /* xShmUnmap */
  3403. apndFetch, /* xFetch */
  3404. apndUnfetch /* xUnfetch */
  3405. };
  3406. /*
  3407. ** Close an apnd-file.
  3408. */
  3409. static int apndClose(sqlite3_file *pFile){
  3410. pFile = ORIGFILE(pFile);
  3411. return pFile->pMethods->xClose(pFile);
  3412. }
  3413. /*
  3414. ** Read data from an apnd-file.
  3415. */
  3416. static int apndRead(
  3417. sqlite3_file *pFile,
  3418. void *zBuf,
  3419. int iAmt,
  3420. sqlite_int64 iOfst
  3421. ){
  3422. ApndFile *p = (ApndFile *)pFile;
  3423. pFile = ORIGFILE(pFile);
  3424. return pFile->pMethods->xRead(pFile, zBuf, iAmt, iOfst+p->iPgOne);
  3425. }
  3426. /*
  3427. ** Add the append-mark onto the end of the file.
  3428. */
  3429. static int apndWriteMark(ApndFile *p, sqlite3_file *pFile){
  3430. int i;
  3431. unsigned char a[APND_MARK_SIZE];
  3432. memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
  3433. for(i=0; i<8; i++){
  3434. a[APND_MARK_PREFIX_SZ+i] = (p->iPgOne >> (56 - i*8)) & 0xff;
  3435. }
  3436. return pFile->pMethods->xWrite(pFile, a, APND_MARK_SIZE, p->iMark);
  3437. }
  3438. /*
  3439. ** Write data to an apnd-file.
  3440. */
  3441. static int apndWrite(
  3442. sqlite3_file *pFile,
  3443. const void *zBuf,
  3444. int iAmt,
  3445. sqlite_int64 iOfst
  3446. ){
  3447. int rc;
  3448. ApndFile *p = (ApndFile *)pFile;
  3449. pFile = ORIGFILE(pFile);
  3450. if( iOfst+iAmt>=APND_MAX_SIZE ) return SQLITE_FULL;
  3451. rc = pFile->pMethods->xWrite(pFile, zBuf, iAmt, iOfst+p->iPgOne);
  3452. if( rc==SQLITE_OK && iOfst + iAmt + p->iPgOne > p->iMark ){
  3453. sqlite3_int64 sz = 0;
  3454. rc = pFile->pMethods->xFileSize(pFile, &sz);
  3455. if( rc==SQLITE_OK ){
  3456. p->iMark = sz - APND_MARK_SIZE;
  3457. if( iOfst + iAmt + p->iPgOne > p->iMark ){
  3458. p->iMark = p->iPgOne + iOfst + iAmt;
  3459. rc = apndWriteMark(p, pFile);
  3460. }
  3461. }
  3462. }
  3463. return rc;
  3464. }
  3465. /*
  3466. ** Truncate an apnd-file.
  3467. */
  3468. static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
  3469. int rc;
  3470. ApndFile *p = (ApndFile *)pFile;
  3471. pFile = ORIGFILE(pFile);
  3472. rc = pFile->pMethods->xTruncate(pFile, size+p->iPgOne+APND_MARK_SIZE);
  3473. if( rc==SQLITE_OK ){
  3474. p->iMark = p->iPgOne+size;
  3475. rc = apndWriteMark(p, pFile);
  3476. }
  3477. return rc;
  3478. }
  3479. /*
  3480. ** Sync an apnd-file.
  3481. */
  3482. static int apndSync(sqlite3_file *pFile, int flags){
  3483. pFile = ORIGFILE(pFile);
  3484. return pFile->pMethods->xSync(pFile, flags);
  3485. }
  3486. /*
  3487. ** Return the current file-size of an apnd-file.
  3488. */
  3489. static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  3490. ApndFile *p = (ApndFile *)pFile;
  3491. int rc;
  3492. pFile = ORIGFILE(p);
  3493. rc = pFile->pMethods->xFileSize(pFile, pSize);
  3494. if( rc==SQLITE_OK && p->iPgOne ){
  3495. *pSize -= p->iPgOne + APND_MARK_SIZE;
  3496. }
  3497. return rc;
  3498. }
  3499. /*
  3500. ** Lock an apnd-file.
  3501. */
  3502. static int apndLock(sqlite3_file *pFile, int eLock){
  3503. pFile = ORIGFILE(pFile);
  3504. return pFile->pMethods->xLock(pFile, eLock);
  3505. }
  3506. /*
  3507. ** Unlock an apnd-file.
  3508. */
  3509. static int apndUnlock(sqlite3_file *pFile, int eLock){
  3510. pFile = ORIGFILE(pFile);
  3511. return pFile->pMethods->xUnlock(pFile, eLock);
  3512. }
  3513. /*
  3514. ** Check if another file-handle holds a RESERVED lock on an apnd-file.
  3515. */
  3516. static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  3517. pFile = ORIGFILE(pFile);
  3518. return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
  3519. }
  3520. /*
  3521. ** File control method. For custom operations on an apnd-file.
  3522. */
  3523. static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
  3524. ApndFile *p = (ApndFile *)pFile;
  3525. int rc;
  3526. pFile = ORIGFILE(pFile);
  3527. rc = pFile->pMethods->xFileControl(pFile, op, pArg);
  3528. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  3529. *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", p->iPgOne, *(char**)pArg);
  3530. }
  3531. return rc;
  3532. }
  3533. /*
  3534. ** Return the sector-size in bytes for an apnd-file.
  3535. */
  3536. static int apndSectorSize(sqlite3_file *pFile){
  3537. pFile = ORIGFILE(pFile);
  3538. return pFile->pMethods->xSectorSize(pFile);
  3539. }
  3540. /*
  3541. ** Return the device characteristic flags supported by an apnd-file.
  3542. */
  3543. static int apndDeviceCharacteristics(sqlite3_file *pFile){
  3544. pFile = ORIGFILE(pFile);
  3545. return pFile->pMethods->xDeviceCharacteristics(pFile);
  3546. }
  3547. /* Create a shared memory file mapping */
  3548. static int apndShmMap(
  3549. sqlite3_file *pFile,
  3550. int iPg,
  3551. int pgsz,
  3552. int bExtend,
  3553. void volatile **pp
  3554. ){
  3555. pFile = ORIGFILE(pFile);
  3556. return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
  3557. }
  3558. /* Perform locking on a shared-memory segment */
  3559. static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
  3560. pFile = ORIGFILE(pFile);
  3561. return pFile->pMethods->xShmLock(pFile,offset,n,flags);
  3562. }
  3563. /* Memory barrier operation on shared memory */
  3564. static void apndShmBarrier(sqlite3_file *pFile){
  3565. pFile = ORIGFILE(pFile);
  3566. pFile->pMethods->xShmBarrier(pFile);
  3567. }
  3568. /* Unmap a shared memory segment */
  3569. static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
  3570. pFile = ORIGFILE(pFile);
  3571. return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
  3572. }
  3573. /* Fetch a page of a memory-mapped file */
  3574. static int apndFetch(
  3575. sqlite3_file *pFile,
  3576. sqlite3_int64 iOfst,
  3577. int iAmt,
  3578. void **pp
  3579. ){
  3580. ApndFile *p = (ApndFile *)pFile;
  3581. pFile = ORIGFILE(pFile);
  3582. return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
  3583. }
  3584. /* Release a memory-mapped page */
  3585. static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
  3586. ApndFile *p = (ApndFile *)pFile;
  3587. pFile = ORIGFILE(pFile);
  3588. return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
  3589. }
  3590. /*
  3591. ** Check to see if the file is an ordinary SQLite database file.
  3592. */
  3593. static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
  3594. int rc;
  3595. char zHdr[16];
  3596. static const char aSqliteHdr[] = "SQLite format 3";
  3597. if( sz<512 ) return 0;
  3598. rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0);
  3599. if( rc ) return 0;
  3600. return memcmp(zHdr, aSqliteHdr, sizeof(zHdr))==0;
  3601. }
  3602. /*
  3603. ** Try to read the append-mark off the end of a file. Return the
  3604. ** start of the appended database if the append-mark is present. If
  3605. ** there is no append-mark, return -1;
  3606. */
  3607. static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
  3608. int rc, i;
  3609. sqlite3_int64 iMark;
  3610. unsigned char a[APND_MARK_SIZE];
  3611. if( sz<=APND_MARK_SIZE ) return -1;
  3612. rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
  3613. if( rc ) return -1;
  3614. if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
  3615. iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ]&0x7f))<<56;
  3616. for(i=1; i<8; i++){
  3617. iMark += (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<(56-8*i);
  3618. }
  3619. return iMark;
  3620. }
  3621. /*
  3622. ** Open an apnd file handle.
  3623. */
  3624. static int apndOpen(
  3625. sqlite3_vfs *pVfs,
  3626. const char *zName,
  3627. sqlite3_file *pFile,
  3628. int flags,
  3629. int *pOutFlags
  3630. ){
  3631. ApndFile *p;
  3632. sqlite3_file *pSubFile;
  3633. sqlite3_vfs *pSubVfs;
  3634. int rc;
  3635. sqlite3_int64 sz;
  3636. pSubVfs = ORIGVFS(pVfs);
  3637. if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
  3638. return pSubVfs->xOpen(pSubVfs, zName, pFile, flags, pOutFlags);
  3639. }
  3640. p = (ApndFile*)pFile;
  3641. memset(p, 0, sizeof(*p));
  3642. pSubFile = ORIGFILE(pFile);
  3643. p->base.pMethods = &apnd_io_methods;
  3644. rc = pSubVfs->xOpen(pSubVfs, zName, pSubFile, flags, pOutFlags);
  3645. if( rc ) goto apnd_open_done;
  3646. rc = pSubFile->pMethods->xFileSize(pSubFile, &sz);
  3647. if( rc ){
  3648. pSubFile->pMethods->xClose(pSubFile);
  3649. goto apnd_open_done;
  3650. }
  3651. if( apndIsOrdinaryDatabaseFile(sz, pSubFile) ){
  3652. memmove(pFile, pSubFile, pSubVfs->szOsFile);
  3653. return SQLITE_OK;
  3654. }
  3655. p->iMark = 0;
  3656. p->iPgOne = apndReadMark(sz, pFile);
  3657. if( p->iPgOne>0 ){
  3658. return SQLITE_OK;
  3659. }
  3660. if( (flags & SQLITE_OPEN_CREATE)==0 ){
  3661. pSubFile->pMethods->xClose(pSubFile);
  3662. rc = SQLITE_CANTOPEN;
  3663. }
  3664. p->iPgOne = (sz+0xfff) & ~(sqlite3_int64)0xfff;
  3665. apnd_open_done:
  3666. if( rc ) pFile->pMethods = 0;
  3667. return rc;
  3668. }
  3669. /*
  3670. ** All other VFS methods are pass-thrus.
  3671. */
  3672. static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  3673. return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
  3674. }
  3675. static int apndAccess(
  3676. sqlite3_vfs *pVfs,
  3677. const char *zPath,
  3678. int flags,
  3679. int *pResOut
  3680. ){
  3681. return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
  3682. }
  3683. static int apndFullPathname(
  3684. sqlite3_vfs *pVfs,
  3685. const char *zPath,
  3686. int nOut,
  3687. char *zOut
  3688. ){
  3689. return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
  3690. }
  3691. static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  3692. return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
  3693. }
  3694. static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  3695. ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
  3696. }
  3697. static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
  3698. return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
  3699. }
  3700. static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
  3701. ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
  3702. }
  3703. static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  3704. return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
  3705. }
  3706. static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
  3707. return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
  3708. }
  3709. static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  3710. return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
  3711. }
  3712. static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  3713. return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
  3714. }
  3715. static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
  3716. return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
  3717. }
  3718. static int apndSetSystemCall(
  3719. sqlite3_vfs *pVfs,
  3720. const char *zName,
  3721. sqlite3_syscall_ptr pCall
  3722. ){
  3723. return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
  3724. }
  3725. static sqlite3_syscall_ptr apndGetSystemCall(
  3726. sqlite3_vfs *pVfs,
  3727. const char *zName
  3728. ){
  3729. return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
  3730. }
  3731. static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
  3732. return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
  3733. }
  3734. #ifdef _WIN32
  3735. #endif
  3736. /*
  3737. ** This routine is called when the extension is loaded.
  3738. ** Register the new VFS.
  3739. */
  3740. int sqlite3_appendvfs_init(
  3741. sqlite3 *db,
  3742. char **pzErrMsg,
  3743. const sqlite3_api_routines *pApi
  3744. ){
  3745. int rc = SQLITE_OK;
  3746. sqlite3_vfs *pOrig;
  3747. SQLITE_EXTENSION_INIT2(pApi);
  3748. (void)pzErrMsg;
  3749. (void)db;
  3750. pOrig = sqlite3_vfs_find(0);
  3751. apnd_vfs.iVersion = pOrig->iVersion;
  3752. apnd_vfs.pAppData = pOrig;
  3753. apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
  3754. rc = sqlite3_vfs_register(&apnd_vfs, 0);
  3755. #ifdef APPENDVFS_TEST
  3756. if( rc==SQLITE_OK ){
  3757. rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
  3758. }
  3759. #endif
  3760. if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
  3761. return rc;
  3762. }
  3763. /************************* End ../ext/misc/appendvfs.c ********************/
  3764. /************************* Begin ../ext/misc/memtrace.c ******************/
  3765. /*
  3766. ** 2019-01-21
  3767. **
  3768. ** The author disclaims copyright to this source code. In place of
  3769. ** a legal notice, here is a blessing:
  3770. **
  3771. ** May you do good and not evil.
  3772. ** May you find forgiveness for yourself and forgive others.
  3773. ** May you share freely, never taking more than you give.
  3774. **
  3775. *************************************************************************
  3776. **
  3777. ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
  3778. ** mechanism to add a tracing layer on top of SQLite. If this extension
  3779. ** is registered prior to sqlite3_initialize(), it will cause all memory
  3780. ** allocation activities to be logged on standard output, or to some other
  3781. ** FILE specified by the initializer.
  3782. **
  3783. ** This file needs to be compiled into the application that uses it.
  3784. **
  3785. ** This extension is used to implement the --memtrace option of the
  3786. ** command-line shell.
  3787. */
  3788. #include <assert.h>
  3789. #include <string.h>
  3790. #include <stdio.h>
  3791. /* The original memory allocation routines */
  3792. static sqlite3_mem_methods memtraceBase;
  3793. static FILE *memtraceOut;
  3794. /* Methods that trace memory allocations */
  3795. static void *memtraceMalloc(int n){
  3796. if( memtraceOut ){
  3797. fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
  3798. memtraceBase.xRoundup(n));
  3799. }
  3800. return memtraceBase.xMalloc(n);
  3801. }
  3802. static void memtraceFree(void *p){
  3803. if( p==0 ) return;
  3804. if( memtraceOut ){
  3805. fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
  3806. }
  3807. memtraceBase.xFree(p);
  3808. }
  3809. static void *memtraceRealloc(void *p, int n){
  3810. if( p==0 ) return memtraceMalloc(n);
  3811. if( n==0 ){
  3812. memtraceFree(p);
  3813. return 0;
  3814. }
  3815. if( memtraceOut ){
  3816. fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
  3817. memtraceBase.xSize(p), memtraceBase.xRoundup(n));
  3818. }
  3819. return memtraceBase.xRealloc(p, n);
  3820. }
  3821. static int memtraceSize(void *p){
  3822. return memtraceBase.xSize(p);
  3823. }
  3824. static int memtraceRoundup(int n){
  3825. return memtraceBase.xRoundup(n);
  3826. }
  3827. static int memtraceInit(void *p){
  3828. return memtraceBase.xInit(p);
  3829. }
  3830. static void memtraceShutdown(void *p){
  3831. memtraceBase.xShutdown(p);
  3832. }
  3833. /* The substitute memory allocator */
  3834. static sqlite3_mem_methods ersaztMethods = {
  3835. memtraceMalloc,
  3836. memtraceFree,
  3837. memtraceRealloc,
  3838. memtraceSize,
  3839. memtraceRoundup,
  3840. memtraceInit,
  3841. memtraceShutdown,
  3842. 0
  3843. };
  3844. /* Begin tracing memory allocations to out. */
  3845. int sqlite3MemTraceActivate(FILE *out){
  3846. int rc = SQLITE_OK;
  3847. if( memtraceBase.xMalloc==0 ){
  3848. rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
  3849. if( rc==SQLITE_OK ){
  3850. rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
  3851. }
  3852. }
  3853. memtraceOut = out;
  3854. return rc;
  3855. }
  3856. /* Deactivate memory tracing */
  3857. int sqlite3MemTraceDeactivate(void){
  3858. int rc = SQLITE_OK;
  3859. if( memtraceBase.xMalloc!=0 ){
  3860. rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
  3861. if( rc==SQLITE_OK ){
  3862. memset(&memtraceBase, 0, sizeof(memtraceBase));
  3863. }
  3864. }
  3865. memtraceOut = 0;
  3866. return rc;
  3867. }
  3868. /************************* End ../ext/misc/memtrace.c ********************/
  3869. #ifdef SQLITE_HAVE_ZLIB
  3870. /************************* Begin ../ext/misc/zipfile.c ******************/
  3871. /*
  3872. ** 2017-12-26
  3873. **
  3874. ** The author disclaims copyright to this source code. In place of
  3875. ** a legal notice, here is a blessing:
  3876. **
  3877. ** May you do good and not evil.
  3878. ** May you find forgiveness for yourself and forgive others.
  3879. ** May you share freely, never taking more than you give.
  3880. **
  3881. ******************************************************************************
  3882. **
  3883. ** This file implements a virtual table for reading and writing ZIP archive
  3884. ** files.
  3885. **
  3886. ** Usage example:
  3887. **
  3888. ** SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
  3889. **
  3890. ** Current limitations:
  3891. **
  3892. ** * No support for encryption
  3893. ** * No support for ZIP archives spanning multiple files
  3894. ** * No support for zip64 extensions
  3895. ** * Only the "inflate/deflate" (zlib) compression method is supported
  3896. */
  3897. SQLITE_EXTENSION_INIT1
  3898. #include <stdio.h>
  3899. #include <string.h>
  3900. #include <assert.h>
  3901. #include <zlib.h>
  3902. #ifndef SQLITE_OMIT_VIRTUALTABLE
  3903. #ifndef SQLITE_AMALGAMATION
  3904. /* typedef sqlite3_int64 i64; */
  3905. /* typedef unsigned char u8; */
  3906. typedef unsigned short u16;
  3907. typedef unsigned long u32;
  3908. #define MIN(a,b) ((a)<(b) ? (a) : (b))
  3909. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  3910. # define ALWAYS(X) (1)
  3911. # define NEVER(X) (0)
  3912. #elif !defined(NDEBUG)
  3913. # define ALWAYS(X) ((X)?1:(assert(0),0))
  3914. # define NEVER(X) ((X)?(assert(0),1):0)
  3915. #else
  3916. # define ALWAYS(X) (X)
  3917. # define NEVER(X) (X)
  3918. #endif
  3919. #endif /* SQLITE_AMALGAMATION */
  3920. /*
  3921. ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
  3922. **
  3923. ** In some ways it would be better to obtain these values from system
  3924. ** header files. But, the dependency is undesirable and (a) these
  3925. ** have been stable for decades, (b) the values are part of POSIX and
  3926. ** are also made explicit in [man stat], and (c) are part of the
  3927. ** file format for zip archives.
  3928. */
  3929. #ifndef S_IFDIR
  3930. # define S_IFDIR 0040000
  3931. #endif
  3932. #ifndef S_IFREG
  3933. # define S_IFREG 0100000
  3934. #endif
  3935. #ifndef S_IFLNK
  3936. # define S_IFLNK 0120000
  3937. #endif
  3938. static const char ZIPFILE_SCHEMA[] =
  3939. "CREATE TABLE y("
  3940. "name PRIMARY KEY," /* 0: Name of file in zip archive */
  3941. "mode," /* 1: POSIX mode for file */
  3942. "mtime," /* 2: Last modification time (secs since 1970)*/
  3943. "sz," /* 3: Size of object */
  3944. "rawdata," /* 4: Raw data */
  3945. "data," /* 5: Uncompressed data */
  3946. "method," /* 6: Compression method (integer) */
  3947. "z HIDDEN" /* 7: Name of zip file */
  3948. ") WITHOUT ROWID;";
  3949. #define ZIPFILE_F_COLUMN_IDX 7 /* Index of column "file" in the above */
  3950. #define ZIPFILE_BUFFER_SIZE (64*1024)
  3951. /*
  3952. ** Magic numbers used to read and write zip files.
  3953. **
  3954. ** ZIPFILE_NEWENTRY_MADEBY:
  3955. ** Use this value for the "version-made-by" field in new zip file
  3956. ** entries. The upper byte indicates "unix", and the lower byte
  3957. ** indicates that the zip file matches pkzip specification 3.0.
  3958. ** This is what info-zip seems to do.
  3959. **
  3960. ** ZIPFILE_NEWENTRY_REQUIRED:
  3961. ** Value for "version-required-to-extract" field of new entries.
  3962. ** Version 2.0 is required to support folders and deflate compression.
  3963. **
  3964. ** ZIPFILE_NEWENTRY_FLAGS:
  3965. ** Value for "general-purpose-bit-flags" field of new entries. Bit
  3966. ** 11 means "utf-8 filename and comment".
  3967. **
  3968. ** ZIPFILE_SIGNATURE_CDS:
  3969. ** First 4 bytes of a valid CDS record.
  3970. **
  3971. ** ZIPFILE_SIGNATURE_LFH:
  3972. ** First 4 bytes of a valid LFH record.
  3973. **
  3974. ** ZIPFILE_SIGNATURE_EOCD
  3975. ** First 4 bytes of a valid EOCD record.
  3976. */
  3977. #define ZIPFILE_EXTRA_TIMESTAMP 0x5455
  3978. #define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30)
  3979. #define ZIPFILE_NEWENTRY_REQUIRED 20
  3980. #define ZIPFILE_NEWENTRY_FLAGS 0x800
  3981. #define ZIPFILE_SIGNATURE_CDS 0x02014b50
  3982. #define ZIPFILE_SIGNATURE_LFH 0x04034b50
  3983. #define ZIPFILE_SIGNATURE_EOCD 0x06054b50
  3984. /*
  3985. ** The sizes of the fixed-size part of each of the three main data
  3986. ** structures in a zip archive.
  3987. */
  3988. #define ZIPFILE_LFH_FIXED_SZ 30
  3989. #define ZIPFILE_EOCD_FIXED_SZ 22
  3990. #define ZIPFILE_CDS_FIXED_SZ 46
  3991. /*
  3992. *** 4.3.16 End of central directory record:
  3993. ***
  3994. *** end of central dir signature 4 bytes (0x06054b50)
  3995. *** number of this disk 2 bytes
  3996. *** number of the disk with the
  3997. *** start of the central directory 2 bytes
  3998. *** total number of entries in the
  3999. *** central directory on this disk 2 bytes
  4000. *** total number of entries in
  4001. *** the central directory 2 bytes
  4002. *** size of the central directory 4 bytes
  4003. *** offset of start of central
  4004. *** directory with respect to
  4005. *** the starting disk number 4 bytes
  4006. *** .ZIP file comment length 2 bytes
  4007. *** .ZIP file comment (variable size)
  4008. */
  4009. typedef struct ZipfileEOCD ZipfileEOCD;
  4010. struct ZipfileEOCD {
  4011. u16 iDisk;
  4012. u16 iFirstDisk;
  4013. u16 nEntry;
  4014. u16 nEntryTotal;
  4015. u32 nSize;
  4016. u32 iOffset;
  4017. };
  4018. /*
  4019. *** 4.3.12 Central directory structure:
  4020. ***
  4021. *** ...
  4022. ***
  4023. *** central file header signature 4 bytes (0x02014b50)
  4024. *** version made by 2 bytes
  4025. *** version needed to extract 2 bytes
  4026. *** general purpose bit flag 2 bytes
  4027. *** compression method 2 bytes
  4028. *** last mod file time 2 bytes
  4029. *** last mod file date 2 bytes
  4030. *** crc-32 4 bytes
  4031. *** compressed size 4 bytes
  4032. *** uncompressed size 4 bytes
  4033. *** file name length 2 bytes
  4034. *** extra field length 2 bytes
  4035. *** file comment length 2 bytes
  4036. *** disk number start 2 bytes
  4037. *** internal file attributes 2 bytes
  4038. *** external file attributes 4 bytes
  4039. *** relative offset of local header 4 bytes
  4040. */
  4041. typedef struct ZipfileCDS ZipfileCDS;
  4042. struct ZipfileCDS {
  4043. u16 iVersionMadeBy;
  4044. u16 iVersionExtract;
  4045. u16 flags;
  4046. u16 iCompression;
  4047. u16 mTime;
  4048. u16 mDate;
  4049. u32 crc32;
  4050. u32 szCompressed;
  4051. u32 szUncompressed;
  4052. u16 nFile;
  4053. u16 nExtra;
  4054. u16 nComment;
  4055. u16 iDiskStart;
  4056. u16 iInternalAttr;
  4057. u32 iExternalAttr;
  4058. u32 iOffset;
  4059. char *zFile; /* Filename (sqlite3_malloc()) */
  4060. };
  4061. /*
  4062. *** 4.3.7 Local file header:
  4063. ***
  4064. *** local file header signature 4 bytes (0x04034b50)
  4065. *** version needed to extract 2 bytes
  4066. *** general purpose bit flag 2 bytes
  4067. *** compression method 2 bytes
  4068. *** last mod file time 2 bytes
  4069. *** last mod file date 2 bytes
  4070. *** crc-32 4 bytes
  4071. *** compressed size 4 bytes
  4072. *** uncompressed size 4 bytes
  4073. *** file name length 2 bytes
  4074. *** extra field length 2 bytes
  4075. ***
  4076. */
  4077. typedef struct ZipfileLFH ZipfileLFH;
  4078. struct ZipfileLFH {
  4079. u16 iVersionExtract;
  4080. u16 flags;
  4081. u16 iCompression;
  4082. u16 mTime;
  4083. u16 mDate;
  4084. u32 crc32;
  4085. u32 szCompressed;
  4086. u32 szUncompressed;
  4087. u16 nFile;
  4088. u16 nExtra;
  4089. };
  4090. typedef struct ZipfileEntry ZipfileEntry;
  4091. struct ZipfileEntry {
  4092. ZipfileCDS cds; /* Parsed CDS record */
  4093. u32 mUnixTime; /* Modification time, in UNIX format */
  4094. u8 *aExtra; /* cds.nExtra+cds.nComment bytes of extra data */
  4095. i64 iDataOff; /* Offset to data in file (if aData==0) */
  4096. u8 *aData; /* cds.szCompressed bytes of compressed data */
  4097. ZipfileEntry *pNext; /* Next element in in-memory CDS */
  4098. };
  4099. /*
  4100. ** Cursor type for zipfile tables.
  4101. */
  4102. typedef struct ZipfileCsr ZipfileCsr;
  4103. struct ZipfileCsr {
  4104. sqlite3_vtab_cursor base; /* Base class - must be first */
  4105. i64 iId; /* Cursor ID */
  4106. u8 bEof; /* True when at EOF */
  4107. u8 bNoop; /* If next xNext() call is no-op */
  4108. /* Used outside of write transactions */
  4109. FILE *pFile; /* Zip file */
  4110. i64 iNextOff; /* Offset of next record in central directory */
  4111. ZipfileEOCD eocd; /* Parse of central directory record */
  4112. ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */
  4113. ZipfileEntry *pCurrent; /* Current entry */
  4114. ZipfileCsr *pCsrNext; /* Next cursor on same virtual table */
  4115. };
  4116. typedef struct ZipfileTab ZipfileTab;
  4117. struct ZipfileTab {
  4118. sqlite3_vtab base; /* Base class - must be first */
  4119. char *zFile; /* Zip file this table accesses (may be NULL) */
  4120. sqlite3 *db; /* Host database connection */
  4121. u8 *aBuffer; /* Temporary buffer used for various tasks */
  4122. ZipfileCsr *pCsrList; /* List of cursors */
  4123. i64 iNextCsrid;
  4124. /* The following are used by write transactions only */
  4125. ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
  4126. ZipfileEntry *pLastEntry; /* Last element in pFirstEntry list */
  4127. FILE *pWriteFd; /* File handle open on zip archive */
  4128. i64 szCurrent; /* Current size of zip archive */
  4129. i64 szOrig; /* Size of archive at start of transaction */
  4130. };
  4131. /*
  4132. ** Set the error message contained in context ctx to the results of
  4133. ** vprintf(zFmt, ...).
  4134. */
  4135. static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
  4136. char *zMsg = 0;
  4137. va_list ap;
  4138. va_start(ap, zFmt);
  4139. zMsg = sqlite3_vmprintf(zFmt, ap);
  4140. sqlite3_result_error(ctx, zMsg, -1);
  4141. sqlite3_free(zMsg);
  4142. va_end(ap);
  4143. }
  4144. /*
  4145. ** If string zIn is quoted, dequote it in place. Otherwise, if the string
  4146. ** is not quoted, do nothing.
  4147. */
  4148. static void zipfileDequote(char *zIn){
  4149. char q = zIn[0];
  4150. if( q=='"' || q=='\'' || q=='`' || q=='[' ){
  4151. int iIn = 1;
  4152. int iOut = 0;
  4153. if( q=='[' ) q = ']';
  4154. while( ALWAYS(zIn[iIn]) ){
  4155. char c = zIn[iIn++];
  4156. if( c==q && zIn[iIn++]!=q ) break;
  4157. zIn[iOut++] = c;
  4158. }
  4159. zIn[iOut] = '\0';
  4160. }
  4161. }
  4162. /*
  4163. ** Construct a new ZipfileTab virtual table object.
  4164. **
  4165. ** argv[0] -> module name ("zipfile")
  4166. ** argv[1] -> database name
  4167. ** argv[2] -> table name
  4168. ** argv[...] -> "column name" and other module argument fields.
  4169. */
  4170. static int zipfileConnect(
  4171. sqlite3 *db,
  4172. void *pAux,
  4173. int argc, const char *const*argv,
  4174. sqlite3_vtab **ppVtab,
  4175. char **pzErr
  4176. ){
  4177. int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
  4178. int nFile = 0;
  4179. const char *zFile = 0;
  4180. ZipfileTab *pNew = 0;
  4181. int rc;
  4182. /* If the table name is not "zipfile", require that the argument be
  4183. ** specified. This stops zipfile tables from being created as:
  4184. **
  4185. ** CREATE VIRTUAL TABLE zzz USING zipfile();
  4186. **
  4187. ** It does not prevent:
  4188. **
  4189. ** CREATE VIRTUAL TABLE zipfile USING zipfile();
  4190. */
  4191. assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
  4192. if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
  4193. *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
  4194. return SQLITE_ERROR;
  4195. }
  4196. if( argc>3 ){
  4197. zFile = argv[3];
  4198. nFile = (int)strlen(zFile)+1;
  4199. }
  4200. rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
  4201. if( rc==SQLITE_OK ){
  4202. pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
  4203. if( pNew==0 ) return SQLITE_NOMEM;
  4204. memset(pNew, 0, nByte+nFile);
  4205. pNew->db = db;
  4206. pNew->aBuffer = (u8*)&pNew[1];
  4207. if( zFile ){
  4208. pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
  4209. memcpy(pNew->zFile, zFile, nFile);
  4210. zipfileDequote(pNew->zFile);
  4211. }
  4212. }
  4213. *ppVtab = (sqlite3_vtab*)pNew;
  4214. return rc;
  4215. }
  4216. /*
  4217. ** Free the ZipfileEntry structure indicated by the only argument.
  4218. */
  4219. static void zipfileEntryFree(ZipfileEntry *p){
  4220. if( p ){
  4221. sqlite3_free(p->cds.zFile);
  4222. sqlite3_free(p);
  4223. }
  4224. }
  4225. /*
  4226. ** Release resources that should be freed at the end of a write
  4227. ** transaction.
  4228. */
  4229. static void zipfileCleanupTransaction(ZipfileTab *pTab){
  4230. ZipfileEntry *pEntry;
  4231. ZipfileEntry *pNext;
  4232. if( pTab->pWriteFd ){
  4233. fclose(pTab->pWriteFd);
  4234. pTab->pWriteFd = 0;
  4235. }
  4236. for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
  4237. pNext = pEntry->pNext;
  4238. zipfileEntryFree(pEntry);
  4239. }
  4240. pTab->pFirstEntry = 0;
  4241. pTab->pLastEntry = 0;
  4242. pTab->szCurrent = 0;
  4243. pTab->szOrig = 0;
  4244. }
  4245. /*
  4246. ** This method is the destructor for zipfile vtab objects.
  4247. */
  4248. static int zipfileDisconnect(sqlite3_vtab *pVtab){
  4249. zipfileCleanupTransaction((ZipfileTab*)pVtab);
  4250. sqlite3_free(pVtab);
  4251. return SQLITE_OK;
  4252. }
  4253. /*
  4254. ** Constructor for a new ZipfileCsr object.
  4255. */
  4256. static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
  4257. ZipfileTab *pTab = (ZipfileTab*)p;
  4258. ZipfileCsr *pCsr;
  4259. pCsr = sqlite3_malloc(sizeof(*pCsr));
  4260. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  4261. if( pCsr==0 ){
  4262. return SQLITE_NOMEM;
  4263. }
  4264. memset(pCsr, 0, sizeof(*pCsr));
  4265. pCsr->iId = ++pTab->iNextCsrid;
  4266. pCsr->pCsrNext = pTab->pCsrList;
  4267. pTab->pCsrList = pCsr;
  4268. return SQLITE_OK;
  4269. }
  4270. /*
  4271. ** Reset a cursor back to the state it was in when first returned
  4272. ** by zipfileOpen().
  4273. */
  4274. static void zipfileResetCursor(ZipfileCsr *pCsr){
  4275. ZipfileEntry *p;
  4276. ZipfileEntry *pNext;
  4277. pCsr->bEof = 0;
  4278. if( pCsr->pFile ){
  4279. fclose(pCsr->pFile);
  4280. pCsr->pFile = 0;
  4281. zipfileEntryFree(pCsr->pCurrent);
  4282. pCsr->pCurrent = 0;
  4283. }
  4284. for(p=pCsr->pFreeEntry; p; p=pNext){
  4285. pNext = p->pNext;
  4286. zipfileEntryFree(p);
  4287. }
  4288. }
  4289. /*
  4290. ** Destructor for an ZipfileCsr.
  4291. */
  4292. static int zipfileClose(sqlite3_vtab_cursor *cur){
  4293. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  4294. ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
  4295. ZipfileCsr **pp;
  4296. zipfileResetCursor(pCsr);
  4297. /* Remove this cursor from the ZipfileTab.pCsrList list. */
  4298. for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
  4299. *pp = pCsr->pCsrNext;
  4300. sqlite3_free(pCsr);
  4301. return SQLITE_OK;
  4302. }
  4303. /*
  4304. ** Set the error message for the virtual table associated with cursor
  4305. ** pCsr to the results of vprintf(zFmt, ...).
  4306. */
  4307. static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
  4308. va_list ap;
  4309. va_start(ap, zFmt);
  4310. sqlite3_free(pTab->base.zErrMsg);
  4311. pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
  4312. va_end(ap);
  4313. }
  4314. static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
  4315. va_list ap;
  4316. va_start(ap, zFmt);
  4317. sqlite3_free(pCsr->base.pVtab->zErrMsg);
  4318. pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
  4319. va_end(ap);
  4320. }
  4321. /*
  4322. ** Read nRead bytes of data from offset iOff of file pFile into buffer
  4323. ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
  4324. ** otherwise.
  4325. **
  4326. ** If an error does occur, output variable (*pzErrmsg) may be set to point
  4327. ** to an English language error message. It is the responsibility of the
  4328. ** caller to eventually free this buffer using
  4329. ** sqlite3_free().
  4330. */
  4331. static int zipfileReadData(
  4332. FILE *pFile, /* Read from this file */
  4333. u8 *aRead, /* Read into this buffer */
  4334. int nRead, /* Number of bytes to read */
  4335. i64 iOff, /* Offset to read from */
  4336. char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */
  4337. ){
  4338. size_t n;
  4339. fseek(pFile, (long)iOff, SEEK_SET);
  4340. n = fread(aRead, 1, nRead, pFile);
  4341. if( (int)n!=nRead ){
  4342. *pzErrmsg = sqlite3_mprintf("error in fread()");
  4343. return SQLITE_ERROR;
  4344. }
  4345. return SQLITE_OK;
  4346. }
  4347. static int zipfileAppendData(
  4348. ZipfileTab *pTab,
  4349. const u8 *aWrite,
  4350. int nWrite
  4351. ){
  4352. size_t n;
  4353. fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
  4354. n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
  4355. if( (int)n!=nWrite ){
  4356. pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
  4357. return SQLITE_ERROR;
  4358. }
  4359. pTab->szCurrent += nWrite;
  4360. return SQLITE_OK;
  4361. }
  4362. /*
  4363. ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
  4364. */
  4365. static u16 zipfileGetU16(const u8 *aBuf){
  4366. return (aBuf[1] << 8) + aBuf[0];
  4367. }
  4368. /*
  4369. ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
  4370. */
  4371. static u32 zipfileGetU32(const u8 *aBuf){
  4372. return ((u32)(aBuf[3]) << 24)
  4373. + ((u32)(aBuf[2]) << 16)
  4374. + ((u32)(aBuf[1]) << 8)
  4375. + ((u32)(aBuf[0]) << 0);
  4376. }
  4377. /*
  4378. ** Write a 16-bit little endiate integer into buffer aBuf.
  4379. */
  4380. static void zipfilePutU16(u8 *aBuf, u16 val){
  4381. aBuf[0] = val & 0xFF;
  4382. aBuf[1] = (val>>8) & 0xFF;
  4383. }
  4384. /*
  4385. ** Write a 32-bit little endiate integer into buffer aBuf.
  4386. */
  4387. static void zipfilePutU32(u8 *aBuf, u32 val){
  4388. aBuf[0] = val & 0xFF;
  4389. aBuf[1] = (val>>8) & 0xFF;
  4390. aBuf[2] = (val>>16) & 0xFF;
  4391. aBuf[3] = (val>>24) & 0xFF;
  4392. }
  4393. #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
  4394. #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
  4395. #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
  4396. #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
  4397. /*
  4398. ** Magic numbers used to read CDS records.
  4399. */
  4400. #define ZIPFILE_CDS_NFILE_OFF 28
  4401. #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
  4402. /*
  4403. ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
  4404. ** if the record is not well-formed, or SQLITE_OK otherwise.
  4405. */
  4406. static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
  4407. u8 *aRead = aBuf;
  4408. u32 sig = zipfileRead32(aRead);
  4409. int rc = SQLITE_OK;
  4410. if( sig!=ZIPFILE_SIGNATURE_CDS ){
  4411. rc = SQLITE_ERROR;
  4412. }else{
  4413. pCDS->iVersionMadeBy = zipfileRead16(aRead);
  4414. pCDS->iVersionExtract = zipfileRead16(aRead);
  4415. pCDS->flags = zipfileRead16(aRead);
  4416. pCDS->iCompression = zipfileRead16(aRead);
  4417. pCDS->mTime = zipfileRead16(aRead);
  4418. pCDS->mDate = zipfileRead16(aRead);
  4419. pCDS->crc32 = zipfileRead32(aRead);
  4420. pCDS->szCompressed = zipfileRead32(aRead);
  4421. pCDS->szUncompressed = zipfileRead32(aRead);
  4422. assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
  4423. pCDS->nFile = zipfileRead16(aRead);
  4424. pCDS->nExtra = zipfileRead16(aRead);
  4425. pCDS->nComment = zipfileRead16(aRead);
  4426. pCDS->iDiskStart = zipfileRead16(aRead);
  4427. pCDS->iInternalAttr = zipfileRead16(aRead);
  4428. pCDS->iExternalAttr = zipfileRead32(aRead);
  4429. pCDS->iOffset = zipfileRead32(aRead);
  4430. assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
  4431. }
  4432. return rc;
  4433. }
  4434. /*
  4435. ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
  4436. ** if the record is not well-formed, or SQLITE_OK otherwise.
  4437. */
  4438. static int zipfileReadLFH(
  4439. u8 *aBuffer,
  4440. ZipfileLFH *pLFH
  4441. ){
  4442. u8 *aRead = aBuffer;
  4443. int rc = SQLITE_OK;
  4444. u32 sig = zipfileRead32(aRead);
  4445. if( sig!=ZIPFILE_SIGNATURE_LFH ){
  4446. rc = SQLITE_ERROR;
  4447. }else{
  4448. pLFH->iVersionExtract = zipfileRead16(aRead);
  4449. pLFH->flags = zipfileRead16(aRead);
  4450. pLFH->iCompression = zipfileRead16(aRead);
  4451. pLFH->mTime = zipfileRead16(aRead);
  4452. pLFH->mDate = zipfileRead16(aRead);
  4453. pLFH->crc32 = zipfileRead32(aRead);
  4454. pLFH->szCompressed = zipfileRead32(aRead);
  4455. pLFH->szUncompressed = zipfileRead32(aRead);
  4456. pLFH->nFile = zipfileRead16(aRead);
  4457. pLFH->nExtra = zipfileRead16(aRead);
  4458. }
  4459. return rc;
  4460. }
  4461. /*
  4462. ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
  4463. ** Scan through this buffer to find an "extra-timestamp" field. If one
  4464. ** exists, extract the 32-bit modification-timestamp from it and store
  4465. ** the value in output parameter *pmTime.
  4466. **
  4467. ** Zero is returned if no extra-timestamp record could be found (and so
  4468. ** *pmTime is left unchanged), or non-zero otherwise.
  4469. **
  4470. ** The general format of an extra field is:
  4471. **
  4472. ** Header ID 2 bytes
  4473. ** Data Size 2 bytes
  4474. ** Data N bytes
  4475. */
  4476. static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
  4477. int ret = 0;
  4478. u8 *p = aExtra;
  4479. u8 *pEnd = &aExtra[nExtra];
  4480. while( p<pEnd ){
  4481. u16 id = zipfileRead16(p);
  4482. u16 nByte = zipfileRead16(p);
  4483. switch( id ){
  4484. case ZIPFILE_EXTRA_TIMESTAMP: {
  4485. u8 b = p[0];
  4486. if( b & 0x01 ){ /* 0x01 -> modtime is present */
  4487. *pmTime = zipfileGetU32(&p[1]);
  4488. ret = 1;
  4489. }
  4490. break;
  4491. }
  4492. }
  4493. p += nByte;
  4494. }
  4495. return ret;
  4496. }
  4497. /*
  4498. ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
  4499. ** fields of the CDS structure passed as the only argument to a 32-bit
  4500. ** UNIX seconds-since-the-epoch timestamp. Return the result.
  4501. **
  4502. ** "Standard" MS-DOS time format:
  4503. **
  4504. ** File modification time:
  4505. ** Bits 00-04: seconds divided by 2
  4506. ** Bits 05-10: minute
  4507. ** Bits 11-15: hour
  4508. ** File modification date:
  4509. ** Bits 00-04: day
  4510. ** Bits 05-08: month (1-12)
  4511. ** Bits 09-15: years from 1980
  4512. **
  4513. ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
  4514. */
  4515. static u32 zipfileMtime(ZipfileCDS *pCDS){
  4516. int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
  4517. int M = ((pCDS->mDate >> 5) & 0x0F);
  4518. int D = (pCDS->mDate & 0x1F);
  4519. int B = -13;
  4520. int sec = (pCDS->mTime & 0x1F)*2;
  4521. int min = (pCDS->mTime >> 5) & 0x3F;
  4522. int hr = (pCDS->mTime >> 11) & 0x1F;
  4523. i64 JD;
  4524. /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */
  4525. /* Calculate the JD in seconds for noon on the day in question */
  4526. if( M<3 ){
  4527. Y = Y-1;
  4528. M = M+12;
  4529. }
  4530. JD = (i64)(24*60*60) * (
  4531. (int)(365.25 * (Y + 4716))
  4532. + (int)(30.6001 * (M + 1))
  4533. + D + B - 1524
  4534. );
  4535. /* Correct the JD for the time within the day */
  4536. JD += (hr-12) * 3600 + min * 60 + sec;
  4537. /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */
  4538. return (u32)(JD - (i64)(24405875) * 24*60*6);
  4539. }
  4540. /*
  4541. ** The opposite of zipfileMtime(). This function populates the mTime and
  4542. ** mDate fields of the CDS structure passed as the first argument according
  4543. ** to the UNIX timestamp value passed as the second.
  4544. */
  4545. static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
  4546. /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
  4547. i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
  4548. int A, B, C, D, E;
  4549. int yr, mon, day;
  4550. int hr, min, sec;
  4551. A = (int)((JD - 1867216.25)/36524.25);
  4552. A = (int)(JD + 1 + A - (A/4));
  4553. B = A + 1524;
  4554. C = (int)((B - 122.1)/365.25);
  4555. D = (36525*(C&32767))/100;
  4556. E = (int)((B-D)/30.6001);
  4557. day = B - D - (int)(30.6001*E);
  4558. mon = (E<14 ? E-1 : E-13);
  4559. yr = mon>2 ? C-4716 : C-4715;
  4560. hr = (mUnixTime % (24*60*60)) / (60*60);
  4561. min = (mUnixTime % (60*60)) / 60;
  4562. sec = (mUnixTime % 60);
  4563. if( yr>=1980 ){
  4564. pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
  4565. pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
  4566. }else{
  4567. pCds->mDate = pCds->mTime = 0;
  4568. }
  4569. assert( mUnixTime<315507600
  4570. || mUnixTime==zipfileMtime(pCds)
  4571. || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
  4572. /* || (mUnixTime % 2) */
  4573. );
  4574. }
  4575. /*
  4576. ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
  4577. ** size) containing an entire zip archive image. Or, if aBlob is NULL,
  4578. ** then pFile is a file-handle open on a zip file. In either case, this
  4579. ** function creates a ZipfileEntry object based on the zip archive entry
  4580. ** for which the CDS record is at offset iOff.
  4581. **
  4582. ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
  4583. ** the new object. Otherwise, an SQLite error code is returned and the
  4584. ** final value of (*ppEntry) undefined.
  4585. */
  4586. static int zipfileGetEntry(
  4587. ZipfileTab *pTab, /* Store any error message here */
  4588. const u8 *aBlob, /* Pointer to in-memory file image */
  4589. int nBlob, /* Size of aBlob[] in bytes */
  4590. FILE *pFile, /* If aBlob==0, read from this file */
  4591. i64 iOff, /* Offset of CDS record */
  4592. ZipfileEntry **ppEntry /* OUT: Pointer to new object */
  4593. ){
  4594. u8 *aRead;
  4595. char **pzErr = &pTab->base.zErrMsg;
  4596. int rc = SQLITE_OK;
  4597. if( aBlob==0 ){
  4598. aRead = pTab->aBuffer;
  4599. rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
  4600. }else{
  4601. aRead = (u8*)&aBlob[iOff];
  4602. }
  4603. if( rc==SQLITE_OK ){
  4604. sqlite3_int64 nAlloc;
  4605. ZipfileEntry *pNew;
  4606. int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
  4607. int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
  4608. nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
  4609. nAlloc = sizeof(ZipfileEntry) + nExtra;
  4610. if( aBlob ){
  4611. nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
  4612. }
  4613. pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
  4614. if( pNew==0 ){
  4615. rc = SQLITE_NOMEM;
  4616. }else{
  4617. memset(pNew, 0, sizeof(ZipfileEntry));
  4618. rc = zipfileReadCDS(aRead, &pNew->cds);
  4619. if( rc!=SQLITE_OK ){
  4620. *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
  4621. }else if( aBlob==0 ){
  4622. rc = zipfileReadData(
  4623. pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
  4624. );
  4625. }else{
  4626. aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
  4627. }
  4628. }
  4629. if( rc==SQLITE_OK ){
  4630. u32 *pt = &pNew->mUnixTime;
  4631. pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
  4632. pNew->aExtra = (u8*)&pNew[1];
  4633. memcpy(pNew->aExtra, &aRead[nFile], nExtra);
  4634. if( pNew->cds.zFile==0 ){
  4635. rc = SQLITE_NOMEM;
  4636. }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
  4637. pNew->mUnixTime = zipfileMtime(&pNew->cds);
  4638. }
  4639. }
  4640. if( rc==SQLITE_OK ){
  4641. static const int szFix = ZIPFILE_LFH_FIXED_SZ;
  4642. ZipfileLFH lfh;
  4643. if( pFile ){
  4644. rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
  4645. }else{
  4646. aRead = (u8*)&aBlob[pNew->cds.iOffset];
  4647. }
  4648. rc = zipfileReadLFH(aRead, &lfh);
  4649. if( rc==SQLITE_OK ){
  4650. pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
  4651. pNew->iDataOff += lfh.nFile + lfh.nExtra;
  4652. if( aBlob && pNew->cds.szCompressed ){
  4653. pNew->aData = &pNew->aExtra[nExtra];
  4654. memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
  4655. }
  4656. }else{
  4657. *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
  4658. (int)pNew->cds.iOffset
  4659. );
  4660. }
  4661. }
  4662. if( rc!=SQLITE_OK ){
  4663. zipfileEntryFree(pNew);
  4664. }else{
  4665. *ppEntry = pNew;
  4666. }
  4667. }
  4668. return rc;
  4669. }
  4670. /*
  4671. ** Advance an ZipfileCsr to its next row of output.
  4672. */
  4673. static int zipfileNext(sqlite3_vtab_cursor *cur){
  4674. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  4675. int rc = SQLITE_OK;
  4676. if( pCsr->pFile ){
  4677. i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
  4678. zipfileEntryFree(pCsr->pCurrent);
  4679. pCsr->pCurrent = 0;
  4680. if( pCsr->iNextOff>=iEof ){
  4681. pCsr->bEof = 1;
  4682. }else{
  4683. ZipfileEntry *p = 0;
  4684. ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
  4685. rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
  4686. if( rc==SQLITE_OK ){
  4687. pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
  4688. pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
  4689. }
  4690. pCsr->pCurrent = p;
  4691. }
  4692. }else{
  4693. if( !pCsr->bNoop ){
  4694. pCsr->pCurrent = pCsr->pCurrent->pNext;
  4695. }
  4696. if( pCsr->pCurrent==0 ){
  4697. pCsr->bEof = 1;
  4698. }
  4699. }
  4700. pCsr->bNoop = 0;
  4701. return rc;
  4702. }
  4703. static void zipfileFree(void *p) {
  4704. sqlite3_free(p);
  4705. }
  4706. /*
  4707. ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
  4708. ** size is nOut bytes. This function uncompresses the data and sets the
  4709. ** return value in context pCtx to the result (a blob).
  4710. **
  4711. ** If an error occurs, an error code is left in pCtx instead.
  4712. */
  4713. static void zipfileInflate(
  4714. sqlite3_context *pCtx, /* Store result here */
  4715. const u8 *aIn, /* Compressed data */
  4716. int nIn, /* Size of buffer aIn[] in bytes */
  4717. int nOut /* Expected output size */
  4718. ){
  4719. u8 *aRes = sqlite3_malloc(nOut);
  4720. if( aRes==0 ){
  4721. sqlite3_result_error_nomem(pCtx);
  4722. }else{
  4723. int err;
  4724. z_stream str;
  4725. memset(&str, 0, sizeof(str));
  4726. str.next_in = (Byte*)aIn;
  4727. str.avail_in = nIn;
  4728. str.next_out = (Byte*)aRes;
  4729. str.avail_out = nOut;
  4730. err = inflateInit2(&str, -15);
  4731. if( err!=Z_OK ){
  4732. zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
  4733. }else{
  4734. err = inflate(&str, Z_NO_FLUSH);
  4735. if( err!=Z_STREAM_END ){
  4736. zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
  4737. }else{
  4738. sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
  4739. aRes = 0;
  4740. }
  4741. }
  4742. sqlite3_free(aRes);
  4743. inflateEnd(&str);
  4744. }
  4745. }
  4746. /*
  4747. ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
  4748. ** compresses it and sets (*ppOut) to point to a buffer containing the
  4749. ** compressed data. The caller is responsible for eventually calling
  4750. ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
  4751. ** is set to the size of buffer (*ppOut) in bytes.
  4752. **
  4753. ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
  4754. ** code is returned and an error message left in virtual-table handle
  4755. ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
  4756. ** case.
  4757. */
  4758. static int zipfileDeflate(
  4759. const u8 *aIn, int nIn, /* Input */
  4760. u8 **ppOut, int *pnOut, /* Output */
  4761. char **pzErr /* OUT: Error message */
  4762. ){
  4763. sqlite3_int64 nAlloc = compressBound(nIn);
  4764. u8 *aOut;
  4765. int rc = SQLITE_OK;
  4766. aOut = (u8*)sqlite3_malloc64(nAlloc);
  4767. if( aOut==0 ){
  4768. rc = SQLITE_NOMEM;
  4769. }else{
  4770. int res;
  4771. z_stream str;
  4772. memset(&str, 0, sizeof(str));
  4773. str.next_in = (Bytef*)aIn;
  4774. str.avail_in = nIn;
  4775. str.next_out = aOut;
  4776. str.avail_out = nAlloc;
  4777. deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
  4778. res = deflate(&str, Z_FINISH);
  4779. if( res==Z_STREAM_END ){
  4780. *ppOut = aOut;
  4781. *pnOut = (int)str.total_out;
  4782. }else{
  4783. sqlite3_free(aOut);
  4784. *pzErr = sqlite3_mprintf("zipfile: deflate() error");
  4785. rc = SQLITE_ERROR;
  4786. }
  4787. deflateEnd(&str);
  4788. }
  4789. return rc;
  4790. }
  4791. /*
  4792. ** Return values of columns for the row at which the series_cursor
  4793. ** is currently pointing.
  4794. */
  4795. static int zipfileColumn(
  4796. sqlite3_vtab_cursor *cur, /* The cursor */
  4797. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  4798. int i /* Which column to return */
  4799. ){
  4800. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  4801. ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
  4802. int rc = SQLITE_OK;
  4803. switch( i ){
  4804. case 0: /* name */
  4805. sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
  4806. break;
  4807. case 1: /* mode */
  4808. /* TODO: Whether or not the following is correct surely depends on
  4809. ** the platform on which the archive was created. */
  4810. sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
  4811. break;
  4812. case 2: { /* mtime */
  4813. sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
  4814. break;
  4815. }
  4816. case 3: { /* sz */
  4817. if( sqlite3_vtab_nochange(ctx)==0 ){
  4818. sqlite3_result_int64(ctx, pCDS->szUncompressed);
  4819. }
  4820. break;
  4821. }
  4822. case 4: /* rawdata */
  4823. if( sqlite3_vtab_nochange(ctx) ) break;
  4824. case 5: { /* data */
  4825. if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
  4826. int sz = pCDS->szCompressed;
  4827. int szFinal = pCDS->szUncompressed;
  4828. if( szFinal>0 ){
  4829. u8 *aBuf;
  4830. u8 *aFree = 0;
  4831. if( pCsr->pCurrent->aData ){
  4832. aBuf = pCsr->pCurrent->aData;
  4833. }else{
  4834. aBuf = aFree = sqlite3_malloc64(sz);
  4835. if( aBuf==0 ){
  4836. rc = SQLITE_NOMEM;
  4837. }else{
  4838. FILE *pFile = pCsr->pFile;
  4839. if( pFile==0 ){
  4840. pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
  4841. }
  4842. rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
  4843. &pCsr->base.pVtab->zErrMsg
  4844. );
  4845. }
  4846. }
  4847. if( rc==SQLITE_OK ){
  4848. if( i==5 && pCDS->iCompression ){
  4849. zipfileInflate(ctx, aBuf, sz, szFinal);
  4850. }else{
  4851. sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
  4852. }
  4853. }
  4854. sqlite3_free(aFree);
  4855. }else{
  4856. /* Figure out if this is a directory or a zero-sized file. Consider
  4857. ** it to be a directory either if the mode suggests so, or if
  4858. ** the final character in the name is '/'. */
  4859. u32 mode = pCDS->iExternalAttr >> 16;
  4860. if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
  4861. sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
  4862. }
  4863. }
  4864. }
  4865. break;
  4866. }
  4867. case 6: /* method */
  4868. sqlite3_result_int(ctx, pCDS->iCompression);
  4869. break;
  4870. default: /* z */
  4871. assert( i==7 );
  4872. sqlite3_result_int64(ctx, pCsr->iId);
  4873. break;
  4874. }
  4875. return rc;
  4876. }
  4877. /*
  4878. ** Return TRUE if the cursor is at EOF.
  4879. */
  4880. static int zipfileEof(sqlite3_vtab_cursor *cur){
  4881. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  4882. return pCsr->bEof;
  4883. }
  4884. /*
  4885. ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
  4886. ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
  4887. ** is guaranteed to be a file-handle open on a zip file.
  4888. **
  4889. ** This function attempts to locate the EOCD record within the zip archive
  4890. ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
  4891. ** returned if successful. Otherwise, an SQLite error code is returned and
  4892. ** an English language error message may be left in virtual-table pTab.
  4893. */
  4894. static int zipfileReadEOCD(
  4895. ZipfileTab *pTab, /* Return errors here */
  4896. const u8 *aBlob, /* Pointer to in-memory file image */
  4897. int nBlob, /* Size of aBlob[] in bytes */
  4898. FILE *pFile, /* Read from this file if aBlob==0 */
  4899. ZipfileEOCD *pEOCD /* Object to populate */
  4900. ){
  4901. u8 *aRead = pTab->aBuffer; /* Temporary buffer */
  4902. int nRead; /* Bytes to read from file */
  4903. int rc = SQLITE_OK;
  4904. if( aBlob==0 ){
  4905. i64 iOff; /* Offset to read from */
  4906. i64 szFile; /* Total size of file in bytes */
  4907. fseek(pFile, 0, SEEK_END);
  4908. szFile = (i64)ftell(pFile);
  4909. if( szFile==0 ){
  4910. memset(pEOCD, 0, sizeof(ZipfileEOCD));
  4911. return SQLITE_OK;
  4912. }
  4913. nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
  4914. iOff = szFile - nRead;
  4915. rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
  4916. }else{
  4917. nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
  4918. aRead = (u8*)&aBlob[nBlob-nRead];
  4919. }
  4920. if( rc==SQLITE_OK ){
  4921. int i;
  4922. /* Scan backwards looking for the signature bytes */
  4923. for(i=nRead-20; i>=0; i--){
  4924. if( aRead[i]==0x50 && aRead[i+1]==0x4b
  4925. && aRead[i+2]==0x05 && aRead[i+3]==0x06
  4926. ){
  4927. break;
  4928. }
  4929. }
  4930. if( i<0 ){
  4931. pTab->base.zErrMsg = sqlite3_mprintf(
  4932. "cannot find end of central directory record"
  4933. );
  4934. return SQLITE_ERROR;
  4935. }
  4936. aRead += i+4;
  4937. pEOCD->iDisk = zipfileRead16(aRead);
  4938. pEOCD->iFirstDisk = zipfileRead16(aRead);
  4939. pEOCD->nEntry = zipfileRead16(aRead);
  4940. pEOCD->nEntryTotal = zipfileRead16(aRead);
  4941. pEOCD->nSize = zipfileRead32(aRead);
  4942. pEOCD->iOffset = zipfileRead32(aRead);
  4943. }
  4944. return rc;
  4945. }
  4946. /*
  4947. ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
  4948. ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
  4949. ** to the end of the list. Otherwise, it is added to the list immediately
  4950. ** before pBefore (which is guaranteed to be a part of said list).
  4951. */
  4952. static void zipfileAddEntry(
  4953. ZipfileTab *pTab,
  4954. ZipfileEntry *pBefore,
  4955. ZipfileEntry *pNew
  4956. ){
  4957. assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
  4958. assert( pNew->pNext==0 );
  4959. if( pBefore==0 ){
  4960. if( pTab->pFirstEntry==0 ){
  4961. pTab->pFirstEntry = pTab->pLastEntry = pNew;
  4962. }else{
  4963. assert( pTab->pLastEntry->pNext==0 );
  4964. pTab->pLastEntry->pNext = pNew;
  4965. pTab->pLastEntry = pNew;
  4966. }
  4967. }else{
  4968. ZipfileEntry **pp;
  4969. for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
  4970. pNew->pNext = pBefore;
  4971. *pp = pNew;
  4972. }
  4973. }
  4974. static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
  4975. ZipfileEOCD eocd;
  4976. int rc;
  4977. int i;
  4978. i64 iOff;
  4979. rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
  4980. iOff = eocd.iOffset;
  4981. for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
  4982. ZipfileEntry *pNew = 0;
  4983. rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
  4984. if( rc==SQLITE_OK ){
  4985. zipfileAddEntry(pTab, 0, pNew);
  4986. iOff += ZIPFILE_CDS_FIXED_SZ;
  4987. iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
  4988. }
  4989. }
  4990. return rc;
  4991. }
  4992. /*
  4993. ** xFilter callback.
  4994. */
  4995. static int zipfileFilter(
  4996. sqlite3_vtab_cursor *cur,
  4997. int idxNum, const char *idxStr,
  4998. int argc, sqlite3_value **argv
  4999. ){
  5000. ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
  5001. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  5002. const char *zFile = 0; /* Zip file to scan */
  5003. int rc = SQLITE_OK; /* Return Code */
  5004. int bInMemory = 0; /* True for an in-memory zipfile */
  5005. zipfileResetCursor(pCsr);
  5006. if( pTab->zFile ){
  5007. zFile = pTab->zFile;
  5008. }else if( idxNum==0 ){
  5009. zipfileCursorErr(pCsr, "zipfile() function requires an argument");
  5010. return SQLITE_ERROR;
  5011. }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
  5012. const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
  5013. int nBlob = sqlite3_value_bytes(argv[0]);
  5014. assert( pTab->pFirstEntry==0 );
  5015. rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
  5016. pCsr->pFreeEntry = pTab->pFirstEntry;
  5017. pTab->pFirstEntry = pTab->pLastEntry = 0;
  5018. if( rc!=SQLITE_OK ) return rc;
  5019. bInMemory = 1;
  5020. }else{
  5021. zFile = (const char*)sqlite3_value_text(argv[0]);
  5022. }
  5023. if( 0==pTab->pWriteFd && 0==bInMemory ){
  5024. pCsr->pFile = fopen(zFile, "rb");
  5025. if( pCsr->pFile==0 ){
  5026. zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
  5027. rc = SQLITE_ERROR;
  5028. }else{
  5029. rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
  5030. if( rc==SQLITE_OK ){
  5031. if( pCsr->eocd.nEntry==0 ){
  5032. pCsr->bEof = 1;
  5033. }else{
  5034. pCsr->iNextOff = pCsr->eocd.iOffset;
  5035. rc = zipfileNext(cur);
  5036. }
  5037. }
  5038. }
  5039. }else{
  5040. pCsr->bNoop = 1;
  5041. pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
  5042. rc = zipfileNext(cur);
  5043. }
  5044. return rc;
  5045. }
  5046. /*
  5047. ** xBestIndex callback.
  5048. */
  5049. static int zipfileBestIndex(
  5050. sqlite3_vtab *tab,
  5051. sqlite3_index_info *pIdxInfo
  5052. ){
  5053. int i;
  5054. int idx = -1;
  5055. int unusable = 0;
  5056. for(i=0; i<pIdxInfo->nConstraint; i++){
  5057. const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
  5058. if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
  5059. if( pCons->usable==0 ){
  5060. unusable = 1;
  5061. }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  5062. idx = i;
  5063. }
  5064. }
  5065. if( idx>=0 ){
  5066. pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
  5067. pIdxInfo->aConstraintUsage[idx].omit = 1;
  5068. pIdxInfo->estimatedCost = 1000.0;
  5069. pIdxInfo->idxNum = 1;
  5070. }else if( unusable ){
  5071. return SQLITE_CONSTRAINT;
  5072. }
  5073. return SQLITE_OK;
  5074. }
  5075. static ZipfileEntry *zipfileNewEntry(const char *zPath){
  5076. ZipfileEntry *pNew;
  5077. pNew = sqlite3_malloc(sizeof(ZipfileEntry));
  5078. if( pNew ){
  5079. memset(pNew, 0, sizeof(ZipfileEntry));
  5080. pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
  5081. if( pNew->cds.zFile==0 ){
  5082. sqlite3_free(pNew);
  5083. pNew = 0;
  5084. }
  5085. }
  5086. return pNew;
  5087. }
  5088. static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
  5089. ZipfileCDS *pCds = &pEntry->cds;
  5090. u8 *a = aBuf;
  5091. pCds->nExtra = 9;
  5092. /* Write the LFH itself */
  5093. zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
  5094. zipfileWrite16(a, pCds->iVersionExtract);
  5095. zipfileWrite16(a, pCds->flags);
  5096. zipfileWrite16(a, pCds->iCompression);
  5097. zipfileWrite16(a, pCds->mTime);
  5098. zipfileWrite16(a, pCds->mDate);
  5099. zipfileWrite32(a, pCds->crc32);
  5100. zipfileWrite32(a, pCds->szCompressed);
  5101. zipfileWrite32(a, pCds->szUncompressed);
  5102. zipfileWrite16(a, (u16)pCds->nFile);
  5103. zipfileWrite16(a, pCds->nExtra);
  5104. assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
  5105. /* Add the file name */
  5106. memcpy(a, pCds->zFile, (int)pCds->nFile);
  5107. a += (int)pCds->nFile;
  5108. /* The "extra" data */
  5109. zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
  5110. zipfileWrite16(a, 5);
  5111. *a++ = 0x01;
  5112. zipfileWrite32(a, pEntry->mUnixTime);
  5113. return a-aBuf;
  5114. }
  5115. static int zipfileAppendEntry(
  5116. ZipfileTab *pTab,
  5117. ZipfileEntry *pEntry,
  5118. const u8 *pData,
  5119. int nData
  5120. ){
  5121. u8 *aBuf = pTab->aBuffer;
  5122. int nBuf;
  5123. int rc;
  5124. nBuf = zipfileSerializeLFH(pEntry, aBuf);
  5125. rc = zipfileAppendData(pTab, aBuf, nBuf);
  5126. if( rc==SQLITE_OK ){
  5127. pEntry->iDataOff = pTab->szCurrent;
  5128. rc = zipfileAppendData(pTab, pData, nData);
  5129. }
  5130. return rc;
  5131. }
  5132. static int zipfileGetMode(
  5133. sqlite3_value *pVal,
  5134. int bIsDir, /* If true, default to directory */
  5135. u32 *pMode, /* OUT: Mode value */
  5136. char **pzErr /* OUT: Error message */
  5137. ){
  5138. const char *z = (const char*)sqlite3_value_text(pVal);
  5139. u32 mode = 0;
  5140. if( z==0 ){
  5141. mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
  5142. }else if( z[0]>='0' && z[0]<='9' ){
  5143. mode = (unsigned int)sqlite3_value_int(pVal);
  5144. }else{
  5145. const char zTemplate[11] = "-rwxrwxrwx";
  5146. int i;
  5147. if( strlen(z)!=10 ) goto parse_error;
  5148. switch( z[0] ){
  5149. case '-': mode |= S_IFREG; break;
  5150. case 'd': mode |= S_IFDIR; break;
  5151. case 'l': mode |= S_IFLNK; break;
  5152. default: goto parse_error;
  5153. }
  5154. for(i=1; i<10; i++){
  5155. if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
  5156. else if( z[i]!='-' ) goto parse_error;
  5157. }
  5158. }
  5159. if( ((mode & S_IFDIR)==0)==bIsDir ){
  5160. /* The "mode" attribute is a directory, but data has been specified.
  5161. ** Or vice-versa - no data but "mode" is a file or symlink. */
  5162. *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
  5163. return SQLITE_CONSTRAINT;
  5164. }
  5165. *pMode = mode;
  5166. return SQLITE_OK;
  5167. parse_error:
  5168. *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
  5169. return SQLITE_ERROR;
  5170. }
  5171. /*
  5172. ** Both (const char*) arguments point to nul-terminated strings. Argument
  5173. ** nB is the value of strlen(zB). This function returns 0 if the strings are
  5174. ** identical, ignoring any trailing '/' character in either path. */
  5175. static int zipfileComparePath(const char *zA, const char *zB, int nB){
  5176. int nA = (int)strlen(zA);
  5177. if( zA[nA-1]=='/' ) nA--;
  5178. if( zB[nB-1]=='/' ) nB--;
  5179. if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
  5180. return 1;
  5181. }
  5182. static int zipfileBegin(sqlite3_vtab *pVtab){
  5183. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  5184. int rc = SQLITE_OK;
  5185. assert( pTab->pWriteFd==0 );
  5186. /* Open a write fd on the file. Also load the entire central directory
  5187. ** structure into memory. During the transaction any new file data is
  5188. ** appended to the archive file, but the central directory is accumulated
  5189. ** in main-memory until the transaction is committed. */
  5190. pTab->pWriteFd = fopen(pTab->zFile, "ab+");
  5191. if( pTab->pWriteFd==0 ){
  5192. pTab->base.zErrMsg = sqlite3_mprintf(
  5193. "zipfile: failed to open file %s for writing", pTab->zFile
  5194. );
  5195. rc = SQLITE_ERROR;
  5196. }else{
  5197. fseek(pTab->pWriteFd, 0, SEEK_END);
  5198. pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
  5199. rc = zipfileLoadDirectory(pTab, 0, 0);
  5200. }
  5201. if( rc!=SQLITE_OK ){
  5202. zipfileCleanupTransaction(pTab);
  5203. }
  5204. return rc;
  5205. }
  5206. /*
  5207. ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
  5208. ** time(2)).
  5209. */
  5210. static u32 zipfileTime(void){
  5211. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  5212. u32 ret;
  5213. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  5214. i64 ms;
  5215. pVfs->xCurrentTimeInt64(pVfs, &ms);
  5216. ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
  5217. }else{
  5218. double day;
  5219. pVfs->xCurrentTime(pVfs, &day);
  5220. ret = (u32)((day - 2440587.5) * 86400);
  5221. }
  5222. return ret;
  5223. }
  5224. /*
  5225. ** Return a 32-bit timestamp in UNIX epoch format.
  5226. **
  5227. ** If the value passed as the only argument is either NULL or an SQL NULL,
  5228. ** return the current time. Otherwise, return the value stored in (*pVal)
  5229. ** cast to a 32-bit unsigned integer.
  5230. */
  5231. static u32 zipfileGetTime(sqlite3_value *pVal){
  5232. if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
  5233. return zipfileTime();
  5234. }
  5235. return (u32)sqlite3_value_int64(pVal);
  5236. }
  5237. /*
  5238. ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
  5239. ** linked list. Remove it from the list and free the object.
  5240. */
  5241. static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
  5242. if( pOld ){
  5243. ZipfileEntry **pp;
  5244. for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
  5245. *pp = (*pp)->pNext;
  5246. zipfileEntryFree(pOld);
  5247. }
  5248. }
  5249. /*
  5250. ** xUpdate method.
  5251. */
  5252. static int zipfileUpdate(
  5253. sqlite3_vtab *pVtab,
  5254. int nVal,
  5255. sqlite3_value **apVal,
  5256. sqlite_int64 *pRowid
  5257. ){
  5258. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  5259. int rc = SQLITE_OK; /* Return Code */
  5260. ZipfileEntry *pNew = 0; /* New in-memory CDS entry */
  5261. u32 mode = 0; /* Mode for new entry */
  5262. u32 mTime = 0; /* Modification time for new entry */
  5263. i64 sz = 0; /* Uncompressed size */
  5264. const char *zPath = 0; /* Path for new entry */
  5265. int nPath = 0; /* strlen(zPath) */
  5266. const u8 *pData = 0; /* Pointer to buffer containing content */
  5267. int nData = 0; /* Size of pData buffer in bytes */
  5268. int iMethod = 0; /* Compression method for new entry */
  5269. u8 *pFree = 0; /* Free this */
  5270. char *zFree = 0; /* Also free this */
  5271. ZipfileEntry *pOld = 0;
  5272. ZipfileEntry *pOld2 = 0;
  5273. int bUpdate = 0; /* True for an update that modifies "name" */
  5274. int bIsDir = 0;
  5275. u32 iCrc32 = 0;
  5276. if( pTab->pWriteFd==0 ){
  5277. rc = zipfileBegin(pVtab);
  5278. if( rc!=SQLITE_OK ) return rc;
  5279. }
  5280. /* If this is a DELETE or UPDATE, find the archive entry to delete. */
  5281. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  5282. const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
  5283. int nDelete = (int)strlen(zDelete);
  5284. if( nVal>1 ){
  5285. const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
  5286. if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
  5287. bUpdate = 1;
  5288. }
  5289. }
  5290. for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
  5291. if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
  5292. break;
  5293. }
  5294. assert( pOld->pNext );
  5295. }
  5296. }
  5297. if( nVal>1 ){
  5298. /* Check that "sz" and "rawdata" are both NULL: */
  5299. if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
  5300. zipfileTableErr(pTab, "sz must be NULL");
  5301. rc = SQLITE_CONSTRAINT;
  5302. }
  5303. if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
  5304. zipfileTableErr(pTab, "rawdata must be NULL");
  5305. rc = SQLITE_CONSTRAINT;
  5306. }
  5307. if( rc==SQLITE_OK ){
  5308. if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
  5309. /* data=NULL. A directory */
  5310. bIsDir = 1;
  5311. }else{
  5312. /* Value specified for "data", and possibly "method". This must be
  5313. ** a regular file or a symlink. */
  5314. const u8 *aIn = sqlite3_value_blob(apVal[7]);
  5315. int nIn = sqlite3_value_bytes(apVal[7]);
  5316. int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
  5317. iMethod = sqlite3_value_int(apVal[8]);
  5318. sz = nIn;
  5319. pData = aIn;
  5320. nData = nIn;
  5321. if( iMethod!=0 && iMethod!=8 ){
  5322. zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
  5323. rc = SQLITE_CONSTRAINT;
  5324. }else{
  5325. if( bAuto || iMethod ){
  5326. int nCmp;
  5327. rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
  5328. if( rc==SQLITE_OK ){
  5329. if( iMethod || nCmp<nIn ){
  5330. iMethod = 8;
  5331. pData = pFree;
  5332. nData = nCmp;
  5333. }
  5334. }
  5335. }
  5336. iCrc32 = crc32(0, aIn, nIn);
  5337. }
  5338. }
  5339. }
  5340. if( rc==SQLITE_OK ){
  5341. rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
  5342. }
  5343. if( rc==SQLITE_OK ){
  5344. zPath = (const char*)sqlite3_value_text(apVal[2]);
  5345. nPath = (int)strlen(zPath);
  5346. mTime = zipfileGetTime(apVal[4]);
  5347. }
  5348. if( rc==SQLITE_OK && bIsDir ){
  5349. /* For a directory, check that the last character in the path is a
  5350. ** '/'. This appears to be required for compatibility with info-zip
  5351. ** (the unzip command on unix). It does not create directories
  5352. ** otherwise. */
  5353. if( zPath[nPath-1]!='/' ){
  5354. zFree = sqlite3_mprintf("%s/", zPath);
  5355. if( zFree==0 ){ rc = SQLITE_NOMEM; }
  5356. zPath = (const char*)zFree;
  5357. nPath++;
  5358. }
  5359. }
  5360. /* Check that we're not inserting a duplicate entry -OR- updating an
  5361. ** entry with a path, thereby making it into a duplicate. */
  5362. if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
  5363. ZipfileEntry *p;
  5364. for(p=pTab->pFirstEntry; p; p=p->pNext){
  5365. if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
  5366. switch( sqlite3_vtab_on_conflict(pTab->db) ){
  5367. case SQLITE_IGNORE: {
  5368. goto zipfile_update_done;
  5369. }
  5370. case SQLITE_REPLACE: {
  5371. pOld2 = p;
  5372. break;
  5373. }
  5374. default: {
  5375. zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
  5376. rc = SQLITE_CONSTRAINT;
  5377. break;
  5378. }
  5379. }
  5380. break;
  5381. }
  5382. }
  5383. }
  5384. if( rc==SQLITE_OK ){
  5385. /* Create the new CDS record. */
  5386. pNew = zipfileNewEntry(zPath);
  5387. if( pNew==0 ){
  5388. rc = SQLITE_NOMEM;
  5389. }else{
  5390. pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
  5391. pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
  5392. pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
  5393. pNew->cds.iCompression = (u16)iMethod;
  5394. zipfileMtimeToDos(&pNew->cds, mTime);
  5395. pNew->cds.crc32 = iCrc32;
  5396. pNew->cds.szCompressed = nData;
  5397. pNew->cds.szUncompressed = (u32)sz;
  5398. pNew->cds.iExternalAttr = (mode<<16);
  5399. pNew->cds.iOffset = (u32)pTab->szCurrent;
  5400. pNew->cds.nFile = (u16)nPath;
  5401. pNew->mUnixTime = (u32)mTime;
  5402. rc = zipfileAppendEntry(pTab, pNew, pData, nData);
  5403. zipfileAddEntry(pTab, pOld, pNew);
  5404. }
  5405. }
  5406. }
  5407. if( rc==SQLITE_OK && (pOld || pOld2) ){
  5408. ZipfileCsr *pCsr;
  5409. for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
  5410. if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
  5411. pCsr->pCurrent = pCsr->pCurrent->pNext;
  5412. pCsr->bNoop = 1;
  5413. }
  5414. }
  5415. zipfileRemoveEntryFromList(pTab, pOld);
  5416. zipfileRemoveEntryFromList(pTab, pOld2);
  5417. }
  5418. zipfile_update_done:
  5419. sqlite3_free(pFree);
  5420. sqlite3_free(zFree);
  5421. return rc;
  5422. }
  5423. static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
  5424. u8 *a = aBuf;
  5425. zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
  5426. zipfileWrite16(a, p->iDisk);
  5427. zipfileWrite16(a, p->iFirstDisk);
  5428. zipfileWrite16(a, p->nEntry);
  5429. zipfileWrite16(a, p->nEntryTotal);
  5430. zipfileWrite32(a, p->nSize);
  5431. zipfileWrite32(a, p->iOffset);
  5432. zipfileWrite16(a, 0); /* Size of trailing comment in bytes*/
  5433. return a-aBuf;
  5434. }
  5435. static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
  5436. int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
  5437. assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
  5438. return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
  5439. }
  5440. /*
  5441. ** Serialize the CDS structure into buffer aBuf[]. Return the number
  5442. ** of bytes written.
  5443. */
  5444. static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
  5445. u8 *a = aBuf;
  5446. ZipfileCDS *pCDS = &pEntry->cds;
  5447. if( pEntry->aExtra==0 ){
  5448. pCDS->nExtra = 9;
  5449. }
  5450. zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
  5451. zipfileWrite16(a, pCDS->iVersionMadeBy);
  5452. zipfileWrite16(a, pCDS->iVersionExtract);
  5453. zipfileWrite16(a, pCDS->flags);
  5454. zipfileWrite16(a, pCDS->iCompression);
  5455. zipfileWrite16(a, pCDS->mTime);
  5456. zipfileWrite16(a, pCDS->mDate);
  5457. zipfileWrite32(a, pCDS->crc32);
  5458. zipfileWrite32(a, pCDS->szCompressed);
  5459. zipfileWrite32(a, pCDS->szUncompressed);
  5460. assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
  5461. zipfileWrite16(a, pCDS->nFile);
  5462. zipfileWrite16(a, pCDS->nExtra);
  5463. zipfileWrite16(a, pCDS->nComment);
  5464. zipfileWrite16(a, pCDS->iDiskStart);
  5465. zipfileWrite16(a, pCDS->iInternalAttr);
  5466. zipfileWrite32(a, pCDS->iExternalAttr);
  5467. zipfileWrite32(a, pCDS->iOffset);
  5468. memcpy(a, pCDS->zFile, pCDS->nFile);
  5469. a += pCDS->nFile;
  5470. if( pEntry->aExtra ){
  5471. int n = (int)pCDS->nExtra + (int)pCDS->nComment;
  5472. memcpy(a, pEntry->aExtra, n);
  5473. a += n;
  5474. }else{
  5475. assert( pCDS->nExtra==9 );
  5476. zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
  5477. zipfileWrite16(a, 5);
  5478. *a++ = 0x01;
  5479. zipfileWrite32(a, pEntry->mUnixTime);
  5480. }
  5481. return a-aBuf;
  5482. }
  5483. static int zipfileCommit(sqlite3_vtab *pVtab){
  5484. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  5485. int rc = SQLITE_OK;
  5486. if( pTab->pWriteFd ){
  5487. i64 iOffset = pTab->szCurrent;
  5488. ZipfileEntry *p;
  5489. ZipfileEOCD eocd;
  5490. int nEntry = 0;
  5491. /* Write out all entries */
  5492. for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
  5493. int n = zipfileSerializeCDS(p, pTab->aBuffer);
  5494. rc = zipfileAppendData(pTab, pTab->aBuffer, n);
  5495. nEntry++;
  5496. }
  5497. /* Write out the EOCD record */
  5498. eocd.iDisk = 0;
  5499. eocd.iFirstDisk = 0;
  5500. eocd.nEntry = (u16)nEntry;
  5501. eocd.nEntryTotal = (u16)nEntry;
  5502. eocd.nSize = (u32)(pTab->szCurrent - iOffset);
  5503. eocd.iOffset = (u32)iOffset;
  5504. rc = zipfileAppendEOCD(pTab, &eocd);
  5505. zipfileCleanupTransaction(pTab);
  5506. }
  5507. return rc;
  5508. }
  5509. static int zipfileRollback(sqlite3_vtab *pVtab){
  5510. return zipfileCommit(pVtab);
  5511. }
  5512. static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
  5513. ZipfileCsr *pCsr;
  5514. for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
  5515. if( iId==pCsr->iId ) break;
  5516. }
  5517. return pCsr;
  5518. }
  5519. static void zipfileFunctionCds(
  5520. sqlite3_context *context,
  5521. int argc,
  5522. sqlite3_value **argv
  5523. ){
  5524. ZipfileCsr *pCsr;
  5525. ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
  5526. assert( argc>0 );
  5527. pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
  5528. if( pCsr ){
  5529. ZipfileCDS *p = &pCsr->pCurrent->cds;
  5530. char *zRes = sqlite3_mprintf("{"
  5531. "\"version-made-by\" : %u, "
  5532. "\"version-to-extract\" : %u, "
  5533. "\"flags\" : %u, "
  5534. "\"compression\" : %u, "
  5535. "\"time\" : %u, "
  5536. "\"date\" : %u, "
  5537. "\"crc32\" : %u, "
  5538. "\"compressed-size\" : %u, "
  5539. "\"uncompressed-size\" : %u, "
  5540. "\"file-name-length\" : %u, "
  5541. "\"extra-field-length\" : %u, "
  5542. "\"file-comment-length\" : %u, "
  5543. "\"disk-number-start\" : %u, "
  5544. "\"internal-attr\" : %u, "
  5545. "\"external-attr\" : %u, "
  5546. "\"offset\" : %u }",
  5547. (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
  5548. (u32)p->flags, (u32)p->iCompression,
  5549. (u32)p->mTime, (u32)p->mDate,
  5550. (u32)p->crc32, (u32)p->szCompressed,
  5551. (u32)p->szUncompressed, (u32)p->nFile,
  5552. (u32)p->nExtra, (u32)p->nComment,
  5553. (u32)p->iDiskStart, (u32)p->iInternalAttr,
  5554. (u32)p->iExternalAttr, (u32)p->iOffset
  5555. );
  5556. if( zRes==0 ){
  5557. sqlite3_result_error_nomem(context);
  5558. }else{
  5559. sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
  5560. sqlite3_free(zRes);
  5561. }
  5562. }
  5563. }
  5564. /*
  5565. ** xFindFunction method.
  5566. */
  5567. static int zipfileFindFunction(
  5568. sqlite3_vtab *pVtab, /* Virtual table handle */
  5569. int nArg, /* Number of SQL function arguments */
  5570. const char *zName, /* Name of SQL function */
  5571. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  5572. void **ppArg /* OUT: User data for *pxFunc */
  5573. ){
  5574. if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
  5575. *pxFunc = zipfileFunctionCds;
  5576. *ppArg = (void*)pVtab;
  5577. return 1;
  5578. }
  5579. return 0;
  5580. }
  5581. typedef struct ZipfileBuffer ZipfileBuffer;
  5582. struct ZipfileBuffer {
  5583. u8 *a; /* Pointer to buffer */
  5584. int n; /* Size of buffer in bytes */
  5585. int nAlloc; /* Byte allocated at a[] */
  5586. };
  5587. typedef struct ZipfileCtx ZipfileCtx;
  5588. struct ZipfileCtx {
  5589. int nEntry;
  5590. ZipfileBuffer body;
  5591. ZipfileBuffer cds;
  5592. };
  5593. static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
  5594. if( pBuf->n+nByte>pBuf->nAlloc ){
  5595. u8 *aNew;
  5596. sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
  5597. int nReq = pBuf->n + nByte;
  5598. while( nNew<nReq ) nNew = nNew*2;
  5599. aNew = sqlite3_realloc64(pBuf->a, nNew);
  5600. if( aNew==0 ) return SQLITE_NOMEM;
  5601. pBuf->a = aNew;
  5602. pBuf->nAlloc = (int)nNew;
  5603. }
  5604. return SQLITE_OK;
  5605. }
  5606. /*
  5607. ** xStep() callback for the zipfile() aggregate. This can be called in
  5608. ** any of the following ways:
  5609. **
  5610. ** SELECT zipfile(name,data) ...
  5611. ** SELECT zipfile(name,mode,mtime,data) ...
  5612. ** SELECT zipfile(name,mode,mtime,data,method) ...
  5613. */
  5614. void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
  5615. ZipfileCtx *p; /* Aggregate function context */
  5616. ZipfileEntry e; /* New entry to add to zip archive */
  5617. sqlite3_value *pName = 0;
  5618. sqlite3_value *pMode = 0;
  5619. sqlite3_value *pMtime = 0;
  5620. sqlite3_value *pData = 0;
  5621. sqlite3_value *pMethod = 0;
  5622. int bIsDir = 0;
  5623. u32 mode;
  5624. int rc = SQLITE_OK;
  5625. char *zErr = 0;
  5626. int iMethod = -1; /* Compression method to use (0 or 8) */
  5627. const u8 *aData = 0; /* Possibly compressed data for new entry */
  5628. int nData = 0; /* Size of aData[] in bytes */
  5629. int szUncompressed = 0; /* Size of data before compression */
  5630. u8 *aFree = 0; /* Free this before returning */
  5631. u32 iCrc32 = 0; /* crc32 of uncompressed data */
  5632. char *zName = 0; /* Path (name) of new entry */
  5633. int nName = 0; /* Size of zName in bytes */
  5634. char *zFree = 0; /* Free this before returning */
  5635. int nByte;
  5636. memset(&e, 0, sizeof(e));
  5637. p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
  5638. if( p==0 ) return;
  5639. /* Martial the arguments into stack variables */
  5640. if( nVal!=2 && nVal!=4 && nVal!=5 ){
  5641. zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
  5642. rc = SQLITE_ERROR;
  5643. goto zipfile_step_out;
  5644. }
  5645. pName = apVal[0];
  5646. if( nVal==2 ){
  5647. pData = apVal[1];
  5648. }else{
  5649. pMode = apVal[1];
  5650. pMtime = apVal[2];
  5651. pData = apVal[3];
  5652. if( nVal==5 ){
  5653. pMethod = apVal[4];
  5654. }
  5655. }
  5656. /* Check that the 'name' parameter looks ok. */
  5657. zName = (char*)sqlite3_value_text(pName);
  5658. nName = sqlite3_value_bytes(pName);
  5659. if( zName==0 ){
  5660. zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
  5661. rc = SQLITE_ERROR;
  5662. goto zipfile_step_out;
  5663. }
  5664. /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
  5665. ** deflate compression) or NULL (choose automatically). */
  5666. if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
  5667. iMethod = (int)sqlite3_value_int64(pMethod);
  5668. if( iMethod!=0 && iMethod!=8 ){
  5669. zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
  5670. rc = SQLITE_ERROR;
  5671. goto zipfile_step_out;
  5672. }
  5673. }
  5674. /* Now inspect the data. If this is NULL, then the new entry must be a
  5675. ** directory. Otherwise, figure out whether or not the data should
  5676. ** be deflated or simply stored in the zip archive. */
  5677. if( sqlite3_value_type(pData)==SQLITE_NULL ){
  5678. bIsDir = 1;
  5679. iMethod = 0;
  5680. }else{
  5681. aData = sqlite3_value_blob(pData);
  5682. szUncompressed = nData = sqlite3_value_bytes(pData);
  5683. iCrc32 = crc32(0, aData, nData);
  5684. if( iMethod<0 || iMethod==8 ){
  5685. int nOut = 0;
  5686. rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
  5687. if( rc!=SQLITE_OK ){
  5688. goto zipfile_step_out;
  5689. }
  5690. if( iMethod==8 || nOut<nData ){
  5691. aData = aFree;
  5692. nData = nOut;
  5693. iMethod = 8;
  5694. }else{
  5695. iMethod = 0;
  5696. }
  5697. }
  5698. }
  5699. /* Decode the "mode" argument. */
  5700. rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
  5701. if( rc ) goto zipfile_step_out;
  5702. /* Decode the "mtime" argument. */
  5703. e.mUnixTime = zipfileGetTime(pMtime);
  5704. /* If this is a directory entry, ensure that there is exactly one '/'
  5705. ** at the end of the path. Or, if this is not a directory and the path
  5706. ** ends in '/' it is an error. */
  5707. if( bIsDir==0 ){
  5708. if( zName[nName-1]=='/' ){
  5709. zErr = sqlite3_mprintf("non-directory name must not end with /");
  5710. rc = SQLITE_ERROR;
  5711. goto zipfile_step_out;
  5712. }
  5713. }else{
  5714. if( zName[nName-1]!='/' ){
  5715. zName = zFree = sqlite3_mprintf("%s/", zName);
  5716. nName++;
  5717. if( zName==0 ){
  5718. rc = SQLITE_NOMEM;
  5719. goto zipfile_step_out;
  5720. }
  5721. }else{
  5722. while( nName>1 && zName[nName-2]=='/' ) nName--;
  5723. }
  5724. }
  5725. /* Assemble the ZipfileEntry object for the new zip archive entry */
  5726. e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
  5727. e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
  5728. e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
  5729. e.cds.iCompression = (u16)iMethod;
  5730. zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
  5731. e.cds.crc32 = iCrc32;
  5732. e.cds.szCompressed = nData;
  5733. e.cds.szUncompressed = szUncompressed;
  5734. e.cds.iExternalAttr = (mode<<16);
  5735. e.cds.iOffset = p->body.n;
  5736. e.cds.nFile = (u16)nName;
  5737. e.cds.zFile = zName;
  5738. /* Append the LFH to the body of the new archive */
  5739. nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
  5740. if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
  5741. p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
  5742. /* Append the data to the body of the new archive */
  5743. if( nData>0 ){
  5744. if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
  5745. memcpy(&p->body.a[p->body.n], aData, nData);
  5746. p->body.n += nData;
  5747. }
  5748. /* Append the CDS record to the directory of the new archive */
  5749. nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
  5750. if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
  5751. p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
  5752. /* Increment the count of entries in the archive */
  5753. p->nEntry++;
  5754. zipfile_step_out:
  5755. sqlite3_free(aFree);
  5756. sqlite3_free(zFree);
  5757. if( rc ){
  5758. if( zErr ){
  5759. sqlite3_result_error(pCtx, zErr, -1);
  5760. }else{
  5761. sqlite3_result_error_code(pCtx, rc);
  5762. }
  5763. }
  5764. sqlite3_free(zErr);
  5765. }
  5766. /*
  5767. ** xFinalize() callback for zipfile aggregate function.
  5768. */
  5769. void zipfileFinal(sqlite3_context *pCtx){
  5770. ZipfileCtx *p;
  5771. ZipfileEOCD eocd;
  5772. sqlite3_int64 nZip;
  5773. u8 *aZip;
  5774. p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
  5775. if( p==0 ) return;
  5776. if( p->nEntry>0 ){
  5777. memset(&eocd, 0, sizeof(eocd));
  5778. eocd.nEntry = (u16)p->nEntry;
  5779. eocd.nEntryTotal = (u16)p->nEntry;
  5780. eocd.nSize = p->cds.n;
  5781. eocd.iOffset = p->body.n;
  5782. nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
  5783. aZip = (u8*)sqlite3_malloc64(nZip);
  5784. if( aZip==0 ){
  5785. sqlite3_result_error_nomem(pCtx);
  5786. }else{
  5787. memcpy(aZip, p->body.a, p->body.n);
  5788. memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
  5789. zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
  5790. sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
  5791. }
  5792. }
  5793. sqlite3_free(p->body.a);
  5794. sqlite3_free(p->cds.a);
  5795. }
  5796. /*
  5797. ** Register the "zipfile" virtual table.
  5798. */
  5799. static int zipfileRegister(sqlite3 *db){
  5800. static sqlite3_module zipfileModule = {
  5801. 1, /* iVersion */
  5802. zipfileConnect, /* xCreate */
  5803. zipfileConnect, /* xConnect */
  5804. zipfileBestIndex, /* xBestIndex */
  5805. zipfileDisconnect, /* xDisconnect */
  5806. zipfileDisconnect, /* xDestroy */
  5807. zipfileOpen, /* xOpen - open a cursor */
  5808. zipfileClose, /* xClose - close a cursor */
  5809. zipfileFilter, /* xFilter - configure scan constraints */
  5810. zipfileNext, /* xNext - advance a cursor */
  5811. zipfileEof, /* xEof - check for end of scan */
  5812. zipfileColumn, /* xColumn - read data */
  5813. 0, /* xRowid - read data */
  5814. zipfileUpdate, /* xUpdate */
  5815. zipfileBegin, /* xBegin */
  5816. 0, /* xSync */
  5817. zipfileCommit, /* xCommit */
  5818. zipfileRollback, /* xRollback */
  5819. zipfileFindFunction, /* xFindMethod */
  5820. 0, /* xRename */
  5821. };
  5822. int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0);
  5823. if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
  5824. if( rc==SQLITE_OK ){
  5825. rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
  5826. zipfileStep, zipfileFinal
  5827. );
  5828. }
  5829. return rc;
  5830. }
  5831. #else /* SQLITE_OMIT_VIRTUALTABLE */
  5832. # define zipfileRegister(x) SQLITE_OK
  5833. #endif
  5834. #ifdef _WIN32
  5835. #endif
  5836. int sqlite3_zipfile_init(
  5837. sqlite3 *db,
  5838. char **pzErrMsg,
  5839. const sqlite3_api_routines *pApi
  5840. ){
  5841. SQLITE_EXTENSION_INIT2(pApi);
  5842. (void)pzErrMsg; /* Unused parameter */
  5843. return zipfileRegister(db);
  5844. }
  5845. /************************* End ../ext/misc/zipfile.c ********************/
  5846. /************************* Begin ../ext/misc/sqlar.c ******************/
  5847. /*
  5848. ** 2017-12-17
  5849. **
  5850. ** The author disclaims copyright to this source code. In place of
  5851. ** a legal notice, here is a blessing:
  5852. **
  5853. ** May you do good and not evil.
  5854. ** May you find forgiveness for yourself and forgive others.
  5855. ** May you share freely, never taking more than you give.
  5856. **
  5857. ******************************************************************************
  5858. **
  5859. ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
  5860. ** for working with sqlar archives and used by the shell tool's built-in
  5861. ** sqlar support.
  5862. */
  5863. SQLITE_EXTENSION_INIT1
  5864. #include <zlib.h>
  5865. /*
  5866. ** Implementation of the "sqlar_compress(X)" SQL function.
  5867. **
  5868. ** If the type of X is SQLITE_BLOB, and compressing that blob using
  5869. ** zlib utility function compress() yields a smaller blob, return the
  5870. ** compressed blob. Otherwise, return a copy of X.
  5871. **
  5872. ** SQLar uses the "zlib format" for compressed content. The zlib format
  5873. ** contains a two-byte identification header and a four-byte checksum at
  5874. ** the end. This is different from ZIP which uses the raw deflate format.
  5875. **
  5876. ** Future enhancements to SQLar might add support for new compression formats.
  5877. ** If so, those new formats will be identified by alternative headers in the
  5878. ** compressed data.
  5879. */
  5880. static void sqlarCompressFunc(
  5881. sqlite3_context *context,
  5882. int argc,
  5883. sqlite3_value **argv
  5884. ){
  5885. assert( argc==1 );
  5886. if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
  5887. const Bytef *pData = sqlite3_value_blob(argv[0]);
  5888. uLong nData = sqlite3_value_bytes(argv[0]);
  5889. uLongf nOut = compressBound(nData);
  5890. Bytef *pOut;
  5891. pOut = (Bytef*)sqlite3_malloc(nOut);
  5892. if( pOut==0 ){
  5893. sqlite3_result_error_nomem(context);
  5894. return;
  5895. }else{
  5896. if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
  5897. sqlite3_result_error(context, "error in compress()", -1);
  5898. }else if( nOut<nData ){
  5899. sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
  5900. }else{
  5901. sqlite3_result_value(context, argv[0]);
  5902. }
  5903. sqlite3_free(pOut);
  5904. }
  5905. }else{
  5906. sqlite3_result_value(context, argv[0]);
  5907. }
  5908. }
  5909. /*
  5910. ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
  5911. **
  5912. ** Parameter SZ is interpreted as an integer. If it is less than or
  5913. ** equal to zero, then this function returns a copy of X. Or, if
  5914. ** SZ is equal to the size of X when interpreted as a blob, also
  5915. ** return a copy of X. Otherwise, decompress blob X using zlib
  5916. ** utility function uncompress() and return the results (another
  5917. ** blob).
  5918. */
  5919. static void sqlarUncompressFunc(
  5920. sqlite3_context *context,
  5921. int argc,
  5922. sqlite3_value **argv
  5923. ){
  5924. uLong nData;
  5925. uLongf sz;
  5926. assert( argc==2 );
  5927. sz = sqlite3_value_int(argv[1]);
  5928. if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
  5929. sqlite3_result_value(context, argv[0]);
  5930. }else{
  5931. const Bytef *pData= sqlite3_value_blob(argv[0]);
  5932. Bytef *pOut = sqlite3_malloc(sz);
  5933. if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
  5934. sqlite3_result_error(context, "error in uncompress()", -1);
  5935. }else{
  5936. sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
  5937. }
  5938. sqlite3_free(pOut);
  5939. }
  5940. }
  5941. #ifdef _WIN32
  5942. #endif
  5943. int sqlite3_sqlar_init(
  5944. sqlite3 *db,
  5945. char **pzErrMsg,
  5946. const sqlite3_api_routines *pApi
  5947. ){
  5948. int rc = SQLITE_OK;
  5949. SQLITE_EXTENSION_INIT2(pApi);
  5950. (void)pzErrMsg; /* Unused parameter */
  5951. rc = sqlite3_create_function(db, "sqlar_compress", 1, SQLITE_UTF8, 0,
  5952. sqlarCompressFunc, 0, 0);
  5953. if( rc==SQLITE_OK ){
  5954. rc = sqlite3_create_function(db, "sqlar_uncompress", 2, SQLITE_UTF8, 0,
  5955. sqlarUncompressFunc, 0, 0);
  5956. }
  5957. return rc;
  5958. }
  5959. /************************* End ../ext/misc/sqlar.c ********************/
  5960. #endif
  5961. /************************* Begin ../ext/expert/sqlite3expert.h ******************/
  5962. /*
  5963. ** 2017 April 07
  5964. **
  5965. ** The author disclaims copyright to this source code. In place of
  5966. ** a legal notice, here is a blessing:
  5967. **
  5968. ** May you do good and not evil.
  5969. ** May you find forgiveness for yourself and forgive others.
  5970. ** May you share freely, never taking more than you give.
  5971. **
  5972. *************************************************************************
  5973. */
  5974. typedef struct sqlite3expert sqlite3expert;
  5975. /*
  5976. ** Create a new sqlite3expert object.
  5977. **
  5978. ** If successful, a pointer to the new object is returned and (*pzErr) set
  5979. ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
  5980. ** an English-language error message. In this case it is the responsibility
  5981. ** of the caller to eventually free the error message buffer using
  5982. ** sqlite3_free().
  5983. */
  5984. sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
  5985. /*
  5986. ** Configure an sqlite3expert object.
  5987. **
  5988. ** EXPERT_CONFIG_SAMPLE:
  5989. ** By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
  5990. ** each candidate index. This involves scanning and sorting the entire
  5991. ** contents of each user database table once for each candidate index
  5992. ** associated with the table. For large databases, this can be
  5993. ** prohibitively slow. This option allows the sqlite3expert object to
  5994. ** be configured so that sqlite_stat1 data is instead generated based on a
  5995. ** subset of each table, or so that no sqlite_stat1 data is used at all.
  5996. **
  5997. ** A single integer argument is passed to this option. If the value is less
  5998. ** than or equal to zero, then no sqlite_stat1 data is generated or used by
  5999. ** the analysis - indexes are recommended based on the database schema only.
  6000. ** Or, if the value is 100 or greater, complete sqlite_stat1 data is
  6001. ** generated for each candidate index (this is the default). Finally, if the
  6002. ** value falls between 0 and 100, then it represents the percentage of user
  6003. ** table rows that should be considered when generating sqlite_stat1 data.
  6004. **
  6005. ** Examples:
  6006. **
  6007. ** // Do not generate any sqlite_stat1 data
  6008. ** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
  6009. **
  6010. ** // Generate sqlite_stat1 data based on 10% of the rows in each table.
  6011. ** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
  6012. */
  6013. int sqlite3_expert_config(sqlite3expert *p, int op, ...);
  6014. #define EXPERT_CONFIG_SAMPLE 1 /* int */
  6015. /*
  6016. ** Specify zero or more SQL statements to be included in the analysis.
  6017. **
  6018. ** Buffer zSql must contain zero or more complete SQL statements. This
  6019. ** function parses all statements contained in the buffer and adds them
  6020. ** to the internal list of statements to analyze. If successful, SQLITE_OK
  6021. ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
  6022. ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
  6023. ** may be set to point to an English language error message. In this case
  6024. ** the caller is responsible for eventually freeing the error message buffer
  6025. ** using sqlite3_free().
  6026. **
  6027. ** If an error does occur while processing one of the statements in the
  6028. ** buffer passed as the second argument, none of the statements in the
  6029. ** buffer are added to the analysis.
  6030. **
  6031. ** This function must be called before sqlite3_expert_analyze(). If a call
  6032. ** to this function is made on an sqlite3expert object that has already
  6033. ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
  6034. ** immediately and no statements are added to the analysis.
  6035. */
  6036. int sqlite3_expert_sql(
  6037. sqlite3expert *p, /* From a successful sqlite3_expert_new() */
  6038. const char *zSql, /* SQL statement(s) to add */
  6039. char **pzErr /* OUT: Error message (if any) */
  6040. );
  6041. /*
  6042. ** This function is called after the sqlite3expert object has been configured
  6043. ** with all SQL statements using sqlite3_expert_sql() to actually perform
  6044. ** the analysis. Once this function has been called, it is not possible to
  6045. ** add further SQL statements to the analysis.
  6046. **
  6047. ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
  6048. ** an error occurs, an SQLite error code is returned and (*pzErr) set to
  6049. ** point to a buffer containing an English language error message. In this
  6050. ** case it is the responsibility of the caller to eventually free the buffer
  6051. ** using sqlite3_free().
  6052. **
  6053. ** If an error does occur within this function, the sqlite3expert object
  6054. ** is no longer useful for any purpose. At that point it is no longer
  6055. ** possible to add further SQL statements to the object or to re-attempt
  6056. ** the analysis. The sqlite3expert object must still be freed using a call
  6057. ** sqlite3_expert_destroy().
  6058. */
  6059. int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
  6060. /*
  6061. ** Return the total number of statements loaded using sqlite3_expert_sql().
  6062. ** The total number of SQL statements may be different from the total number
  6063. ** to calls to sqlite3_expert_sql().
  6064. */
  6065. int sqlite3_expert_count(sqlite3expert*);
  6066. /*
  6067. ** Return a component of the report.
  6068. **
  6069. ** This function is called after sqlite3_expert_analyze() to extract the
  6070. ** results of the analysis. Each call to this function returns either a
  6071. ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
  6072. ** The value passed as the third argument must be one of the EXPERT_REPORT_*
  6073. ** #define constants defined below.
  6074. **
  6075. ** For some EXPERT_REPORT_* parameters, the buffer returned contains
  6076. ** information relating to a specific SQL statement. In these cases that
  6077. ** SQL statement is identified by the value passed as the second argument.
  6078. ** SQL statements are numbered from 0 in the order in which they are parsed.
  6079. ** If an out-of-range value (less than zero or equal to or greater than the
  6080. ** value returned by sqlite3_expert_count()) is passed as the second argument
  6081. ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
  6082. **
  6083. ** EXPERT_REPORT_SQL:
  6084. ** Return the text of SQL statement iStmt.
  6085. **
  6086. ** EXPERT_REPORT_INDEXES:
  6087. ** Return a buffer containing the CREATE INDEX statements for all recommended
  6088. ** indexes for statement iStmt. If there are no new recommeded indexes, NULL
  6089. ** is returned.
  6090. **
  6091. ** EXPERT_REPORT_PLAN:
  6092. ** Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
  6093. ** iStmt after the proposed indexes have been added to the database schema.
  6094. **
  6095. ** EXPERT_REPORT_CANDIDATES:
  6096. ** Return a pointer to a buffer containing the CREATE INDEX statements
  6097. ** for all indexes that were tested (for all SQL statements). The iStmt
  6098. ** parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
  6099. */
  6100. const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
  6101. /*
  6102. ** Values for the third argument passed to sqlite3_expert_report().
  6103. */
  6104. #define EXPERT_REPORT_SQL 1
  6105. #define EXPERT_REPORT_INDEXES 2
  6106. #define EXPERT_REPORT_PLAN 3
  6107. #define EXPERT_REPORT_CANDIDATES 4
  6108. /*
  6109. ** Free an (sqlite3expert*) handle and all associated resources. There
  6110. ** should be one call to this function for each successful call to
  6111. ** sqlite3-expert_new().
  6112. */
  6113. void sqlite3_expert_destroy(sqlite3expert*);
  6114. /************************* End ../ext/expert/sqlite3expert.h ********************/
  6115. /************************* Begin ../ext/expert/sqlite3expert.c ******************/
  6116. /*
  6117. ** 2017 April 09
  6118. **
  6119. ** The author disclaims copyright to this source code. In place of
  6120. ** a legal notice, here is a blessing:
  6121. **
  6122. ** May you do good and not evil.
  6123. ** May you find forgiveness for yourself and forgive others.
  6124. ** May you share freely, never taking more than you give.
  6125. **
  6126. *************************************************************************
  6127. */
  6128. #include <assert.h>
  6129. #include <string.h>
  6130. #include <stdio.h>
  6131. #ifndef SQLITE_OMIT_VIRTUALTABLE
  6132. /* typedef sqlite3_int64 i64; */
  6133. /* typedef sqlite3_uint64 u64; */
  6134. typedef struct IdxColumn IdxColumn;
  6135. typedef struct IdxConstraint IdxConstraint;
  6136. typedef struct IdxScan IdxScan;
  6137. typedef struct IdxStatement IdxStatement;
  6138. typedef struct IdxTable IdxTable;
  6139. typedef struct IdxWrite IdxWrite;
  6140. #define STRLEN (int)strlen
  6141. /*
  6142. ** A temp table name that we assume no user database will actually use.
  6143. ** If this assumption proves incorrect triggers on the table with the
  6144. ** conflicting name will be ignored.
  6145. */
  6146. #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
  6147. /*
  6148. ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
  6149. ** any other type of single-ended range constraint on a column).
  6150. **
  6151. ** pLink:
  6152. ** Used to temporarily link IdxConstraint objects into lists while
  6153. ** creating candidate indexes.
  6154. */
  6155. struct IdxConstraint {
  6156. char *zColl; /* Collation sequence */
  6157. int bRange; /* True for range, false for eq */
  6158. int iCol; /* Constrained table column */
  6159. int bFlag; /* Used by idxFindCompatible() */
  6160. int bDesc; /* True if ORDER BY <expr> DESC */
  6161. IdxConstraint *pNext; /* Next constraint in pEq or pRange list */
  6162. IdxConstraint *pLink; /* See above */
  6163. };
  6164. /*
  6165. ** A single scan of a single table.
  6166. */
  6167. struct IdxScan {
  6168. IdxTable *pTab; /* Associated table object */
  6169. int iDb; /* Database containing table zTable */
  6170. i64 covering; /* Mask of columns required for cov. index */
  6171. IdxConstraint *pOrder; /* ORDER BY columns */
  6172. IdxConstraint *pEq; /* List of == constraints */
  6173. IdxConstraint *pRange; /* List of < constraints */
  6174. IdxScan *pNextScan; /* Next IdxScan object for same analysis */
  6175. };
  6176. /*
  6177. ** Information regarding a single database table. Extracted from
  6178. ** "PRAGMA table_info" by function idxGetTableInfo().
  6179. */
  6180. struct IdxColumn {
  6181. char *zName;
  6182. char *zColl;
  6183. int iPk;
  6184. };
  6185. struct IdxTable {
  6186. int nCol;
  6187. char *zName; /* Table name */
  6188. IdxColumn *aCol;
  6189. IdxTable *pNext; /* Next table in linked list of all tables */
  6190. };
  6191. /*
  6192. ** An object of the following type is created for each unique table/write-op
  6193. ** seen. The objects are stored in a singly-linked list beginning at
  6194. ** sqlite3expert.pWrite.
  6195. */
  6196. struct IdxWrite {
  6197. IdxTable *pTab;
  6198. int eOp; /* SQLITE_UPDATE, DELETE or INSERT */
  6199. IdxWrite *pNext;
  6200. };
  6201. /*
  6202. ** Each statement being analyzed is represented by an instance of this
  6203. ** structure.
  6204. */
  6205. struct IdxStatement {
  6206. int iId; /* Statement number */
  6207. char *zSql; /* SQL statement */
  6208. char *zIdx; /* Indexes */
  6209. char *zEQP; /* Plan */
  6210. IdxStatement *pNext;
  6211. };
  6212. /*
  6213. ** A hash table for storing strings. With space for a payload string
  6214. ** with each entry. Methods are:
  6215. **
  6216. ** idxHashInit()
  6217. ** idxHashClear()
  6218. ** idxHashAdd()
  6219. ** idxHashSearch()
  6220. */
  6221. #define IDX_HASH_SIZE 1023
  6222. typedef struct IdxHashEntry IdxHashEntry;
  6223. typedef struct IdxHash IdxHash;
  6224. struct IdxHashEntry {
  6225. char *zKey; /* nul-terminated key */
  6226. char *zVal; /* nul-terminated value string */
  6227. char *zVal2; /* nul-terminated value string 2 */
  6228. IdxHashEntry *pHashNext; /* Next entry in same hash bucket */
  6229. IdxHashEntry *pNext; /* Next entry in hash */
  6230. };
  6231. struct IdxHash {
  6232. IdxHashEntry *pFirst;
  6233. IdxHashEntry *aHash[IDX_HASH_SIZE];
  6234. };
  6235. /*
  6236. ** sqlite3expert object.
  6237. */
  6238. struct sqlite3expert {
  6239. int iSample; /* Percentage of tables to sample for stat1 */
  6240. sqlite3 *db; /* User database */
  6241. sqlite3 *dbm; /* In-memory db for this analysis */
  6242. sqlite3 *dbv; /* Vtab schema for this analysis */
  6243. IdxTable *pTable; /* List of all IdxTable objects */
  6244. IdxScan *pScan; /* List of scan objects */
  6245. IdxWrite *pWrite; /* List of write objects */
  6246. IdxStatement *pStatement; /* List of IdxStatement objects */
  6247. int bRun; /* True once analysis has run */
  6248. char **pzErrmsg;
  6249. int rc; /* Error code from whereinfo hook */
  6250. IdxHash hIdx; /* Hash containing all candidate indexes */
  6251. char *zCandidates; /* For EXPERT_REPORT_CANDIDATES */
  6252. };
  6253. /*
  6254. ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
  6255. ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
  6256. */
  6257. static void *idxMalloc(int *pRc, int nByte){
  6258. void *pRet;
  6259. assert( *pRc==SQLITE_OK );
  6260. assert( nByte>0 );
  6261. pRet = sqlite3_malloc(nByte);
  6262. if( pRet ){
  6263. memset(pRet, 0, nByte);
  6264. }else{
  6265. *pRc = SQLITE_NOMEM;
  6266. }
  6267. return pRet;
  6268. }
  6269. /*
  6270. ** Initialize an IdxHash hash table.
  6271. */
  6272. static void idxHashInit(IdxHash *pHash){
  6273. memset(pHash, 0, sizeof(IdxHash));
  6274. }
  6275. /*
  6276. ** Reset an IdxHash hash table.
  6277. */
  6278. static void idxHashClear(IdxHash *pHash){
  6279. int i;
  6280. for(i=0; i<IDX_HASH_SIZE; i++){
  6281. IdxHashEntry *pEntry;
  6282. IdxHashEntry *pNext;
  6283. for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
  6284. pNext = pEntry->pHashNext;
  6285. sqlite3_free(pEntry->zVal2);
  6286. sqlite3_free(pEntry);
  6287. }
  6288. }
  6289. memset(pHash, 0, sizeof(IdxHash));
  6290. }
  6291. /*
  6292. ** Return the index of the hash bucket that the string specified by the
  6293. ** arguments to this function belongs.
  6294. */
  6295. static int idxHashString(const char *z, int n){
  6296. unsigned int ret = 0;
  6297. int i;
  6298. for(i=0; i<n; i++){
  6299. ret += (ret<<3) + (unsigned char)(z[i]);
  6300. }
  6301. return (int)(ret % IDX_HASH_SIZE);
  6302. }
  6303. /*
  6304. ** If zKey is already present in the hash table, return non-zero and do
  6305. ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
  6306. ** the hash table passed as the second argument.
  6307. */
  6308. static int idxHashAdd(
  6309. int *pRc,
  6310. IdxHash *pHash,
  6311. const char *zKey,
  6312. const char *zVal
  6313. ){
  6314. int nKey = STRLEN(zKey);
  6315. int iHash = idxHashString(zKey, nKey);
  6316. int nVal = (zVal ? STRLEN(zVal) : 0);
  6317. IdxHashEntry *pEntry;
  6318. assert( iHash>=0 );
  6319. for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
  6320. if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
  6321. return 1;
  6322. }
  6323. }
  6324. pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
  6325. if( pEntry ){
  6326. pEntry->zKey = (char*)&pEntry[1];
  6327. memcpy(pEntry->zKey, zKey, nKey);
  6328. if( zVal ){
  6329. pEntry->zVal = &pEntry->zKey[nKey+1];
  6330. memcpy(pEntry->zVal, zVal, nVal);
  6331. }
  6332. pEntry->pHashNext = pHash->aHash[iHash];
  6333. pHash->aHash[iHash] = pEntry;
  6334. pEntry->pNext = pHash->pFirst;
  6335. pHash->pFirst = pEntry;
  6336. }
  6337. return 0;
  6338. }
  6339. /*
  6340. ** If zKey/nKey is present in the hash table, return a pointer to the
  6341. ** hash-entry object.
  6342. */
  6343. static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
  6344. int iHash;
  6345. IdxHashEntry *pEntry;
  6346. if( nKey<0 ) nKey = STRLEN(zKey);
  6347. iHash = idxHashString(zKey, nKey);
  6348. assert( iHash>=0 );
  6349. for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
  6350. if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
  6351. return pEntry;
  6352. }
  6353. }
  6354. return 0;
  6355. }
  6356. /*
  6357. ** If the hash table contains an entry with a key equal to the string
  6358. ** passed as the final two arguments to this function, return a pointer
  6359. ** to the payload string. Otherwise, if zKey/nKey is not present in the
  6360. ** hash table, return NULL.
  6361. */
  6362. static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
  6363. IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
  6364. if( pEntry ) return pEntry->zVal;
  6365. return 0;
  6366. }
  6367. /*
  6368. ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
  6369. ** variable to point to a copy of nul-terminated string zColl.
  6370. */
  6371. static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
  6372. IdxConstraint *pNew;
  6373. int nColl = STRLEN(zColl);
  6374. assert( *pRc==SQLITE_OK );
  6375. pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
  6376. if( pNew ){
  6377. pNew->zColl = (char*)&pNew[1];
  6378. memcpy(pNew->zColl, zColl, nColl+1);
  6379. }
  6380. return pNew;
  6381. }
  6382. /*
  6383. ** An error associated with database handle db has just occurred. Pass
  6384. ** the error message to callback function xOut.
  6385. */
  6386. static void idxDatabaseError(
  6387. sqlite3 *db, /* Database handle */
  6388. char **pzErrmsg /* Write error here */
  6389. ){
  6390. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  6391. }
  6392. /*
  6393. ** Prepare an SQL statement.
  6394. */
  6395. static int idxPrepareStmt(
  6396. sqlite3 *db, /* Database handle to compile against */
  6397. sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
  6398. char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
  6399. const char *zSql /* SQL statement to compile */
  6400. ){
  6401. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  6402. if( rc!=SQLITE_OK ){
  6403. *ppStmt = 0;
  6404. idxDatabaseError(db, pzErrmsg);
  6405. }
  6406. return rc;
  6407. }
  6408. /*
  6409. ** Prepare an SQL statement using the results of a printf() formatting.
  6410. */
  6411. static int idxPrintfPrepareStmt(
  6412. sqlite3 *db, /* Database handle to compile against */
  6413. sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
  6414. char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
  6415. const char *zFmt, /* printf() format of SQL statement */
  6416. ... /* Trailing printf() arguments */
  6417. ){
  6418. va_list ap;
  6419. int rc;
  6420. char *zSql;
  6421. va_start(ap, zFmt);
  6422. zSql = sqlite3_vmprintf(zFmt, ap);
  6423. if( zSql==0 ){
  6424. rc = SQLITE_NOMEM;
  6425. }else{
  6426. rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
  6427. sqlite3_free(zSql);
  6428. }
  6429. va_end(ap);
  6430. return rc;
  6431. }
  6432. /*************************************************************************
  6433. ** Beginning of virtual table implementation.
  6434. */
  6435. typedef struct ExpertVtab ExpertVtab;
  6436. struct ExpertVtab {
  6437. sqlite3_vtab base;
  6438. IdxTable *pTab;
  6439. sqlite3expert *pExpert;
  6440. };
  6441. typedef struct ExpertCsr ExpertCsr;
  6442. struct ExpertCsr {
  6443. sqlite3_vtab_cursor base;
  6444. sqlite3_stmt *pData;
  6445. };
  6446. static char *expertDequote(const char *zIn){
  6447. int n = STRLEN(zIn);
  6448. char *zRet = sqlite3_malloc(n);
  6449. assert( zIn[0]=='\'' );
  6450. assert( zIn[n-1]=='\'' );
  6451. if( zRet ){
  6452. int iOut = 0;
  6453. int iIn = 0;
  6454. for(iIn=1; iIn<(n-1); iIn++){
  6455. if( zIn[iIn]=='\'' ){
  6456. assert( zIn[iIn+1]=='\'' );
  6457. iIn++;
  6458. }
  6459. zRet[iOut++] = zIn[iIn];
  6460. }
  6461. zRet[iOut] = '\0';
  6462. }
  6463. return zRet;
  6464. }
  6465. /*
  6466. ** This function is the implementation of both the xConnect and xCreate
  6467. ** methods of the r-tree virtual table.
  6468. **
  6469. ** argv[0] -> module name
  6470. ** argv[1] -> database name
  6471. ** argv[2] -> table name
  6472. ** argv[...] -> column names...
  6473. */
  6474. static int expertConnect(
  6475. sqlite3 *db,
  6476. void *pAux,
  6477. int argc, const char *const*argv,
  6478. sqlite3_vtab **ppVtab,
  6479. char **pzErr
  6480. ){
  6481. sqlite3expert *pExpert = (sqlite3expert*)pAux;
  6482. ExpertVtab *p = 0;
  6483. int rc;
  6484. if( argc!=4 ){
  6485. *pzErr = sqlite3_mprintf("internal error!");
  6486. rc = SQLITE_ERROR;
  6487. }else{
  6488. char *zCreateTable = expertDequote(argv[3]);
  6489. if( zCreateTable ){
  6490. rc = sqlite3_declare_vtab(db, zCreateTable);
  6491. if( rc==SQLITE_OK ){
  6492. p = idxMalloc(&rc, sizeof(ExpertVtab));
  6493. }
  6494. if( rc==SQLITE_OK ){
  6495. p->pExpert = pExpert;
  6496. p->pTab = pExpert->pTable;
  6497. assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
  6498. }
  6499. sqlite3_free(zCreateTable);
  6500. }else{
  6501. rc = SQLITE_NOMEM;
  6502. }
  6503. }
  6504. *ppVtab = (sqlite3_vtab*)p;
  6505. return rc;
  6506. }
  6507. static int expertDisconnect(sqlite3_vtab *pVtab){
  6508. ExpertVtab *p = (ExpertVtab*)pVtab;
  6509. sqlite3_free(p);
  6510. return SQLITE_OK;
  6511. }
  6512. static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
  6513. ExpertVtab *p = (ExpertVtab*)pVtab;
  6514. int rc = SQLITE_OK;
  6515. int n = 0;
  6516. IdxScan *pScan;
  6517. const int opmask =
  6518. SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
  6519. SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
  6520. SQLITE_INDEX_CONSTRAINT_LE;
  6521. pScan = idxMalloc(&rc, sizeof(IdxScan));
  6522. if( pScan ){
  6523. int i;
  6524. /* Link the new scan object into the list */
  6525. pScan->pTab = p->pTab;
  6526. pScan->pNextScan = p->pExpert->pScan;
  6527. p->pExpert->pScan = pScan;
  6528. /* Add the constraints to the IdxScan object */
  6529. for(i=0; i<pIdxInfo->nConstraint; i++){
  6530. struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
  6531. if( pCons->usable
  6532. && pCons->iColumn>=0
  6533. && p->pTab->aCol[pCons->iColumn].iPk==0
  6534. && (pCons->op & opmask)
  6535. ){
  6536. IdxConstraint *pNew;
  6537. const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
  6538. pNew = idxNewConstraint(&rc, zColl);
  6539. if( pNew ){
  6540. pNew->iCol = pCons->iColumn;
  6541. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  6542. pNew->pNext = pScan->pEq;
  6543. pScan->pEq = pNew;
  6544. }else{
  6545. pNew->bRange = 1;
  6546. pNew->pNext = pScan->pRange;
  6547. pScan->pRange = pNew;
  6548. }
  6549. }
  6550. n++;
  6551. pIdxInfo->aConstraintUsage[i].argvIndex = n;
  6552. }
  6553. }
  6554. /* Add the ORDER BY to the IdxScan object */
  6555. for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
  6556. int iCol = pIdxInfo->aOrderBy[i].iColumn;
  6557. if( iCol>=0 ){
  6558. IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
  6559. if( pNew ){
  6560. pNew->iCol = iCol;
  6561. pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
  6562. pNew->pNext = pScan->pOrder;
  6563. pNew->pLink = pScan->pOrder;
  6564. pScan->pOrder = pNew;
  6565. n++;
  6566. }
  6567. }
  6568. }
  6569. }
  6570. pIdxInfo->estimatedCost = 1000000.0 / (n+1);
  6571. return rc;
  6572. }
  6573. static int expertUpdate(
  6574. sqlite3_vtab *pVtab,
  6575. int nData,
  6576. sqlite3_value **azData,
  6577. sqlite_int64 *pRowid
  6578. ){
  6579. (void)pVtab;
  6580. (void)nData;
  6581. (void)azData;
  6582. (void)pRowid;
  6583. return SQLITE_OK;
  6584. }
  6585. /*
  6586. ** Virtual table module xOpen method.
  6587. */
  6588. static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  6589. int rc = SQLITE_OK;
  6590. ExpertCsr *pCsr;
  6591. (void)pVTab;
  6592. pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
  6593. *ppCursor = (sqlite3_vtab_cursor*)pCsr;
  6594. return rc;
  6595. }
  6596. /*
  6597. ** Virtual table module xClose method.
  6598. */
  6599. static int expertClose(sqlite3_vtab_cursor *cur){
  6600. ExpertCsr *pCsr = (ExpertCsr*)cur;
  6601. sqlite3_finalize(pCsr->pData);
  6602. sqlite3_free(pCsr);
  6603. return SQLITE_OK;
  6604. }
  6605. /*
  6606. ** Virtual table module xEof method.
  6607. **
  6608. ** Return non-zero if the cursor does not currently point to a valid
  6609. ** record (i.e if the scan has finished), or zero otherwise.
  6610. */
  6611. static int expertEof(sqlite3_vtab_cursor *cur){
  6612. ExpertCsr *pCsr = (ExpertCsr*)cur;
  6613. return pCsr->pData==0;
  6614. }
  6615. /*
  6616. ** Virtual table module xNext method.
  6617. */
  6618. static int expertNext(sqlite3_vtab_cursor *cur){
  6619. ExpertCsr *pCsr = (ExpertCsr*)cur;
  6620. int rc = SQLITE_OK;
  6621. assert( pCsr->pData );
  6622. rc = sqlite3_step(pCsr->pData);
  6623. if( rc!=SQLITE_ROW ){
  6624. rc = sqlite3_finalize(pCsr->pData);
  6625. pCsr->pData = 0;
  6626. }else{
  6627. rc = SQLITE_OK;
  6628. }
  6629. return rc;
  6630. }
  6631. /*
  6632. ** Virtual table module xRowid method.
  6633. */
  6634. static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  6635. (void)cur;
  6636. *pRowid = 0;
  6637. return SQLITE_OK;
  6638. }
  6639. /*
  6640. ** Virtual table module xColumn method.
  6641. */
  6642. static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  6643. ExpertCsr *pCsr = (ExpertCsr*)cur;
  6644. sqlite3_value *pVal;
  6645. pVal = sqlite3_column_value(pCsr->pData, i);
  6646. if( pVal ){
  6647. sqlite3_result_value(ctx, pVal);
  6648. }
  6649. return SQLITE_OK;
  6650. }
  6651. /*
  6652. ** Virtual table module xFilter method.
  6653. */
  6654. static int expertFilter(
  6655. sqlite3_vtab_cursor *cur,
  6656. int idxNum, const char *idxStr,
  6657. int argc, sqlite3_value **argv
  6658. ){
  6659. ExpertCsr *pCsr = (ExpertCsr*)cur;
  6660. ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
  6661. sqlite3expert *pExpert = pVtab->pExpert;
  6662. int rc;
  6663. (void)idxNum;
  6664. (void)idxStr;
  6665. (void)argc;
  6666. (void)argv;
  6667. rc = sqlite3_finalize(pCsr->pData);
  6668. pCsr->pData = 0;
  6669. if( rc==SQLITE_OK ){
  6670. rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
  6671. "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
  6672. );
  6673. }
  6674. if( rc==SQLITE_OK ){
  6675. rc = expertNext(cur);
  6676. }
  6677. return rc;
  6678. }
  6679. static int idxRegisterVtab(sqlite3expert *p){
  6680. static sqlite3_module expertModule = {
  6681. 2, /* iVersion */
  6682. expertConnect, /* xCreate - create a table */
  6683. expertConnect, /* xConnect - connect to an existing table */
  6684. expertBestIndex, /* xBestIndex - Determine search strategy */
  6685. expertDisconnect, /* xDisconnect - Disconnect from a table */
  6686. expertDisconnect, /* xDestroy - Drop a table */
  6687. expertOpen, /* xOpen - open a cursor */
  6688. expertClose, /* xClose - close a cursor */
  6689. expertFilter, /* xFilter - configure scan constraints */
  6690. expertNext, /* xNext - advance a cursor */
  6691. expertEof, /* xEof */
  6692. expertColumn, /* xColumn - read data */
  6693. expertRowid, /* xRowid - read data */
  6694. expertUpdate, /* xUpdate - write data */
  6695. 0, /* xBegin - begin transaction */
  6696. 0, /* xSync - sync transaction */
  6697. 0, /* xCommit - commit transaction */
  6698. 0, /* xRollback - rollback transaction */
  6699. 0, /* xFindFunction - function overloading */
  6700. 0, /* xRename - rename the table */
  6701. 0, /* xSavepoint */
  6702. 0, /* xRelease */
  6703. 0, /* xRollbackTo */
  6704. 0, /* xShadowName */
  6705. };
  6706. return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
  6707. }
  6708. /*
  6709. ** End of virtual table implementation.
  6710. *************************************************************************/
  6711. /*
  6712. ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
  6713. ** is called, set it to the return value of sqlite3_finalize() before
  6714. ** returning. Otherwise, discard the sqlite3_finalize() return value.
  6715. */
  6716. static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
  6717. int rc = sqlite3_finalize(pStmt);
  6718. if( *pRc==SQLITE_OK ) *pRc = rc;
  6719. }
  6720. /*
  6721. ** Attempt to allocate an IdxTable structure corresponding to table zTab
  6722. ** in the main database of connection db. If successful, set (*ppOut) to
  6723. ** point to the new object and return SQLITE_OK. Otherwise, return an
  6724. ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
  6725. ** set to point to an error string.
  6726. **
  6727. ** It is the responsibility of the caller to eventually free either the
  6728. ** IdxTable object or error message using sqlite3_free().
  6729. */
  6730. static int idxGetTableInfo(
  6731. sqlite3 *db, /* Database connection to read details from */
  6732. const char *zTab, /* Table name */
  6733. IdxTable **ppOut, /* OUT: New object (if successful) */
  6734. char **pzErrmsg /* OUT: Error message (if not) */
  6735. ){
  6736. sqlite3_stmt *p1 = 0;
  6737. int nCol = 0;
  6738. int nTab = STRLEN(zTab);
  6739. int nByte = sizeof(IdxTable) + nTab + 1;
  6740. IdxTable *pNew = 0;
  6741. int rc, rc2;
  6742. char *pCsr = 0;
  6743. rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_info=%Q", zTab);
  6744. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
  6745. const char *zCol = (const char*)sqlite3_column_text(p1, 1);
  6746. nByte += 1 + STRLEN(zCol);
  6747. rc = sqlite3_table_column_metadata(
  6748. db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
  6749. );
  6750. nByte += 1 + STRLEN(zCol);
  6751. nCol++;
  6752. }
  6753. rc2 = sqlite3_reset(p1);
  6754. if( rc==SQLITE_OK ) rc = rc2;
  6755. nByte += sizeof(IdxColumn) * nCol;
  6756. if( rc==SQLITE_OK ){
  6757. pNew = idxMalloc(&rc, nByte);
  6758. }
  6759. if( rc==SQLITE_OK ){
  6760. pNew->aCol = (IdxColumn*)&pNew[1];
  6761. pNew->nCol = nCol;
  6762. pCsr = (char*)&pNew->aCol[nCol];
  6763. }
  6764. nCol = 0;
  6765. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
  6766. const char *zCol = (const char*)sqlite3_column_text(p1, 1);
  6767. int nCopy = STRLEN(zCol) + 1;
  6768. pNew->aCol[nCol].zName = pCsr;
  6769. pNew->aCol[nCol].iPk = sqlite3_column_int(p1, 5);
  6770. memcpy(pCsr, zCol, nCopy);
  6771. pCsr += nCopy;
  6772. rc = sqlite3_table_column_metadata(
  6773. db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
  6774. );
  6775. if( rc==SQLITE_OK ){
  6776. nCopy = STRLEN(zCol) + 1;
  6777. pNew->aCol[nCol].zColl = pCsr;
  6778. memcpy(pCsr, zCol, nCopy);
  6779. pCsr += nCopy;
  6780. }
  6781. nCol++;
  6782. }
  6783. idxFinalize(&rc, p1);
  6784. if( rc!=SQLITE_OK ){
  6785. sqlite3_free(pNew);
  6786. pNew = 0;
  6787. }else{
  6788. pNew->zName = pCsr;
  6789. memcpy(pNew->zName, zTab, nTab+1);
  6790. }
  6791. *ppOut = pNew;
  6792. return rc;
  6793. }
  6794. /*
  6795. ** This function is a no-op if *pRc is set to anything other than
  6796. ** SQLITE_OK when it is called.
  6797. **
  6798. ** If *pRc is initially set to SQLITE_OK, then the text specified by
  6799. ** the printf() style arguments is appended to zIn and the result returned
  6800. ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
  6801. ** zIn before returning.
  6802. */
  6803. static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
  6804. va_list ap;
  6805. char *zAppend = 0;
  6806. char *zRet = 0;
  6807. int nIn = zIn ? STRLEN(zIn) : 0;
  6808. int nAppend = 0;
  6809. va_start(ap, zFmt);
  6810. if( *pRc==SQLITE_OK ){
  6811. zAppend = sqlite3_vmprintf(zFmt, ap);
  6812. if( zAppend ){
  6813. nAppend = STRLEN(zAppend);
  6814. zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
  6815. }
  6816. if( zAppend && zRet ){
  6817. if( nIn ) memcpy(zRet, zIn, nIn);
  6818. memcpy(&zRet[nIn], zAppend, nAppend+1);
  6819. }else{
  6820. sqlite3_free(zRet);
  6821. zRet = 0;
  6822. *pRc = SQLITE_NOMEM;
  6823. }
  6824. sqlite3_free(zAppend);
  6825. sqlite3_free(zIn);
  6826. }
  6827. va_end(ap);
  6828. return zRet;
  6829. }
  6830. /*
  6831. ** Return true if zId must be quoted in order to use it as an SQL
  6832. ** identifier, or false otherwise.
  6833. */
  6834. static int idxIdentifierRequiresQuotes(const char *zId){
  6835. int i;
  6836. for(i=0; zId[i]; i++){
  6837. if( !(zId[i]=='_')
  6838. && !(zId[i]>='0' && zId[i]<='9')
  6839. && !(zId[i]>='a' && zId[i]<='z')
  6840. && !(zId[i]>='A' && zId[i]<='Z')
  6841. ){
  6842. return 1;
  6843. }
  6844. }
  6845. return 0;
  6846. }
  6847. /*
  6848. ** This function appends an index column definition suitable for constraint
  6849. ** pCons to the string passed as zIn and returns the result.
  6850. */
  6851. static char *idxAppendColDefn(
  6852. int *pRc, /* IN/OUT: Error code */
  6853. char *zIn, /* Column defn accumulated so far */
  6854. IdxTable *pTab, /* Table index will be created on */
  6855. IdxConstraint *pCons
  6856. ){
  6857. char *zRet = zIn;
  6858. IdxColumn *p = &pTab->aCol[pCons->iCol];
  6859. if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
  6860. if( idxIdentifierRequiresQuotes(p->zName) ){
  6861. zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
  6862. }else{
  6863. zRet = idxAppendText(pRc, zRet, "%s", p->zName);
  6864. }
  6865. if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
  6866. if( idxIdentifierRequiresQuotes(pCons->zColl) ){
  6867. zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
  6868. }else{
  6869. zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
  6870. }
  6871. }
  6872. if( pCons->bDesc ){
  6873. zRet = idxAppendText(pRc, zRet, " DESC");
  6874. }
  6875. return zRet;
  6876. }
  6877. /*
  6878. ** Search database dbm for an index compatible with the one idxCreateFromCons()
  6879. ** would create from arguments pScan, pEq and pTail. If no error occurs and
  6880. ** such an index is found, return non-zero. Or, if no such index is found,
  6881. ** return zero.
  6882. **
  6883. ** If an error occurs, set *pRc to an SQLite error code and return zero.
  6884. */
  6885. static int idxFindCompatible(
  6886. int *pRc, /* OUT: Error code */
  6887. sqlite3* dbm, /* Database to search */
  6888. IdxScan *pScan, /* Scan for table to search for index on */
  6889. IdxConstraint *pEq, /* List of == constraints */
  6890. IdxConstraint *pTail /* List of range constraints */
  6891. ){
  6892. const char *zTbl = pScan->pTab->zName;
  6893. sqlite3_stmt *pIdxList = 0;
  6894. IdxConstraint *pIter;
  6895. int nEq = 0; /* Number of elements in pEq */
  6896. int rc;
  6897. /* Count the elements in list pEq */
  6898. for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
  6899. rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
  6900. while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
  6901. int bMatch = 1;
  6902. IdxConstraint *pT = pTail;
  6903. sqlite3_stmt *pInfo = 0;
  6904. const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
  6905. /* Zero the IdxConstraint.bFlag values in the pEq list */
  6906. for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
  6907. rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
  6908. while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
  6909. int iIdx = sqlite3_column_int(pInfo, 0);
  6910. int iCol = sqlite3_column_int(pInfo, 1);
  6911. const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
  6912. if( iIdx<nEq ){
  6913. for(pIter=pEq; pIter; pIter=pIter->pLink){
  6914. if( pIter->bFlag ) continue;
  6915. if( pIter->iCol!=iCol ) continue;
  6916. if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
  6917. pIter->bFlag = 1;
  6918. break;
  6919. }
  6920. if( pIter==0 ){
  6921. bMatch = 0;
  6922. break;
  6923. }
  6924. }else{
  6925. if( pT ){
  6926. if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
  6927. bMatch = 0;
  6928. break;
  6929. }
  6930. pT = pT->pLink;
  6931. }
  6932. }
  6933. }
  6934. idxFinalize(&rc, pInfo);
  6935. if( rc==SQLITE_OK && bMatch ){
  6936. sqlite3_finalize(pIdxList);
  6937. return 1;
  6938. }
  6939. }
  6940. idxFinalize(&rc, pIdxList);
  6941. *pRc = rc;
  6942. return 0;
  6943. }
  6944. static int idxCreateFromCons(
  6945. sqlite3expert *p,
  6946. IdxScan *pScan,
  6947. IdxConstraint *pEq,
  6948. IdxConstraint *pTail
  6949. ){
  6950. sqlite3 *dbm = p->dbm;
  6951. int rc = SQLITE_OK;
  6952. if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
  6953. IdxTable *pTab = pScan->pTab;
  6954. char *zCols = 0;
  6955. char *zIdx = 0;
  6956. IdxConstraint *pCons;
  6957. unsigned int h = 0;
  6958. const char *zFmt;
  6959. for(pCons=pEq; pCons; pCons=pCons->pLink){
  6960. zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
  6961. }
  6962. for(pCons=pTail; pCons; pCons=pCons->pLink){
  6963. zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
  6964. }
  6965. if( rc==SQLITE_OK ){
  6966. /* Hash the list of columns to come up with a name for the index */
  6967. const char *zTable = pScan->pTab->zName;
  6968. char *zName; /* Index name */
  6969. int i;
  6970. for(i=0; zCols[i]; i++){
  6971. h += ((h<<3) + zCols[i]);
  6972. }
  6973. zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
  6974. if( zName==0 ){
  6975. rc = SQLITE_NOMEM;
  6976. }else{
  6977. if( idxIdentifierRequiresQuotes(zTable) ){
  6978. zFmt = "CREATE INDEX '%q' ON %Q(%s)";
  6979. }else{
  6980. zFmt = "CREATE INDEX %s ON %s(%s)";
  6981. }
  6982. zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
  6983. if( !zIdx ){
  6984. rc = SQLITE_NOMEM;
  6985. }else{
  6986. rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
  6987. idxHashAdd(&rc, &p->hIdx, zName, zIdx);
  6988. }
  6989. sqlite3_free(zName);
  6990. sqlite3_free(zIdx);
  6991. }
  6992. }
  6993. sqlite3_free(zCols);
  6994. }
  6995. return rc;
  6996. }
  6997. /*
  6998. ** Return true if list pList (linked by IdxConstraint.pLink) contains
  6999. ** a constraint compatible with *p. Otherwise return false.
  7000. */
  7001. static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
  7002. IdxConstraint *pCmp;
  7003. for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
  7004. if( p->iCol==pCmp->iCol ) return 1;
  7005. }
  7006. return 0;
  7007. }
  7008. static int idxCreateFromWhere(
  7009. sqlite3expert *p,
  7010. IdxScan *pScan, /* Create indexes for this scan */
  7011. IdxConstraint *pTail /* range/ORDER BY constraints for inclusion */
  7012. ){
  7013. IdxConstraint *p1 = 0;
  7014. IdxConstraint *pCon;
  7015. int rc;
  7016. /* Gather up all the == constraints. */
  7017. for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
  7018. if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
  7019. pCon->pLink = p1;
  7020. p1 = pCon;
  7021. }
  7022. }
  7023. /* Create an index using the == constraints collected above. And the
  7024. ** range constraint/ORDER BY terms passed in by the caller, if any. */
  7025. rc = idxCreateFromCons(p, pScan, p1, pTail);
  7026. /* If no range/ORDER BY passed by the caller, create a version of the
  7027. ** index for each range constraint. */
  7028. if( pTail==0 ){
  7029. for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
  7030. assert( pCon->pLink==0 );
  7031. if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
  7032. rc = idxCreateFromCons(p, pScan, p1, pCon);
  7033. }
  7034. }
  7035. }
  7036. return rc;
  7037. }
  7038. /*
  7039. ** Create candidate indexes in database [dbm] based on the data in
  7040. ** linked-list pScan.
  7041. */
  7042. static int idxCreateCandidates(sqlite3expert *p){
  7043. int rc = SQLITE_OK;
  7044. IdxScan *pIter;
  7045. for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
  7046. rc = idxCreateFromWhere(p, pIter, 0);
  7047. if( rc==SQLITE_OK && pIter->pOrder ){
  7048. rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
  7049. }
  7050. }
  7051. return rc;
  7052. }
  7053. /*
  7054. ** Free all elements of the linked list starting at pConstraint.
  7055. */
  7056. static void idxConstraintFree(IdxConstraint *pConstraint){
  7057. IdxConstraint *pNext;
  7058. IdxConstraint *p;
  7059. for(p=pConstraint; p; p=pNext){
  7060. pNext = p->pNext;
  7061. sqlite3_free(p);
  7062. }
  7063. }
  7064. /*
  7065. ** Free all elements of the linked list starting from pScan up until pLast
  7066. ** (pLast is not freed).
  7067. */
  7068. static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
  7069. IdxScan *p;
  7070. IdxScan *pNext;
  7071. for(p=pScan; p!=pLast; p=pNext){
  7072. pNext = p->pNextScan;
  7073. idxConstraintFree(p->pOrder);
  7074. idxConstraintFree(p->pEq);
  7075. idxConstraintFree(p->pRange);
  7076. sqlite3_free(p);
  7077. }
  7078. }
  7079. /*
  7080. ** Free all elements of the linked list starting from pStatement up
  7081. ** until pLast (pLast is not freed).
  7082. */
  7083. static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
  7084. IdxStatement *p;
  7085. IdxStatement *pNext;
  7086. for(p=pStatement; p!=pLast; p=pNext){
  7087. pNext = p->pNext;
  7088. sqlite3_free(p->zEQP);
  7089. sqlite3_free(p->zIdx);
  7090. sqlite3_free(p);
  7091. }
  7092. }
  7093. /*
  7094. ** Free the linked list of IdxTable objects starting at pTab.
  7095. */
  7096. static void idxTableFree(IdxTable *pTab){
  7097. IdxTable *pIter;
  7098. IdxTable *pNext;
  7099. for(pIter=pTab; pIter; pIter=pNext){
  7100. pNext = pIter->pNext;
  7101. sqlite3_free(pIter);
  7102. }
  7103. }
  7104. /*
  7105. ** Free the linked list of IdxWrite objects starting at pTab.
  7106. */
  7107. static void idxWriteFree(IdxWrite *pTab){
  7108. IdxWrite *pIter;
  7109. IdxWrite *pNext;
  7110. for(pIter=pTab; pIter; pIter=pNext){
  7111. pNext = pIter->pNext;
  7112. sqlite3_free(pIter);
  7113. }
  7114. }
  7115. /*
  7116. ** This function is called after candidate indexes have been created. It
  7117. ** runs all the queries to see which indexes they prefer, and populates
  7118. ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
  7119. */
  7120. int idxFindIndexes(
  7121. sqlite3expert *p,
  7122. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  7123. ){
  7124. IdxStatement *pStmt;
  7125. sqlite3 *dbm = p->dbm;
  7126. int rc = SQLITE_OK;
  7127. IdxHash hIdx;
  7128. idxHashInit(&hIdx);
  7129. for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
  7130. IdxHashEntry *pEntry;
  7131. sqlite3_stmt *pExplain = 0;
  7132. idxHashClear(&hIdx);
  7133. rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
  7134. "EXPLAIN QUERY PLAN %s", pStmt->zSql
  7135. );
  7136. while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
  7137. /* int iId = sqlite3_column_int(pExplain, 0); */
  7138. /* int iParent = sqlite3_column_int(pExplain, 1); */
  7139. /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
  7140. const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
  7141. int nDetail = STRLEN(zDetail);
  7142. int i;
  7143. for(i=0; i<nDetail; i++){
  7144. const char *zIdx = 0;
  7145. if( memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
  7146. zIdx = &zDetail[i+13];
  7147. }else if( memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0 ){
  7148. zIdx = &zDetail[i+22];
  7149. }
  7150. if( zIdx ){
  7151. const char *zSql;
  7152. int nIdx = 0;
  7153. while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
  7154. nIdx++;
  7155. }
  7156. zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
  7157. if( zSql ){
  7158. idxHashAdd(&rc, &hIdx, zSql, 0);
  7159. if( rc ) goto find_indexes_out;
  7160. }
  7161. break;
  7162. }
  7163. }
  7164. if( zDetail[0]!='-' ){
  7165. pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
  7166. }
  7167. }
  7168. for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
  7169. pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
  7170. }
  7171. idxFinalize(&rc, pExplain);
  7172. }
  7173. find_indexes_out:
  7174. idxHashClear(&hIdx);
  7175. return rc;
  7176. }
  7177. static int idxAuthCallback(
  7178. void *pCtx,
  7179. int eOp,
  7180. const char *z3,
  7181. const char *z4,
  7182. const char *zDb,
  7183. const char *zTrigger
  7184. ){
  7185. int rc = SQLITE_OK;
  7186. (void)z4;
  7187. (void)zTrigger;
  7188. if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
  7189. if( sqlite3_stricmp(zDb, "main")==0 ){
  7190. sqlite3expert *p = (sqlite3expert*)pCtx;
  7191. IdxTable *pTab;
  7192. for(pTab=p->pTable; pTab; pTab=pTab->pNext){
  7193. if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
  7194. }
  7195. if( pTab ){
  7196. IdxWrite *pWrite;
  7197. for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
  7198. if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
  7199. }
  7200. if( pWrite==0 ){
  7201. pWrite = idxMalloc(&rc, sizeof(IdxWrite));
  7202. if( rc==SQLITE_OK ){
  7203. pWrite->pTab = pTab;
  7204. pWrite->eOp = eOp;
  7205. pWrite->pNext = p->pWrite;
  7206. p->pWrite = pWrite;
  7207. }
  7208. }
  7209. }
  7210. }
  7211. }
  7212. return rc;
  7213. }
  7214. static int idxProcessOneTrigger(
  7215. sqlite3expert *p,
  7216. IdxWrite *pWrite,
  7217. char **pzErr
  7218. ){
  7219. static const char *zInt = UNIQUE_TABLE_NAME;
  7220. static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
  7221. IdxTable *pTab = pWrite->pTab;
  7222. const char *zTab = pTab->zName;
  7223. const char *zSql =
  7224. "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_master "
  7225. "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
  7226. "ORDER BY type;";
  7227. sqlite3_stmt *pSelect = 0;
  7228. int rc = SQLITE_OK;
  7229. char *zWrite = 0;
  7230. /* Create the table and its triggers in the temp schema */
  7231. rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
  7232. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
  7233. const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
  7234. rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
  7235. }
  7236. idxFinalize(&rc, pSelect);
  7237. /* Rename the table in the temp schema to zInt */
  7238. if( rc==SQLITE_OK ){
  7239. char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
  7240. if( z==0 ){
  7241. rc = SQLITE_NOMEM;
  7242. }else{
  7243. rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
  7244. sqlite3_free(z);
  7245. }
  7246. }
  7247. switch( pWrite->eOp ){
  7248. case SQLITE_INSERT: {
  7249. int i;
  7250. zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
  7251. for(i=0; i<pTab->nCol; i++){
  7252. zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
  7253. }
  7254. zWrite = idxAppendText(&rc, zWrite, ")");
  7255. break;
  7256. }
  7257. case SQLITE_UPDATE: {
  7258. int i;
  7259. zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
  7260. for(i=0; i<pTab->nCol; i++){
  7261. zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
  7262. pTab->aCol[i].zName
  7263. );
  7264. }
  7265. break;
  7266. }
  7267. default: {
  7268. assert( pWrite->eOp==SQLITE_DELETE );
  7269. if( rc==SQLITE_OK ){
  7270. zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
  7271. if( zWrite==0 ) rc = SQLITE_NOMEM;
  7272. }
  7273. }
  7274. }
  7275. if( rc==SQLITE_OK ){
  7276. sqlite3_stmt *pX = 0;
  7277. rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
  7278. idxFinalize(&rc, pX);
  7279. if( rc!=SQLITE_OK ){
  7280. idxDatabaseError(p->dbv, pzErr);
  7281. }
  7282. }
  7283. sqlite3_free(zWrite);
  7284. if( rc==SQLITE_OK ){
  7285. rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
  7286. }
  7287. return rc;
  7288. }
  7289. static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
  7290. int rc = SQLITE_OK;
  7291. IdxWrite *pEnd = 0;
  7292. IdxWrite *pFirst = p->pWrite;
  7293. while( rc==SQLITE_OK && pFirst!=pEnd ){
  7294. IdxWrite *pIter;
  7295. for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
  7296. rc = idxProcessOneTrigger(p, pIter, pzErr);
  7297. }
  7298. pEnd = pFirst;
  7299. pFirst = p->pWrite;
  7300. }
  7301. return rc;
  7302. }
  7303. static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
  7304. int rc = idxRegisterVtab(p);
  7305. sqlite3_stmt *pSchema = 0;
  7306. /* For each table in the main db schema:
  7307. **
  7308. ** 1) Add an entry to the p->pTable list, and
  7309. ** 2) Create the equivalent virtual table in dbv.
  7310. */
  7311. rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
  7312. "SELECT type, name, sql, 1 FROM sqlite_master "
  7313. "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
  7314. " UNION ALL "
  7315. "SELECT type, name, sql, 2 FROM sqlite_master "
  7316. "WHERE type = 'trigger'"
  7317. " AND tbl_name IN(SELECT name FROM sqlite_master WHERE type = 'view') "
  7318. "ORDER BY 4, 1"
  7319. );
  7320. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
  7321. const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
  7322. const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
  7323. const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
  7324. if( zType[0]=='v' || zType[1]=='r' ){
  7325. rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
  7326. }else{
  7327. IdxTable *pTab;
  7328. rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
  7329. if( rc==SQLITE_OK ){
  7330. int i;
  7331. char *zInner = 0;
  7332. char *zOuter = 0;
  7333. pTab->pNext = p->pTable;
  7334. p->pTable = pTab;
  7335. /* The statement the vtab will pass to sqlite3_declare_vtab() */
  7336. zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
  7337. for(i=0; i<pTab->nCol; i++){
  7338. zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
  7339. (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
  7340. );
  7341. }
  7342. zInner = idxAppendText(&rc, zInner, ")");
  7343. /* The CVT statement to create the vtab */
  7344. zOuter = idxAppendText(&rc, 0,
  7345. "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
  7346. );
  7347. if( rc==SQLITE_OK ){
  7348. rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
  7349. }
  7350. sqlite3_free(zInner);
  7351. sqlite3_free(zOuter);
  7352. }
  7353. }
  7354. }
  7355. idxFinalize(&rc, pSchema);
  7356. return rc;
  7357. }
  7358. struct IdxSampleCtx {
  7359. int iTarget;
  7360. double target; /* Target nRet/nRow value */
  7361. double nRow; /* Number of rows seen */
  7362. double nRet; /* Number of rows returned */
  7363. };
  7364. static void idxSampleFunc(
  7365. sqlite3_context *pCtx,
  7366. int argc,
  7367. sqlite3_value **argv
  7368. ){
  7369. struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
  7370. int bRet;
  7371. (void)argv;
  7372. assert( argc==0 );
  7373. if( p->nRow==0.0 ){
  7374. bRet = 1;
  7375. }else{
  7376. bRet = (p->nRet / p->nRow) <= p->target;
  7377. if( bRet==0 ){
  7378. unsigned short rnd;
  7379. sqlite3_randomness(2, (void*)&rnd);
  7380. bRet = ((int)rnd % 100) <= p->iTarget;
  7381. }
  7382. }
  7383. sqlite3_result_int(pCtx, bRet);
  7384. p->nRow += 1.0;
  7385. p->nRet += (double)bRet;
  7386. }
  7387. struct IdxRemCtx {
  7388. int nSlot;
  7389. struct IdxRemSlot {
  7390. int eType; /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
  7391. i64 iVal; /* SQLITE_INTEGER value */
  7392. double rVal; /* SQLITE_FLOAT value */
  7393. int nByte; /* Bytes of space allocated at z */
  7394. int n; /* Size of buffer z */
  7395. char *z; /* SQLITE_TEXT/BLOB value */
  7396. } aSlot[1];
  7397. };
  7398. /*
  7399. ** Implementation of scalar function rem().
  7400. */
  7401. static void idxRemFunc(
  7402. sqlite3_context *pCtx,
  7403. int argc,
  7404. sqlite3_value **argv
  7405. ){
  7406. struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
  7407. struct IdxRemSlot *pSlot;
  7408. int iSlot;
  7409. assert( argc==2 );
  7410. iSlot = sqlite3_value_int(argv[0]);
  7411. assert( iSlot<=p->nSlot );
  7412. pSlot = &p->aSlot[iSlot];
  7413. switch( pSlot->eType ){
  7414. case SQLITE_NULL:
  7415. /* no-op */
  7416. break;
  7417. case SQLITE_INTEGER:
  7418. sqlite3_result_int64(pCtx, pSlot->iVal);
  7419. break;
  7420. case SQLITE_FLOAT:
  7421. sqlite3_result_double(pCtx, pSlot->rVal);
  7422. break;
  7423. case SQLITE_BLOB:
  7424. sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
  7425. break;
  7426. case SQLITE_TEXT:
  7427. sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
  7428. break;
  7429. }
  7430. pSlot->eType = sqlite3_value_type(argv[1]);
  7431. switch( pSlot->eType ){
  7432. case SQLITE_NULL:
  7433. /* no-op */
  7434. break;
  7435. case SQLITE_INTEGER:
  7436. pSlot->iVal = sqlite3_value_int64(argv[1]);
  7437. break;
  7438. case SQLITE_FLOAT:
  7439. pSlot->rVal = sqlite3_value_double(argv[1]);
  7440. break;
  7441. case SQLITE_BLOB:
  7442. case SQLITE_TEXT: {
  7443. int nByte = sqlite3_value_bytes(argv[1]);
  7444. if( nByte>pSlot->nByte ){
  7445. char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
  7446. if( zNew==0 ){
  7447. sqlite3_result_error_nomem(pCtx);
  7448. return;
  7449. }
  7450. pSlot->nByte = nByte*2;
  7451. pSlot->z = zNew;
  7452. }
  7453. pSlot->n = nByte;
  7454. if( pSlot->eType==SQLITE_BLOB ){
  7455. memcpy(pSlot->z, sqlite3_value_blob(argv[1]), nByte);
  7456. }else{
  7457. memcpy(pSlot->z, sqlite3_value_text(argv[1]), nByte);
  7458. }
  7459. break;
  7460. }
  7461. }
  7462. }
  7463. static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
  7464. int rc = SQLITE_OK;
  7465. const char *zMax =
  7466. "SELECT max(i.seqno) FROM "
  7467. " sqlite_master AS s, "
  7468. " pragma_index_list(s.name) AS l, "
  7469. " pragma_index_info(l.name) AS i "
  7470. "WHERE s.type = 'table'";
  7471. sqlite3_stmt *pMax = 0;
  7472. *pnMax = 0;
  7473. rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
  7474. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
  7475. *pnMax = sqlite3_column_int(pMax, 0) + 1;
  7476. }
  7477. idxFinalize(&rc, pMax);
  7478. return rc;
  7479. }
  7480. static int idxPopulateOneStat1(
  7481. sqlite3expert *p,
  7482. sqlite3_stmt *pIndexXInfo,
  7483. sqlite3_stmt *pWriteStat,
  7484. const char *zTab,
  7485. const char *zIdx,
  7486. char **pzErr
  7487. ){
  7488. char *zCols = 0;
  7489. char *zOrder = 0;
  7490. char *zQuery = 0;
  7491. int nCol = 0;
  7492. int i;
  7493. sqlite3_stmt *pQuery = 0;
  7494. int *aStat = 0;
  7495. int rc = SQLITE_OK;
  7496. assert( p->iSample>0 );
  7497. /* Formulate the query text */
  7498. sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
  7499. while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
  7500. const char *zComma = zCols==0 ? "" : ", ";
  7501. const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
  7502. const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
  7503. zCols = idxAppendText(&rc, zCols,
  7504. "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
  7505. );
  7506. zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
  7507. }
  7508. sqlite3_reset(pIndexXInfo);
  7509. if( rc==SQLITE_OK ){
  7510. if( p->iSample==100 ){
  7511. zQuery = sqlite3_mprintf(
  7512. "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
  7513. );
  7514. }else{
  7515. zQuery = sqlite3_mprintf(
  7516. "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
  7517. );
  7518. }
  7519. }
  7520. sqlite3_free(zCols);
  7521. sqlite3_free(zOrder);
  7522. /* Formulate the query text */
  7523. if( rc==SQLITE_OK ){
  7524. sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
  7525. rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
  7526. }
  7527. sqlite3_free(zQuery);
  7528. if( rc==SQLITE_OK ){
  7529. aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
  7530. }
  7531. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
  7532. IdxHashEntry *pEntry;
  7533. char *zStat = 0;
  7534. for(i=0; i<=nCol; i++) aStat[i] = 1;
  7535. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
  7536. aStat[0]++;
  7537. for(i=0; i<nCol; i++){
  7538. if( sqlite3_column_int(pQuery, i)==0 ) break;
  7539. }
  7540. for(/*no-op*/; i<nCol; i++){
  7541. aStat[i+1]++;
  7542. }
  7543. }
  7544. if( rc==SQLITE_OK ){
  7545. int s0 = aStat[0];
  7546. zStat = sqlite3_mprintf("%d", s0);
  7547. if( zStat==0 ) rc = SQLITE_NOMEM;
  7548. for(i=1; rc==SQLITE_OK && i<=nCol; i++){
  7549. zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
  7550. }
  7551. }
  7552. if( rc==SQLITE_OK ){
  7553. sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
  7554. sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
  7555. sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
  7556. sqlite3_step(pWriteStat);
  7557. rc = sqlite3_reset(pWriteStat);
  7558. }
  7559. pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
  7560. if( pEntry ){
  7561. assert( pEntry->zVal2==0 );
  7562. pEntry->zVal2 = zStat;
  7563. }else{
  7564. sqlite3_free(zStat);
  7565. }
  7566. }
  7567. sqlite3_free(aStat);
  7568. idxFinalize(&rc, pQuery);
  7569. return rc;
  7570. }
  7571. static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
  7572. int rc;
  7573. char *zSql;
  7574. rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
  7575. if( rc!=SQLITE_OK ) return rc;
  7576. zSql = sqlite3_mprintf(
  7577. "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
  7578. );
  7579. if( zSql==0 ) return SQLITE_NOMEM;
  7580. rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
  7581. sqlite3_free(zSql);
  7582. return rc;
  7583. }
  7584. /*
  7585. ** This function is called as part of sqlite3_expert_analyze(). Candidate
  7586. ** indexes have already been created in database sqlite3expert.dbm, this
  7587. ** function populates sqlite_stat1 table in the same database.
  7588. **
  7589. ** The stat1 data is generated by querying the
  7590. */
  7591. static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
  7592. int rc = SQLITE_OK;
  7593. int nMax =0;
  7594. struct IdxRemCtx *pCtx = 0;
  7595. struct IdxSampleCtx samplectx;
  7596. int i;
  7597. i64 iPrev = -100000;
  7598. sqlite3_stmt *pAllIndex = 0;
  7599. sqlite3_stmt *pIndexXInfo = 0;
  7600. sqlite3_stmt *pWrite = 0;
  7601. const char *zAllIndex =
  7602. "SELECT s.rowid, s.name, l.name FROM "
  7603. " sqlite_master AS s, "
  7604. " pragma_index_list(s.name) AS l "
  7605. "WHERE s.type = 'table'";
  7606. const char *zIndexXInfo =
  7607. "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
  7608. const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
  7609. /* If iSample==0, no sqlite_stat1 data is required. */
  7610. if( p->iSample==0 ) return SQLITE_OK;
  7611. rc = idxLargestIndex(p->dbm, &nMax, pzErr);
  7612. if( nMax<=0 || rc!=SQLITE_OK ) return rc;
  7613. rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
  7614. if( rc==SQLITE_OK ){
  7615. int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
  7616. pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
  7617. }
  7618. if( rc==SQLITE_OK ){
  7619. sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
  7620. rc = sqlite3_create_function(
  7621. dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
  7622. );
  7623. }
  7624. if( rc==SQLITE_OK ){
  7625. rc = sqlite3_create_function(
  7626. p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
  7627. );
  7628. }
  7629. if( rc==SQLITE_OK ){
  7630. pCtx->nSlot = nMax+1;
  7631. rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
  7632. }
  7633. if( rc==SQLITE_OK ){
  7634. rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
  7635. }
  7636. if( rc==SQLITE_OK ){
  7637. rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
  7638. }
  7639. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
  7640. i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
  7641. const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
  7642. const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
  7643. if( p->iSample<100 && iPrev!=iRowid ){
  7644. samplectx.target = (double)p->iSample / 100.0;
  7645. samplectx.iTarget = p->iSample;
  7646. samplectx.nRow = 0.0;
  7647. samplectx.nRet = 0.0;
  7648. rc = idxBuildSampleTable(p, zTab);
  7649. if( rc!=SQLITE_OK ) break;
  7650. }
  7651. rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
  7652. iPrev = iRowid;
  7653. }
  7654. if( rc==SQLITE_OK && p->iSample<100 ){
  7655. rc = sqlite3_exec(p->dbv,
  7656. "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
  7657. );
  7658. }
  7659. idxFinalize(&rc, pAllIndex);
  7660. idxFinalize(&rc, pIndexXInfo);
  7661. idxFinalize(&rc, pWrite);
  7662. for(i=0; i<pCtx->nSlot; i++){
  7663. sqlite3_free(pCtx->aSlot[i].z);
  7664. }
  7665. sqlite3_free(pCtx);
  7666. if( rc==SQLITE_OK ){
  7667. rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_master", 0, 0, 0);
  7668. }
  7669. sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
  7670. return rc;
  7671. }
  7672. /*
  7673. ** Allocate a new sqlite3expert object.
  7674. */
  7675. sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
  7676. int rc = SQLITE_OK;
  7677. sqlite3expert *pNew;
  7678. pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
  7679. /* Open two in-memory databases to work with. The "vtab database" (dbv)
  7680. ** will contain a virtual table corresponding to each real table in
  7681. ** the user database schema, and a copy of each view. It is used to
  7682. ** collect information regarding the WHERE, ORDER BY and other clauses
  7683. ** of the user's query.
  7684. */
  7685. if( rc==SQLITE_OK ){
  7686. pNew->db = db;
  7687. pNew->iSample = 100;
  7688. rc = sqlite3_open(":memory:", &pNew->dbv);
  7689. }
  7690. if( rc==SQLITE_OK ){
  7691. rc = sqlite3_open(":memory:", &pNew->dbm);
  7692. if( rc==SQLITE_OK ){
  7693. sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
  7694. }
  7695. }
  7696. /* Copy the entire schema of database [db] into [dbm]. */
  7697. if( rc==SQLITE_OK ){
  7698. sqlite3_stmt *pSql;
  7699. rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
  7700. "SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%%'"
  7701. " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
  7702. );
  7703. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  7704. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  7705. rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
  7706. }
  7707. idxFinalize(&rc, pSql);
  7708. }
  7709. /* Create the vtab schema */
  7710. if( rc==SQLITE_OK ){
  7711. rc = idxCreateVtabSchema(pNew, pzErrmsg);
  7712. }
  7713. /* Register the auth callback with dbv */
  7714. if( rc==SQLITE_OK ){
  7715. sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
  7716. }
  7717. /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
  7718. ** return the new sqlite3expert handle. */
  7719. if( rc!=SQLITE_OK ){
  7720. sqlite3_expert_destroy(pNew);
  7721. pNew = 0;
  7722. }
  7723. return pNew;
  7724. }
  7725. /*
  7726. ** Configure an sqlite3expert object.
  7727. */
  7728. int sqlite3_expert_config(sqlite3expert *p, int op, ...){
  7729. int rc = SQLITE_OK;
  7730. va_list ap;
  7731. va_start(ap, op);
  7732. switch( op ){
  7733. case EXPERT_CONFIG_SAMPLE: {
  7734. int iVal = va_arg(ap, int);
  7735. if( iVal<0 ) iVal = 0;
  7736. if( iVal>100 ) iVal = 100;
  7737. p->iSample = iVal;
  7738. break;
  7739. }
  7740. default:
  7741. rc = SQLITE_NOTFOUND;
  7742. break;
  7743. }
  7744. va_end(ap);
  7745. return rc;
  7746. }
  7747. /*
  7748. ** Add an SQL statement to the analysis.
  7749. */
  7750. int sqlite3_expert_sql(
  7751. sqlite3expert *p, /* From sqlite3_expert_new() */
  7752. const char *zSql, /* SQL statement to add */
  7753. char **pzErr /* OUT: Error message (if any) */
  7754. ){
  7755. IdxScan *pScanOrig = p->pScan;
  7756. IdxStatement *pStmtOrig = p->pStatement;
  7757. int rc = SQLITE_OK;
  7758. const char *zStmt = zSql;
  7759. if( p->bRun ) return SQLITE_MISUSE;
  7760. while( rc==SQLITE_OK && zStmt && zStmt[0] ){
  7761. sqlite3_stmt *pStmt = 0;
  7762. rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
  7763. if( rc==SQLITE_OK ){
  7764. if( pStmt ){
  7765. IdxStatement *pNew;
  7766. const char *z = sqlite3_sql(pStmt);
  7767. int n = STRLEN(z);
  7768. pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
  7769. if( rc==SQLITE_OK ){
  7770. pNew->zSql = (char*)&pNew[1];
  7771. memcpy(pNew->zSql, z, n+1);
  7772. pNew->pNext = p->pStatement;
  7773. if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
  7774. p->pStatement = pNew;
  7775. }
  7776. sqlite3_finalize(pStmt);
  7777. }
  7778. }else{
  7779. idxDatabaseError(p->dbv, pzErr);
  7780. }
  7781. }
  7782. if( rc!=SQLITE_OK ){
  7783. idxScanFree(p->pScan, pScanOrig);
  7784. idxStatementFree(p->pStatement, pStmtOrig);
  7785. p->pScan = pScanOrig;
  7786. p->pStatement = pStmtOrig;
  7787. }
  7788. return rc;
  7789. }
  7790. int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
  7791. int rc;
  7792. IdxHashEntry *pEntry;
  7793. /* Do trigger processing to collect any extra IdxScan structures */
  7794. rc = idxProcessTriggers(p, pzErr);
  7795. /* Create candidate indexes within the in-memory database file */
  7796. if( rc==SQLITE_OK ){
  7797. rc = idxCreateCandidates(p);
  7798. }
  7799. /* Generate the stat1 data */
  7800. if( rc==SQLITE_OK ){
  7801. rc = idxPopulateStat1(p, pzErr);
  7802. }
  7803. /* Formulate the EXPERT_REPORT_CANDIDATES text */
  7804. for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
  7805. p->zCandidates = idxAppendText(&rc, p->zCandidates,
  7806. "%s;%s%s\n", pEntry->zVal,
  7807. pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
  7808. );
  7809. }
  7810. /* Figure out which of the candidate indexes are preferred by the query
  7811. ** planner and report the results to the user. */
  7812. if( rc==SQLITE_OK ){
  7813. rc = idxFindIndexes(p, pzErr);
  7814. }
  7815. if( rc==SQLITE_OK ){
  7816. p->bRun = 1;
  7817. }
  7818. return rc;
  7819. }
  7820. /*
  7821. ** Return the total number of statements that have been added to this
  7822. ** sqlite3expert using sqlite3_expert_sql().
  7823. */
  7824. int sqlite3_expert_count(sqlite3expert *p){
  7825. int nRet = 0;
  7826. if( p->pStatement ) nRet = p->pStatement->iId+1;
  7827. return nRet;
  7828. }
  7829. /*
  7830. ** Return a component of the report.
  7831. */
  7832. const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
  7833. const char *zRet = 0;
  7834. IdxStatement *pStmt;
  7835. if( p->bRun==0 ) return 0;
  7836. for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
  7837. switch( eReport ){
  7838. case EXPERT_REPORT_SQL:
  7839. if( pStmt ) zRet = pStmt->zSql;
  7840. break;
  7841. case EXPERT_REPORT_INDEXES:
  7842. if( pStmt ) zRet = pStmt->zIdx;
  7843. break;
  7844. case EXPERT_REPORT_PLAN:
  7845. if( pStmt ) zRet = pStmt->zEQP;
  7846. break;
  7847. case EXPERT_REPORT_CANDIDATES:
  7848. zRet = p->zCandidates;
  7849. break;
  7850. }
  7851. return zRet;
  7852. }
  7853. /*
  7854. ** Free an sqlite3expert object.
  7855. */
  7856. void sqlite3_expert_destroy(sqlite3expert *p){
  7857. if( p ){
  7858. sqlite3_close(p->dbm);
  7859. sqlite3_close(p->dbv);
  7860. idxScanFree(p->pScan, 0);
  7861. idxStatementFree(p->pStatement, 0);
  7862. idxTableFree(p->pTable);
  7863. idxWriteFree(p->pWrite);
  7864. idxHashClear(&p->hIdx);
  7865. sqlite3_free(p->zCandidates);
  7866. sqlite3_free(p);
  7867. }
  7868. }
  7869. #endif /* ifndef SQLITE_OMIT_VIRTUAL_TABLE */
  7870. /************************* End ../ext/expert/sqlite3expert.c ********************/
  7871. #if defined(SQLITE_ENABLE_SESSION)
  7872. /*
  7873. ** State information for a single open session
  7874. */
  7875. typedef struct OpenSession OpenSession;
  7876. struct OpenSession {
  7877. char *zName; /* Symbolic name for this session */
  7878. int nFilter; /* Number of xFilter rejection GLOB patterns */
  7879. char **azFilter; /* Array of xFilter rejection GLOB patterns */
  7880. sqlite3_session *p; /* The open session */
  7881. };
  7882. #endif
  7883. /*
  7884. ** Shell output mode information from before ".explain on",
  7885. ** saved so that it can be restored by ".explain off"
  7886. */
  7887. typedef struct SavedModeInfo SavedModeInfo;
  7888. struct SavedModeInfo {
  7889. int valid; /* Is there legit data in here? */
  7890. int mode; /* Mode prior to ".explain on" */
  7891. int showHeader; /* The ".header" setting prior to ".explain on" */
  7892. int colWidth[100]; /* Column widths prior to ".explain on" */
  7893. };
  7894. typedef struct ExpertInfo ExpertInfo;
  7895. struct ExpertInfo {
  7896. sqlite3expert *pExpert;
  7897. int bVerbose;
  7898. };
  7899. /* A single line in the EQP output */
  7900. typedef struct EQPGraphRow EQPGraphRow;
  7901. struct EQPGraphRow {
  7902. int iEqpId; /* ID for this row */
  7903. int iParentId; /* ID of the parent row */
  7904. EQPGraphRow *pNext; /* Next row in sequence */
  7905. char zText[1]; /* Text to display for this row */
  7906. };
  7907. /* All EQP output is collected into an instance of the following */
  7908. typedef struct EQPGraph EQPGraph;
  7909. struct EQPGraph {
  7910. EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
  7911. EQPGraphRow *pLast; /* Last element of the pRow list */
  7912. char zPrefix[100]; /* Graph prefix */
  7913. };
  7914. /*
  7915. ** State information about the database connection is contained in an
  7916. ** instance of the following structure.
  7917. */
  7918. typedef struct ShellState ShellState;
  7919. struct ShellState {
  7920. sqlite3 *db; /* The database */
  7921. u8 autoExplain; /* Automatically turn on .explain mode */
  7922. u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
  7923. u8 autoEQPtest; /* autoEQP is in test mode */
  7924. u8 autoEQPtrace; /* autoEQP is in trace mode */
  7925. u8 statsOn; /* True to display memory stats before each finalize */
  7926. u8 scanstatsOn; /* True to display scan stats before each finalize */
  7927. u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
  7928. u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
  7929. u8 nEqpLevel; /* Depth of the EQP output graph */
  7930. u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
  7931. unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
  7932. int outCount; /* Revert to stdout when reaching zero */
  7933. int cnt; /* Number of records displayed so far */
  7934. int lineno; /* Line number of last line read from in */
  7935. FILE *in; /* Read commands from this stream */
  7936. FILE *out; /* Write results here */
  7937. FILE *traceOut; /* Output for sqlite3_trace() */
  7938. int nErr; /* Number of errors seen */
  7939. int mode; /* An output mode setting */
  7940. int modePrior; /* Saved mode */
  7941. int cMode; /* temporary output mode for the current query */
  7942. int normalMode; /* Output mode before ".explain on" */
  7943. int writableSchema; /* True if PRAGMA writable_schema=ON */
  7944. int showHeader; /* True to show column names in List or Column mode */
  7945. int nCheck; /* Number of ".check" commands run */
  7946. unsigned nProgress; /* Number of progress callbacks encountered */
  7947. unsigned mxProgress; /* Maximum progress callbacks before failing */
  7948. unsigned flgProgress; /* Flags for the progress callback */
  7949. unsigned shellFlgs; /* Various flags */
  7950. sqlite3_int64 szMax; /* --maxsize argument to .open */
  7951. char *zDestTable; /* Name of destination table when MODE_Insert */
  7952. char *zTempFile; /* Temporary file that might need deleting */
  7953. char zTestcase[30]; /* Name of current test case */
  7954. char colSeparator[20]; /* Column separator character for several modes */
  7955. char rowSeparator[20]; /* Row separator character for MODE_Ascii */
  7956. char colSepPrior[20]; /* Saved column separator */
  7957. char rowSepPrior[20]; /* Saved row separator */
  7958. int colWidth[100]; /* Requested width of each column when in column mode*/
  7959. int actualWidth[100]; /* Actual width of each column */
  7960. char nullValue[20]; /* The text to print when a NULL comes back from
  7961. ** the database */
  7962. char outfile[FILENAME_MAX]; /* Filename for *out */
  7963. const char *zDbFilename; /* name of the database file */
  7964. char *zFreeOnClose; /* Filename to free when closing */
  7965. const char *zVfs; /* Name of VFS to use */
  7966. sqlite3_stmt *pStmt; /* Current statement if any. */
  7967. FILE *pLog; /* Write log output here */
  7968. int *aiIndent; /* Array of indents used in MODE_Explain */
  7969. int nIndent; /* Size of array aiIndent[] */
  7970. int iIndent; /* Index of current op in aiIndent[] */
  7971. EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
  7972. #if defined(SQLITE_ENABLE_SESSION)
  7973. int nSession; /* Number of active sessions */
  7974. OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
  7975. #endif
  7976. ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
  7977. };
  7978. /* Allowed values for ShellState.autoEQP
  7979. */
  7980. #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
  7981. #define AUTOEQP_on 1 /* Automatic EQP is on */
  7982. #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
  7983. #define AUTOEQP_full 3 /* Show full EXPLAIN */
  7984. /* Allowed values for ShellState.openMode
  7985. */
  7986. #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
  7987. #define SHELL_OPEN_NORMAL 1 /* Normal database file */
  7988. #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
  7989. #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
  7990. #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
  7991. #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
  7992. #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
  7993. /* Allowed values for ShellState.eTraceType
  7994. */
  7995. #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
  7996. #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
  7997. #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
  7998. /* Bits in the ShellState.flgProgress variable */
  7999. #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
  8000. #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
  8001. ** callback limit is reached, and for each
  8002. ** top-level SQL statement */
  8003. #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
  8004. /*
  8005. ** These are the allowed shellFlgs values
  8006. */
  8007. #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
  8008. #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
  8009. #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
  8010. #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
  8011. #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
  8012. #define SHFLG_CountChanges 0x00000020 /* .changes setting */
  8013. #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
  8014. /*
  8015. ** Macros for testing and setting shellFlgs
  8016. */
  8017. #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
  8018. #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
  8019. #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
  8020. /*
  8021. ** These are the allowed modes.
  8022. */
  8023. #define MODE_Line 0 /* One column per line. Blank line between records */
  8024. #define MODE_Column 1 /* One record per line in neat columns */
  8025. #define MODE_List 2 /* One record per line with a separator */
  8026. #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
  8027. #define MODE_Html 4 /* Generate an XHTML table */
  8028. #define MODE_Insert 5 /* Generate SQL "insert" statements */
  8029. #define MODE_Quote 6 /* Quote values as for SQL */
  8030. #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
  8031. #define MODE_Csv 8 /* Quote strings, numbers are plain */
  8032. #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
  8033. #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
  8034. #define MODE_Pretty 11 /* Pretty-print schemas */
  8035. #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
  8036. static const char *modeDescr[] = {
  8037. "line",
  8038. "column",
  8039. "list",
  8040. "semi",
  8041. "html",
  8042. "insert",
  8043. "quote",
  8044. "tcl",
  8045. "csv",
  8046. "explain",
  8047. "ascii",
  8048. "prettyprint",
  8049. "eqp"
  8050. };
  8051. /*
  8052. ** These are the column/row/line separators used by the various
  8053. ** import/export modes.
  8054. */
  8055. #define SEP_Column "|"
  8056. #define SEP_Row "\n"
  8057. #define SEP_Tab "\t"
  8058. #define SEP_Space " "
  8059. #define SEP_Comma ","
  8060. #define SEP_CrLf "\r\n"
  8061. #define SEP_Unit "\x1F"
  8062. #define SEP_Record "\x1E"
  8063. /*
  8064. ** A callback for the sqlite3_log() interface.
  8065. */
  8066. static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  8067. ShellState *p = (ShellState*)pArg;
  8068. if( p->pLog==0 ) return;
  8069. utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  8070. fflush(p->pLog);
  8071. }
  8072. /*
  8073. ** SQL function: shell_putsnl(X)
  8074. **
  8075. ** Write the text X to the screen (or whatever output is being directed)
  8076. ** adding a newline at the end, and then return X.
  8077. */
  8078. static void shellPutsFunc(
  8079. sqlite3_context *pCtx,
  8080. int nVal,
  8081. sqlite3_value **apVal
  8082. ){
  8083. ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
  8084. (void)nVal;
  8085. utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
  8086. sqlite3_result_value(pCtx, apVal[0]);
  8087. }
  8088. /*
  8089. ** SQL function: edit(VALUE)
  8090. ** edit(VALUE,EDITOR)
  8091. **
  8092. ** These steps:
  8093. **
  8094. ** (1) Write VALUE into a temporary file.
  8095. ** (2) Run program EDITOR on that temporary file.
  8096. ** (3) Read the temporary file back and return its content as the result.
  8097. ** (4) Delete the temporary file
  8098. **
  8099. ** If the EDITOR argument is omitted, use the value in the VISUAL
  8100. ** environment variable. If still there is no EDITOR, through an error.
  8101. **
  8102. ** Also throw an error if the EDITOR program returns a non-zero exit code.
  8103. */
  8104. #ifndef SQLITE_NOHAVE_SYSTEM
  8105. static void editFunc(
  8106. sqlite3_context *context,
  8107. int argc,
  8108. sqlite3_value **argv
  8109. ){
  8110. const char *zEditor;
  8111. char *zTempFile = 0;
  8112. sqlite3 *db;
  8113. char *zCmd = 0;
  8114. int bBin;
  8115. int rc;
  8116. int hasCRNL = 0;
  8117. FILE *f = 0;
  8118. sqlite3_int64 sz;
  8119. sqlite3_int64 x;
  8120. unsigned char *p = 0;
  8121. if( argc==2 ){
  8122. zEditor = (const char*)sqlite3_value_text(argv[1]);
  8123. }else{
  8124. zEditor = getenv("VISUAL");
  8125. }
  8126. if( zEditor==0 ){
  8127. sqlite3_result_error(context, "no editor for edit()", -1);
  8128. return;
  8129. }
  8130. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  8131. sqlite3_result_error(context, "NULL input to edit()", -1);
  8132. return;
  8133. }
  8134. db = sqlite3_context_db_handle(context);
  8135. zTempFile = 0;
  8136. sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
  8137. if( zTempFile==0 ){
  8138. sqlite3_uint64 r = 0;
  8139. sqlite3_randomness(sizeof(r), &r);
  8140. zTempFile = sqlite3_mprintf("temp%llx", r);
  8141. if( zTempFile==0 ){
  8142. sqlite3_result_error_nomem(context);
  8143. return;
  8144. }
  8145. }
  8146. bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
  8147. /* When writing the file to be edited, do \n to \r\n conversions on systems
  8148. ** that want \r\n line endings */
  8149. f = fopen(zTempFile, bBin ? "wb" : "w");
  8150. if( f==0 ){
  8151. sqlite3_result_error(context, "edit() cannot open temp file", -1);
  8152. goto edit_func_end;
  8153. }
  8154. sz = sqlite3_value_bytes(argv[0]);
  8155. if( bBin ){
  8156. x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
  8157. }else{
  8158. const char *z = (const char*)sqlite3_value_text(argv[0]);
  8159. /* Remember whether or not the value originally contained \r\n */
  8160. if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
  8161. x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
  8162. }
  8163. fclose(f);
  8164. f = 0;
  8165. if( x!=sz ){
  8166. sqlite3_result_error(context, "edit() could not write the whole file", -1);
  8167. goto edit_func_end;
  8168. }
  8169. zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
  8170. if( zCmd==0 ){
  8171. sqlite3_result_error_nomem(context);
  8172. goto edit_func_end;
  8173. }
  8174. rc = system(zCmd);
  8175. sqlite3_free(zCmd);
  8176. if( rc ){
  8177. sqlite3_result_error(context, "EDITOR returned non-zero", -1);
  8178. goto edit_func_end;
  8179. }
  8180. f = fopen(zTempFile, "rb");
  8181. if( f==0 ){
  8182. sqlite3_result_error(context,
  8183. "edit() cannot reopen temp file after edit", -1);
  8184. goto edit_func_end;
  8185. }
  8186. fseek(f, 0, SEEK_END);
  8187. sz = ftell(f);
  8188. rewind(f);
  8189. p = sqlite3_malloc64( sz+(bBin==0) );
  8190. if( p==0 ){
  8191. sqlite3_result_error_nomem(context);
  8192. goto edit_func_end;
  8193. }
  8194. x = fread(p, 1, sz, f);
  8195. fclose(f);
  8196. f = 0;
  8197. if( x!=sz ){
  8198. sqlite3_result_error(context, "could not read back the whole file", -1);
  8199. goto edit_func_end;
  8200. }
  8201. if( bBin ){
  8202. sqlite3_result_blob64(context, p, sz, sqlite3_free);
  8203. }else{
  8204. sqlite3_int64 i, j;
  8205. if( hasCRNL ){
  8206. /* If the original contains \r\n then do no conversions back to \n */
  8207. j = sz;
  8208. }else{
  8209. /* If the file did not originally contain \r\n then convert any new
  8210. ** \r\n back into \n */
  8211. for(i=j=0; i<sz; i++){
  8212. if( p[i]=='\r' && p[i+1]=='\n' ) i++;
  8213. p[j++] = p[i];
  8214. }
  8215. sz = j;
  8216. p[sz] = 0;
  8217. }
  8218. sqlite3_result_text64(context, (const char*)p, sz,
  8219. sqlite3_free, SQLITE_UTF8);
  8220. }
  8221. p = 0;
  8222. edit_func_end:
  8223. if( f ) fclose(f);
  8224. unlink(zTempFile);
  8225. sqlite3_free(zTempFile);
  8226. sqlite3_free(p);
  8227. }
  8228. #endif /* SQLITE_NOHAVE_SYSTEM */
  8229. /*
  8230. ** Save or restore the current output mode
  8231. */
  8232. static void outputModePush(ShellState *p){
  8233. p->modePrior = p->mode;
  8234. memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
  8235. memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
  8236. }
  8237. static void outputModePop(ShellState *p){
  8238. p->mode = p->modePrior;
  8239. memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
  8240. memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
  8241. }
  8242. /*
  8243. ** Output the given string as a hex-encoded blob (eg. X'1234' )
  8244. */
  8245. static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  8246. int i;
  8247. char *zBlob = (char *)pBlob;
  8248. raw_printf(out,"X'");
  8249. for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
  8250. raw_printf(out,"'");
  8251. }
  8252. /*
  8253. ** Find a string that is not found anywhere in z[]. Return a pointer
  8254. ** to that string.
  8255. **
  8256. ** Try to use zA and zB first. If both of those are already found in z[]
  8257. ** then make up some string and store it in the buffer zBuf.
  8258. */
  8259. static const char *unused_string(
  8260. const char *z, /* Result must not appear anywhere in z */
  8261. const char *zA, const char *zB, /* Try these first */
  8262. char *zBuf /* Space to store a generated string */
  8263. ){
  8264. unsigned i = 0;
  8265. if( strstr(z, zA)==0 ) return zA;
  8266. if( strstr(z, zB)==0 ) return zB;
  8267. do{
  8268. sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
  8269. }while( strstr(z,zBuf)!=0 );
  8270. return zBuf;
  8271. }
  8272. /*
  8273. ** Output the given string as a quoted string using SQL quoting conventions.
  8274. **
  8275. ** See also: output_quoted_escaped_string()
  8276. */
  8277. static void output_quoted_string(FILE *out, const char *z){
  8278. int i;
  8279. char c;
  8280. setBinaryMode(out, 1);
  8281. for(i=0; (c = z[i])!=0 && c!='\''; i++){}
  8282. if( c==0 ){
  8283. utf8_printf(out,"'%s'",z);
  8284. }else{
  8285. raw_printf(out, "'");
  8286. while( *z ){
  8287. for(i=0; (c = z[i])!=0 && c!='\''; i++){}
  8288. if( c=='\'' ) i++;
  8289. if( i ){
  8290. utf8_printf(out, "%.*s", i, z);
  8291. z += i;
  8292. }
  8293. if( c=='\'' ){
  8294. raw_printf(out, "'");
  8295. continue;
  8296. }
  8297. if( c==0 ){
  8298. break;
  8299. }
  8300. z++;
  8301. }
  8302. raw_printf(out, "'");
  8303. }
  8304. setTextMode(out, 1);
  8305. }
  8306. /*
  8307. ** Output the given string as a quoted string using SQL quoting conventions.
  8308. ** Additionallly , escape the "\n" and "\r" characters so that they do not
  8309. ** get corrupted by end-of-line translation facilities in some operating
  8310. ** systems.
  8311. **
  8312. ** This is like output_quoted_string() but with the addition of the \r\n
  8313. ** escape mechanism.
  8314. */
  8315. static void output_quoted_escaped_string(FILE *out, const char *z){
  8316. int i;
  8317. char c;
  8318. setBinaryMode(out, 1);
  8319. for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
  8320. if( c==0 ){
  8321. utf8_printf(out,"'%s'",z);
  8322. }else{
  8323. const char *zNL = 0;
  8324. const char *zCR = 0;
  8325. int nNL = 0;
  8326. int nCR = 0;
  8327. char zBuf1[20], zBuf2[20];
  8328. for(i=0; z[i]; i++){
  8329. if( z[i]=='\n' ) nNL++;
  8330. if( z[i]=='\r' ) nCR++;
  8331. }
  8332. if( nNL ){
  8333. raw_printf(out, "replace(");
  8334. zNL = unused_string(z, "\\n", "\\012", zBuf1);
  8335. }
  8336. if( nCR ){
  8337. raw_printf(out, "replace(");
  8338. zCR = unused_string(z, "\\r", "\\015", zBuf2);
  8339. }
  8340. raw_printf(out, "'");
  8341. while( *z ){
  8342. for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
  8343. if( c=='\'' ) i++;
  8344. if( i ){
  8345. utf8_printf(out, "%.*s", i, z);
  8346. z += i;
  8347. }
  8348. if( c=='\'' ){
  8349. raw_printf(out, "'");
  8350. continue;
  8351. }
  8352. if( c==0 ){
  8353. break;
  8354. }
  8355. z++;
  8356. if( c=='\n' ){
  8357. raw_printf(out, "%s", zNL);
  8358. continue;
  8359. }
  8360. raw_printf(out, "%s", zCR);
  8361. }
  8362. raw_printf(out, "'");
  8363. if( nCR ){
  8364. raw_printf(out, ",'%s',char(13))", zCR);
  8365. }
  8366. if( nNL ){
  8367. raw_printf(out, ",'%s',char(10))", zNL);
  8368. }
  8369. }
  8370. setTextMode(out, 1);
  8371. }
  8372. /*
  8373. ** Output the given string as a quoted according to C or TCL quoting rules.
  8374. */
  8375. static void output_c_string(FILE *out, const char *z){
  8376. unsigned int c;
  8377. fputc('"', out);
  8378. while( (c = *(z++))!=0 ){
  8379. if( c=='\\' ){
  8380. fputc(c, out);
  8381. fputc(c, out);
  8382. }else if( c=='"' ){
  8383. fputc('\\', out);
  8384. fputc('"', out);
  8385. }else if( c=='\t' ){
  8386. fputc('\\', out);
  8387. fputc('t', out);
  8388. }else if( c=='\n' ){
  8389. fputc('\\', out);
  8390. fputc('n', out);
  8391. }else if( c=='\r' ){
  8392. fputc('\\', out);
  8393. fputc('r', out);
  8394. }else if( !isprint(c&0xff) ){
  8395. raw_printf(out, "\\%03o", c&0xff);
  8396. }else{
  8397. fputc(c, out);
  8398. }
  8399. }
  8400. fputc('"', out);
  8401. }
  8402. /*
  8403. ** Output the given string with characters that are special to
  8404. ** HTML escaped.
  8405. */
  8406. static void output_html_string(FILE *out, const char *z){
  8407. int i;
  8408. if( z==0 ) z = "";
  8409. while( *z ){
  8410. for(i=0; z[i]
  8411. && z[i]!='<'
  8412. && z[i]!='&'
  8413. && z[i]!='>'
  8414. && z[i]!='\"'
  8415. && z[i]!='\'';
  8416. i++){}
  8417. if( i>0 ){
  8418. utf8_printf(out,"%.*s",i,z);
  8419. }
  8420. if( z[i]=='<' ){
  8421. raw_printf(out,"&lt;");
  8422. }else if( z[i]=='&' ){
  8423. raw_printf(out,"&amp;");
  8424. }else if( z[i]=='>' ){
  8425. raw_printf(out,"&gt;");
  8426. }else if( z[i]=='\"' ){
  8427. raw_printf(out,"&quot;");
  8428. }else if( z[i]=='\'' ){
  8429. raw_printf(out,"&#39;");
  8430. }else{
  8431. break;
  8432. }
  8433. z += i + 1;
  8434. }
  8435. }
  8436. /*
  8437. ** If a field contains any character identified by a 1 in the following
  8438. ** array, then the string must be quoted for CSV.
  8439. */
  8440. static const char needCsvQuote[] = {
  8441. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8442. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8443. 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  8444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  8445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  8446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  8447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  8448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  8449. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8450. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8451. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8452. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8453. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8454. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8455. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8456. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8457. };
  8458. /*
  8459. ** Output a single term of CSV. Actually, p->colSeparator is used for
  8460. ** the separator, which may or may not be a comma. p->nullValue is
  8461. ** the null value. Strings are quoted if necessary. The separator
  8462. ** is only issued if bSep is true.
  8463. */
  8464. static void output_csv(ShellState *p, const char *z, int bSep){
  8465. FILE *out = p->out;
  8466. if( z==0 ){
  8467. utf8_printf(out,"%s",p->nullValue);
  8468. }else{
  8469. int i;
  8470. int nSep = strlen30(p->colSeparator);
  8471. for(i=0; z[i]; i++){
  8472. if( needCsvQuote[((unsigned char*)z)[i]]
  8473. || (z[i]==p->colSeparator[0] &&
  8474. (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
  8475. i = 0;
  8476. break;
  8477. }
  8478. }
  8479. if( i==0 ){
  8480. char *zQuoted = sqlite3_mprintf("\"%w\"", z);
  8481. utf8_printf(out, "%s", zQuoted);
  8482. sqlite3_free(zQuoted);
  8483. }else{
  8484. utf8_printf(out, "%s", z);
  8485. }
  8486. }
  8487. if( bSep ){
  8488. utf8_printf(p->out, "%s", p->colSeparator);
  8489. }
  8490. }
  8491. /*
  8492. ** This routine runs when the user presses Ctrl-C
  8493. */
  8494. static void interrupt_handler(int NotUsed){
  8495. UNUSED_PARAMETER(NotUsed);
  8496. seenInterrupt++;
  8497. if( seenInterrupt>2 ) exit(1);
  8498. if( globalDb ) sqlite3_interrupt(globalDb);
  8499. }
  8500. #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
  8501. /*
  8502. ** This routine runs for console events (e.g. Ctrl-C) on Win32
  8503. */
  8504. static BOOL WINAPI ConsoleCtrlHandler(
  8505. DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
  8506. ){
  8507. if( dwCtrlType==CTRL_C_EVENT ){
  8508. interrupt_handler(0);
  8509. return TRUE;
  8510. }
  8511. return FALSE;
  8512. }
  8513. #endif
  8514. #ifndef SQLITE_OMIT_AUTHORIZATION
  8515. /*
  8516. ** When the ".auth ON" is set, the following authorizer callback is
  8517. ** invoked. It always returns SQLITE_OK.
  8518. */
  8519. static int shellAuth(
  8520. void *pClientData,
  8521. int op,
  8522. const char *zA1,
  8523. const char *zA2,
  8524. const char *zA3,
  8525. const char *zA4
  8526. ){
  8527. ShellState *p = (ShellState*)pClientData;
  8528. static const char *azAction[] = { 0,
  8529. "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
  8530. "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
  8531. "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
  8532. "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
  8533. "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
  8534. "DROP_TRIGGER", "DROP_VIEW", "INSERT",
  8535. "PRAGMA", "READ", "SELECT",
  8536. "TRANSACTION", "UPDATE", "ATTACH",
  8537. "DETACH", "ALTER_TABLE", "REINDEX",
  8538. "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
  8539. "FUNCTION", "SAVEPOINT", "RECURSIVE"
  8540. };
  8541. int i;
  8542. const char *az[4];
  8543. az[0] = zA1;
  8544. az[1] = zA2;
  8545. az[2] = zA3;
  8546. az[3] = zA4;
  8547. utf8_printf(p->out, "authorizer: %s", azAction[op]);
  8548. for(i=0; i<4; i++){
  8549. raw_printf(p->out, " ");
  8550. if( az[i] ){
  8551. output_c_string(p->out, az[i]);
  8552. }else{
  8553. raw_printf(p->out, "NULL");
  8554. }
  8555. }
  8556. raw_printf(p->out, "\n");
  8557. return SQLITE_OK;
  8558. }
  8559. #endif
  8560. /*
  8561. ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
  8562. **
  8563. ** This routine converts some CREATE TABLE statements for shadow tables
  8564. ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
  8565. */
  8566. static void printSchemaLine(FILE *out, const char *z, const char *zTail){
  8567. if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
  8568. utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
  8569. }else{
  8570. utf8_printf(out, "%s%s", z, zTail);
  8571. }
  8572. }
  8573. static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
  8574. char c = z[n];
  8575. z[n] = 0;
  8576. printSchemaLine(out, z, zTail);
  8577. z[n] = c;
  8578. }
  8579. /*
  8580. ** Return true if string z[] has nothing but whitespace and comments to the
  8581. ** end of the first line.
  8582. */
  8583. static int wsToEol(const char *z){
  8584. int i;
  8585. for(i=0; z[i]; i++){
  8586. if( z[i]=='\n' ) return 1;
  8587. if( IsSpace(z[i]) ) continue;
  8588. if( z[i]=='-' && z[i+1]=='-' ) return 1;
  8589. return 0;
  8590. }
  8591. return 1;
  8592. }
  8593. /*
  8594. ** Add a new entry to the EXPLAIN QUERY PLAN data
  8595. */
  8596. static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
  8597. EQPGraphRow *pNew;
  8598. int nText = strlen30(zText);
  8599. if( p->autoEQPtest ){
  8600. utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
  8601. }
  8602. pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
  8603. if( pNew==0 ) shell_out_of_memory();
  8604. pNew->iEqpId = iEqpId;
  8605. pNew->iParentId = p2;
  8606. memcpy(pNew->zText, zText, nText+1);
  8607. pNew->pNext = 0;
  8608. if( p->sGraph.pLast ){
  8609. p->sGraph.pLast->pNext = pNew;
  8610. }else{
  8611. p->sGraph.pRow = pNew;
  8612. }
  8613. p->sGraph.pLast = pNew;
  8614. }
  8615. /*
  8616. ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
  8617. ** in p->sGraph.
  8618. */
  8619. static void eqp_reset(ShellState *p){
  8620. EQPGraphRow *pRow, *pNext;
  8621. for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
  8622. pNext = pRow->pNext;
  8623. sqlite3_free(pRow);
  8624. }
  8625. memset(&p->sGraph, 0, sizeof(p->sGraph));
  8626. }
  8627. /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
  8628. ** pOld, or return the first such line if pOld is NULL
  8629. */
  8630. static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
  8631. EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
  8632. while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
  8633. return pRow;
  8634. }
  8635. /* Render a single level of the graph that has iEqpId as its parent. Called
  8636. ** recursively to render sublevels.
  8637. */
  8638. static void eqp_render_level(ShellState *p, int iEqpId){
  8639. EQPGraphRow *pRow, *pNext;
  8640. int n = strlen30(p->sGraph.zPrefix);
  8641. char *z;
  8642. for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
  8643. pNext = eqp_next_row(p, iEqpId, pRow);
  8644. z = pRow->zText;
  8645. utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
  8646. if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
  8647. memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
  8648. eqp_render_level(p, pRow->iEqpId);
  8649. p->sGraph.zPrefix[n] = 0;
  8650. }
  8651. }
  8652. }
  8653. /*
  8654. ** Display and reset the EXPLAIN QUERY PLAN data
  8655. */
  8656. static void eqp_render(ShellState *p){
  8657. EQPGraphRow *pRow = p->sGraph.pRow;
  8658. if( pRow ){
  8659. if( pRow->zText[0]=='-' ){
  8660. if( pRow->pNext==0 ){
  8661. eqp_reset(p);
  8662. return;
  8663. }
  8664. utf8_printf(p->out, "%s\n", pRow->zText+3);
  8665. p->sGraph.pRow = pRow->pNext;
  8666. sqlite3_free(pRow);
  8667. }else{
  8668. utf8_printf(p->out, "QUERY PLAN\n");
  8669. }
  8670. p->sGraph.zPrefix[0] = 0;
  8671. eqp_render_level(p, 0);
  8672. eqp_reset(p);
  8673. }
  8674. }
  8675. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  8676. /*
  8677. ** Progress handler callback.
  8678. */
  8679. static int progress_handler(void *pClientData) {
  8680. ShellState *p = (ShellState*)pClientData;
  8681. p->nProgress++;
  8682. if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
  8683. raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
  8684. if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
  8685. if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
  8686. return 1;
  8687. }
  8688. if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
  8689. raw_printf(p->out, "Progress %u\n", p->nProgress);
  8690. }
  8691. return 0;
  8692. }
  8693. #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
  8694. /*
  8695. ** This is the callback routine that the shell
  8696. ** invokes for each row of a query result.
  8697. */
  8698. static int shell_callback(
  8699. void *pArg,
  8700. int nArg, /* Number of result columns */
  8701. char **azArg, /* Text of each result column */
  8702. char **azCol, /* Column names */
  8703. int *aiType /* Column types */
  8704. ){
  8705. int i;
  8706. ShellState *p = (ShellState*)pArg;
  8707. if( azArg==0 ) return 0;
  8708. switch( p->cMode ){
  8709. case MODE_Line: {
  8710. int w = 5;
  8711. if( azArg==0 ) break;
  8712. for(i=0; i<nArg; i++){
  8713. int len = strlen30(azCol[i] ? azCol[i] : "");
  8714. if( len>w ) w = len;
  8715. }
  8716. if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
  8717. for(i=0; i<nArg; i++){
  8718. utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
  8719. azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
  8720. }
  8721. break;
  8722. }
  8723. case MODE_Explain:
  8724. case MODE_Column: {
  8725. static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
  8726. const int *colWidth;
  8727. int showHdr;
  8728. char *rowSep;
  8729. if( p->cMode==MODE_Column ){
  8730. colWidth = p->colWidth;
  8731. showHdr = p->showHeader;
  8732. rowSep = p->rowSeparator;
  8733. }else{
  8734. colWidth = aExplainWidths;
  8735. showHdr = 1;
  8736. rowSep = SEP_Row;
  8737. }
  8738. if( p->cnt++==0 ){
  8739. for(i=0; i<nArg; i++){
  8740. int w, n;
  8741. if( i<ArraySize(p->colWidth) ){
  8742. w = colWidth[i];
  8743. }else{
  8744. w = 0;
  8745. }
  8746. if( w==0 ){
  8747. w = strlenChar(azCol[i] ? azCol[i] : "");
  8748. if( w<10 ) w = 10;
  8749. n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
  8750. if( w<n ) w = n;
  8751. }
  8752. if( i<ArraySize(p->actualWidth) ){
  8753. p->actualWidth[i] = w;
  8754. }
  8755. if( showHdr ){
  8756. utf8_width_print(p->out, w, azCol[i]);
  8757. utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
  8758. }
  8759. }
  8760. if( showHdr ){
  8761. for(i=0; i<nArg; i++){
  8762. int w;
  8763. if( i<ArraySize(p->actualWidth) ){
  8764. w = p->actualWidth[i];
  8765. if( w<0 ) w = -w;
  8766. }else{
  8767. w = 10;
  8768. }
  8769. utf8_printf(p->out,"%-*.*s%s",w,w,
  8770. "----------------------------------------------------------"
  8771. "----------------------------------------------------------",
  8772. i==nArg-1 ? rowSep : " ");
  8773. }
  8774. }
  8775. }
  8776. if( azArg==0 ) break;
  8777. for(i=0; i<nArg; i++){
  8778. int w;
  8779. if( i<ArraySize(p->actualWidth) ){
  8780. w = p->actualWidth[i];
  8781. }else{
  8782. w = 10;
  8783. }
  8784. if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
  8785. w = strlenChar(azArg[i]);
  8786. }
  8787. if( i==1 && p->aiIndent && p->pStmt ){
  8788. if( p->iIndent<p->nIndent ){
  8789. utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
  8790. }
  8791. p->iIndent++;
  8792. }
  8793. utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
  8794. utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
  8795. }
  8796. break;
  8797. }
  8798. case MODE_Semi: { /* .schema and .fullschema output */
  8799. printSchemaLine(p->out, azArg[0], ";\n");
  8800. break;
  8801. }
  8802. case MODE_Pretty: { /* .schema and .fullschema with --indent */
  8803. char *z;
  8804. int j;
  8805. int nParen = 0;
  8806. char cEnd = 0;
  8807. char c;
  8808. int nLine = 0;
  8809. assert( nArg==1 );
  8810. if( azArg[0]==0 ) break;
  8811. if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
  8812. || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
  8813. ){
  8814. utf8_printf(p->out, "%s;\n", azArg[0]);
  8815. break;
  8816. }
  8817. z = sqlite3_mprintf("%s", azArg[0]);
  8818. j = 0;
  8819. for(i=0; IsSpace(z[i]); i++){}
  8820. for(; (c = z[i])!=0; i++){
  8821. if( IsSpace(c) ){
  8822. if( z[j-1]=='\r' ) z[j-1] = '\n';
  8823. if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
  8824. }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
  8825. j--;
  8826. }
  8827. z[j++] = c;
  8828. }
  8829. while( j>0 && IsSpace(z[j-1]) ){ j--; }
  8830. z[j] = 0;
  8831. if( strlen30(z)>=79 ){
  8832. for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
  8833. if( c==cEnd ){
  8834. cEnd = 0;
  8835. }else if( c=='"' || c=='\'' || c=='`' ){
  8836. cEnd = c;
  8837. }else if( c=='[' ){
  8838. cEnd = ']';
  8839. }else if( c=='-' && z[i+1]=='-' ){
  8840. cEnd = '\n';
  8841. }else if( c=='(' ){
  8842. nParen++;
  8843. }else if( c==')' ){
  8844. nParen--;
  8845. if( nLine>0 && nParen==0 && j>0 ){
  8846. printSchemaLineN(p->out, z, j, "\n");
  8847. j = 0;
  8848. }
  8849. }
  8850. z[j++] = c;
  8851. if( nParen==1 && cEnd==0
  8852. && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
  8853. ){
  8854. if( c=='\n' ) j--;
  8855. printSchemaLineN(p->out, z, j, "\n ");
  8856. j = 0;
  8857. nLine++;
  8858. while( IsSpace(z[i+1]) ){ i++; }
  8859. }
  8860. }
  8861. z[j] = 0;
  8862. }
  8863. printSchemaLine(p->out, z, ";\n");
  8864. sqlite3_free(z);
  8865. break;
  8866. }
  8867. case MODE_List: {
  8868. if( p->cnt++==0 && p->showHeader ){
  8869. for(i=0; i<nArg; i++){
  8870. utf8_printf(p->out,"%s%s",azCol[i],
  8871. i==nArg-1 ? p->rowSeparator : p->colSeparator);
  8872. }
  8873. }
  8874. if( azArg==0 ) break;
  8875. for(i=0; i<nArg; i++){
  8876. char *z = azArg[i];
  8877. if( z==0 ) z = p->nullValue;
  8878. utf8_printf(p->out, "%s", z);
  8879. if( i<nArg-1 ){
  8880. utf8_printf(p->out, "%s", p->colSeparator);
  8881. }else{
  8882. utf8_printf(p->out, "%s", p->rowSeparator);
  8883. }
  8884. }
  8885. break;
  8886. }
  8887. case MODE_Html: {
  8888. if( p->cnt++==0 && p->showHeader ){
  8889. raw_printf(p->out,"<TR>");
  8890. for(i=0; i<nArg; i++){
  8891. raw_printf(p->out,"<TH>");
  8892. output_html_string(p->out, azCol[i]);
  8893. raw_printf(p->out,"</TH>\n");
  8894. }
  8895. raw_printf(p->out,"</TR>\n");
  8896. }
  8897. if( azArg==0 ) break;
  8898. raw_printf(p->out,"<TR>");
  8899. for(i=0; i<nArg; i++){
  8900. raw_printf(p->out,"<TD>");
  8901. output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  8902. raw_printf(p->out,"</TD>\n");
  8903. }
  8904. raw_printf(p->out,"</TR>\n");
  8905. break;
  8906. }
  8907. case MODE_Tcl: {
  8908. if( p->cnt++==0 && p->showHeader ){
  8909. for(i=0; i<nArg; i++){
  8910. output_c_string(p->out,azCol[i] ? azCol[i] : "");
  8911. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  8912. }
  8913. utf8_printf(p->out, "%s", p->rowSeparator);
  8914. }
  8915. if( azArg==0 ) break;
  8916. for(i=0; i<nArg; i++){
  8917. output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  8918. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  8919. }
  8920. utf8_printf(p->out, "%s", p->rowSeparator);
  8921. break;
  8922. }
  8923. case MODE_Csv: {
  8924. setBinaryMode(p->out, 1);
  8925. if( p->cnt++==0 && p->showHeader ){
  8926. for(i=0; i<nArg; i++){
  8927. output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  8928. }
  8929. utf8_printf(p->out, "%s", p->rowSeparator);
  8930. }
  8931. if( nArg>0 ){
  8932. for(i=0; i<nArg; i++){
  8933. output_csv(p, azArg[i], i<nArg-1);
  8934. }
  8935. utf8_printf(p->out, "%s", p->rowSeparator);
  8936. }
  8937. setTextMode(p->out, 1);
  8938. break;
  8939. }
  8940. case MODE_Insert: {
  8941. if( azArg==0 ) break;
  8942. utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
  8943. if( p->showHeader ){
  8944. raw_printf(p->out,"(");
  8945. for(i=0; i<nArg; i++){
  8946. if( i>0 ) raw_printf(p->out, ",");
  8947. if( quoteChar(azCol[i]) ){
  8948. char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
  8949. utf8_printf(p->out, "%s", z);
  8950. sqlite3_free(z);
  8951. }else{
  8952. raw_printf(p->out, "%s", azCol[i]);
  8953. }
  8954. }
  8955. raw_printf(p->out,")");
  8956. }
  8957. p->cnt++;
  8958. for(i=0; i<nArg; i++){
  8959. raw_printf(p->out, i>0 ? "," : " VALUES(");
  8960. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  8961. utf8_printf(p->out,"NULL");
  8962. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  8963. if( ShellHasFlag(p, SHFLG_Newlines) ){
  8964. output_quoted_string(p->out, azArg[i]);
  8965. }else{
  8966. output_quoted_escaped_string(p->out, azArg[i]);
  8967. }
  8968. }else if( aiType && aiType[i]==SQLITE_INTEGER ){
  8969. utf8_printf(p->out,"%s", azArg[i]);
  8970. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  8971. char z[50];
  8972. double r = sqlite3_column_double(p->pStmt, i);
  8973. sqlite3_uint64 ur;
  8974. memcpy(&ur,&r,sizeof(r));
  8975. if( ur==0x7ff0000000000000LL ){
  8976. raw_printf(p->out, "1e999");
  8977. }else if( ur==0xfff0000000000000LL ){
  8978. raw_printf(p->out, "-1e999");
  8979. }else{
  8980. sqlite3_snprintf(50,z,"%!.20g", r);
  8981. raw_printf(p->out, "%s", z);
  8982. }
  8983. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  8984. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  8985. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  8986. output_hex_blob(p->out, pBlob, nBlob);
  8987. }else if( isNumber(azArg[i], 0) ){
  8988. utf8_printf(p->out,"%s", azArg[i]);
  8989. }else if( ShellHasFlag(p, SHFLG_Newlines) ){
  8990. output_quoted_string(p->out, azArg[i]);
  8991. }else{
  8992. output_quoted_escaped_string(p->out, azArg[i]);
  8993. }
  8994. }
  8995. raw_printf(p->out,");\n");
  8996. break;
  8997. }
  8998. case MODE_Quote: {
  8999. if( azArg==0 ) break;
  9000. if( p->cnt==0 && p->showHeader ){
  9001. for(i=0; i<nArg; i++){
  9002. if( i>0 ) raw_printf(p->out, ",");
  9003. output_quoted_string(p->out, azCol[i]);
  9004. }
  9005. raw_printf(p->out,"\n");
  9006. }
  9007. p->cnt++;
  9008. for(i=0; i<nArg; i++){
  9009. if( i>0 ) raw_printf(p->out, ",");
  9010. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  9011. utf8_printf(p->out,"NULL");
  9012. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  9013. output_quoted_string(p->out, azArg[i]);
  9014. }else if( aiType && aiType[i]==SQLITE_INTEGER ){
  9015. utf8_printf(p->out,"%s", azArg[i]);
  9016. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  9017. char z[50];
  9018. double r = sqlite3_column_double(p->pStmt, i);
  9019. sqlite3_snprintf(50,z,"%!.20g", r);
  9020. raw_printf(p->out, "%s", z);
  9021. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  9022. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  9023. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  9024. output_hex_blob(p->out, pBlob, nBlob);
  9025. }else if( isNumber(azArg[i], 0) ){
  9026. utf8_printf(p->out,"%s", azArg[i]);
  9027. }else{
  9028. output_quoted_string(p->out, azArg[i]);
  9029. }
  9030. }
  9031. raw_printf(p->out,"\n");
  9032. break;
  9033. }
  9034. case MODE_Ascii: {
  9035. if( p->cnt++==0 && p->showHeader ){
  9036. for(i=0; i<nArg; i++){
  9037. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  9038. utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
  9039. }
  9040. utf8_printf(p->out, "%s", p->rowSeparator);
  9041. }
  9042. if( azArg==0 ) break;
  9043. for(i=0; i<nArg; i++){
  9044. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  9045. utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
  9046. }
  9047. utf8_printf(p->out, "%s", p->rowSeparator);
  9048. break;
  9049. }
  9050. case MODE_EQP: {
  9051. eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
  9052. break;
  9053. }
  9054. }
  9055. return 0;
  9056. }
  9057. /*
  9058. ** This is the callback routine that the SQLite library
  9059. ** invokes for each row of a query result.
  9060. */
  9061. static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  9062. /* since we don't have type info, call the shell_callback with a NULL value */
  9063. return shell_callback(pArg, nArg, azArg, azCol, NULL);
  9064. }
  9065. /*
  9066. ** This is the callback routine from sqlite3_exec() that appends all
  9067. ** output onto the end of a ShellText object.
  9068. */
  9069. static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
  9070. ShellText *p = (ShellText*)pArg;
  9071. int i;
  9072. UNUSED_PARAMETER(az);
  9073. if( azArg==0 ) return 0;
  9074. if( p->n ) appendText(p, "|", 0);
  9075. for(i=0; i<nArg; i++){
  9076. if( i ) appendText(p, ",", 0);
  9077. if( azArg[i] ) appendText(p, azArg[i], 0);
  9078. }
  9079. return 0;
  9080. }
  9081. /*
  9082. ** Generate an appropriate SELFTEST table in the main database.
  9083. */
  9084. static void createSelftestTable(ShellState *p){
  9085. char *zErrMsg = 0;
  9086. sqlite3_exec(p->db,
  9087. "SAVEPOINT selftest_init;\n"
  9088. "CREATE TABLE IF NOT EXISTS selftest(\n"
  9089. " tno INTEGER PRIMARY KEY,\n" /* Test number */
  9090. " op TEXT,\n" /* Operator: memo run */
  9091. " cmd TEXT,\n" /* Command text */
  9092. " ans TEXT\n" /* Desired answer */
  9093. ");"
  9094. "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
  9095. "INSERT INTO [_shell$self](rowid,op,cmd)\n"
  9096. " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
  9097. " 'memo','Tests generated by --init');\n"
  9098. "INSERT INTO [_shell$self]\n"
  9099. " SELECT 'run',\n"
  9100. " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
  9101. "FROM sqlite_master ORDER BY 2'',224))',\n"
  9102. " hex(sha3_query('SELECT type,name,tbl_name,sql "
  9103. "FROM sqlite_master ORDER BY 2',224));\n"
  9104. "INSERT INTO [_shell$self]\n"
  9105. " SELECT 'run',"
  9106. " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
  9107. " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
  9108. " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
  9109. " FROM (\n"
  9110. " SELECT name FROM sqlite_master\n"
  9111. " WHERE type='table'\n"
  9112. " AND name<>'selftest'\n"
  9113. " AND coalesce(rootpage,0)>0\n"
  9114. " )\n"
  9115. " ORDER BY name;\n"
  9116. "INSERT INTO [_shell$self]\n"
  9117. " VALUES('run','PRAGMA integrity_check','ok');\n"
  9118. "INSERT INTO selftest(tno,op,cmd,ans)"
  9119. " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
  9120. "DROP TABLE [_shell$self];"
  9121. ,0,0,&zErrMsg);
  9122. if( zErrMsg ){
  9123. utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
  9124. sqlite3_free(zErrMsg);
  9125. }
  9126. sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
  9127. }
  9128. /*
  9129. ** Set the destination table field of the ShellState structure to
  9130. ** the name of the table given. Escape any quote characters in the
  9131. ** table name.
  9132. */
  9133. static void set_table_name(ShellState *p, const char *zName){
  9134. int i, n;
  9135. char cQuote;
  9136. char *z;
  9137. if( p->zDestTable ){
  9138. free(p->zDestTable);
  9139. p->zDestTable = 0;
  9140. }
  9141. if( zName==0 ) return;
  9142. cQuote = quoteChar(zName);
  9143. n = strlen30(zName);
  9144. if( cQuote ) n += n+2;
  9145. z = p->zDestTable = malloc( n+1 );
  9146. if( z==0 ) shell_out_of_memory();
  9147. n = 0;
  9148. if( cQuote ) z[n++] = cQuote;
  9149. for(i=0; zName[i]; i++){
  9150. z[n++] = zName[i];
  9151. if( zName[i]==cQuote ) z[n++] = cQuote;
  9152. }
  9153. if( cQuote ) z[n++] = cQuote;
  9154. z[n] = 0;
  9155. }
  9156. /*
  9157. ** Execute a query statement that will generate SQL output. Print
  9158. ** the result columns, comma-separated, on a line and then add a
  9159. ** semicolon terminator to the end of that line.
  9160. **
  9161. ** If the number of columns is 1 and that column contains text "--"
  9162. ** then write the semicolon on a separate line. That way, if a
  9163. ** "--" comment occurs at the end of the statement, the comment
  9164. ** won't consume the semicolon terminator.
  9165. */
  9166. static int run_table_dump_query(
  9167. ShellState *p, /* Query context */
  9168. const char *zSelect, /* SELECT statement to extract content */
  9169. const char *zFirstRow /* Print before first row, if not NULL */
  9170. ){
  9171. sqlite3_stmt *pSelect;
  9172. int rc;
  9173. int nResult;
  9174. int i;
  9175. const char *z;
  9176. rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
  9177. if( rc!=SQLITE_OK || !pSelect ){
  9178. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  9179. sqlite3_errmsg(p->db));
  9180. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  9181. return rc;
  9182. }
  9183. rc = sqlite3_step(pSelect);
  9184. nResult = sqlite3_column_count(pSelect);
  9185. while( rc==SQLITE_ROW ){
  9186. if( zFirstRow ){
  9187. utf8_printf(p->out, "%s", zFirstRow);
  9188. zFirstRow = 0;
  9189. }
  9190. z = (const char*)sqlite3_column_text(pSelect, 0);
  9191. utf8_printf(p->out, "%s", z);
  9192. for(i=1; i<nResult; i++){
  9193. utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
  9194. }
  9195. if( z==0 ) z = "";
  9196. while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
  9197. if( z[0] ){
  9198. raw_printf(p->out, "\n;\n");
  9199. }else{
  9200. raw_printf(p->out, ";\n");
  9201. }
  9202. rc = sqlite3_step(pSelect);
  9203. }
  9204. rc = sqlite3_finalize(pSelect);
  9205. if( rc!=SQLITE_OK ){
  9206. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  9207. sqlite3_errmsg(p->db));
  9208. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  9209. }
  9210. return rc;
  9211. }
  9212. /*
  9213. ** Allocate space and save off current error string.
  9214. */
  9215. static char *save_err_msg(
  9216. sqlite3 *db /* Database to query */
  9217. ){
  9218. int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
  9219. char *zErrMsg = sqlite3_malloc64(nErrMsg);
  9220. if( zErrMsg ){
  9221. memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
  9222. }
  9223. return zErrMsg;
  9224. }
  9225. #ifdef __linux__
  9226. /*
  9227. ** Attempt to display I/O stats on Linux using /proc/PID/io
  9228. */
  9229. static void displayLinuxIoStats(FILE *out){
  9230. FILE *in;
  9231. char z[200];
  9232. sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
  9233. in = fopen(z, "rb");
  9234. if( in==0 ) return;
  9235. while( fgets(z, sizeof(z), in)!=0 ){
  9236. static const struct {
  9237. const char *zPattern;
  9238. const char *zDesc;
  9239. } aTrans[] = {
  9240. { "rchar: ", "Bytes received by read():" },
  9241. { "wchar: ", "Bytes sent to write():" },
  9242. { "syscr: ", "Read() system calls:" },
  9243. { "syscw: ", "Write() system calls:" },
  9244. { "read_bytes: ", "Bytes read from storage:" },
  9245. { "write_bytes: ", "Bytes written to storage:" },
  9246. { "cancelled_write_bytes: ", "Cancelled write bytes:" },
  9247. };
  9248. int i;
  9249. for(i=0; i<ArraySize(aTrans); i++){
  9250. int n = strlen30(aTrans[i].zPattern);
  9251. if( strncmp(aTrans[i].zPattern, z, n)==0 ){
  9252. utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
  9253. break;
  9254. }
  9255. }
  9256. }
  9257. fclose(in);
  9258. }
  9259. #endif
  9260. /*
  9261. ** Display a single line of status using 64-bit values.
  9262. */
  9263. static void displayStatLine(
  9264. ShellState *p, /* The shell context */
  9265. char *zLabel, /* Label for this one line */
  9266. char *zFormat, /* Format for the result */
  9267. int iStatusCtrl, /* Which status to display */
  9268. int bReset /* True to reset the stats */
  9269. ){
  9270. sqlite3_int64 iCur = -1;
  9271. sqlite3_int64 iHiwtr = -1;
  9272. int i, nPercent;
  9273. char zLine[200];
  9274. sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
  9275. for(i=0, nPercent=0; zFormat[i]; i++){
  9276. if( zFormat[i]=='%' ) nPercent++;
  9277. }
  9278. if( nPercent>1 ){
  9279. sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
  9280. }else{
  9281. sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
  9282. }
  9283. raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
  9284. }
  9285. /*
  9286. ** Display memory stats.
  9287. */
  9288. static int display_stats(
  9289. sqlite3 *db, /* Database to query */
  9290. ShellState *pArg, /* Pointer to ShellState */
  9291. int bReset /* True to reset the stats */
  9292. ){
  9293. int iCur;
  9294. int iHiwtr;
  9295. FILE *out;
  9296. if( pArg==0 || pArg->out==0 ) return 0;
  9297. out = pArg->out;
  9298. if( pArg->pStmt && (pArg->statsOn & 2) ){
  9299. int nCol, i, x;
  9300. sqlite3_stmt *pStmt = pArg->pStmt;
  9301. char z[100];
  9302. nCol = sqlite3_column_count(pStmt);
  9303. raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
  9304. for(i=0; i<nCol; i++){
  9305. sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
  9306. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
  9307. #ifndef SQLITE_OMIT_DECLTYPE
  9308. sqlite3_snprintf(30, z+x, "declared type:");
  9309. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
  9310. #endif
  9311. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  9312. sqlite3_snprintf(30, z+x, "database name:");
  9313. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
  9314. sqlite3_snprintf(30, z+x, "table name:");
  9315. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
  9316. sqlite3_snprintf(30, z+x, "origin name:");
  9317. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
  9318. #endif
  9319. }
  9320. }
  9321. displayStatLine(pArg, "Memory Used:",
  9322. "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
  9323. displayStatLine(pArg, "Number of Outstanding Allocations:",
  9324. "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
  9325. if( pArg->shellFlgs & SHFLG_Pagecache ){
  9326. displayStatLine(pArg, "Number of Pcache Pages Used:",
  9327. "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
  9328. }
  9329. displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
  9330. "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
  9331. displayStatLine(pArg, "Largest Allocation:",
  9332. "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
  9333. displayStatLine(pArg, "Largest Pcache Allocation:",
  9334. "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
  9335. #ifdef YYTRACKMAXSTACKDEPTH
  9336. displayStatLine(pArg, "Deepest Parser Stack:",
  9337. "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
  9338. #endif
  9339. if( db ){
  9340. if( pArg->shellFlgs & SHFLG_Lookaside ){
  9341. iHiwtr = iCur = -1;
  9342. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
  9343. &iCur, &iHiwtr, bReset);
  9344. raw_printf(pArg->out,
  9345. "Lookaside Slots Used: %d (max %d)\n",
  9346. iCur, iHiwtr);
  9347. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
  9348. &iCur, &iHiwtr, bReset);
  9349. raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
  9350. iHiwtr);
  9351. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
  9352. &iCur, &iHiwtr, bReset);
  9353. raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
  9354. iHiwtr);
  9355. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
  9356. &iCur, &iHiwtr, bReset);
  9357. raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
  9358. iHiwtr);
  9359. }
  9360. iHiwtr = iCur = -1;
  9361. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
  9362. raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
  9363. iCur);
  9364. iHiwtr = iCur = -1;
  9365. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
  9366. raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
  9367. iHiwtr = iCur = -1;
  9368. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
  9369. raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
  9370. iHiwtr = iCur = -1;
  9371. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
  9372. raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
  9373. iHiwtr = iCur = -1;
  9374. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
  9375. raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
  9376. iHiwtr = iCur = -1;
  9377. sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
  9378. raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
  9379. iCur);
  9380. iHiwtr = iCur = -1;
  9381. sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
  9382. raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
  9383. iCur);
  9384. }
  9385. if( pArg->pStmt ){
  9386. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
  9387. bReset);
  9388. raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
  9389. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
  9390. raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
  9391. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
  9392. raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
  9393. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
  9394. raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
  9395. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
  9396. raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
  9397. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
  9398. raw_printf(pArg->out, "Number of times run: %d\n", iCur);
  9399. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
  9400. raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
  9401. }
  9402. #ifdef __linux__
  9403. displayLinuxIoStats(pArg->out);
  9404. #endif
  9405. /* Do not remove this machine readable comment: extra-stats-output-here */
  9406. return 0;
  9407. }
  9408. /*
  9409. ** Display scan stats.
  9410. */
  9411. static void display_scanstats(
  9412. sqlite3 *db, /* Database to query */
  9413. ShellState *pArg /* Pointer to ShellState */
  9414. ){
  9415. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  9416. UNUSED_PARAMETER(db);
  9417. UNUSED_PARAMETER(pArg);
  9418. #else
  9419. int i, k, n, mx;
  9420. raw_printf(pArg->out, "-------- scanstats --------\n");
  9421. mx = 0;
  9422. for(k=0; k<=mx; k++){
  9423. double rEstLoop = 1.0;
  9424. for(i=n=0; 1; i++){
  9425. sqlite3_stmt *p = pArg->pStmt;
  9426. sqlite3_int64 nLoop, nVisit;
  9427. double rEst;
  9428. int iSid;
  9429. const char *zExplain;
  9430. if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
  9431. break;
  9432. }
  9433. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
  9434. if( iSid>mx ) mx = iSid;
  9435. if( iSid!=k ) continue;
  9436. if( n==0 ){
  9437. rEstLoop = (double)nLoop;
  9438. if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
  9439. }
  9440. n++;
  9441. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
  9442. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
  9443. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
  9444. utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
  9445. rEstLoop *= rEst;
  9446. raw_printf(pArg->out,
  9447. " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
  9448. nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
  9449. );
  9450. }
  9451. }
  9452. raw_printf(pArg->out, "---------------------------\n");
  9453. #endif
  9454. }
  9455. /*
  9456. ** Parameter azArray points to a zero-terminated array of strings. zStr
  9457. ** points to a single nul-terminated string. Return non-zero if zStr
  9458. ** is equal, according to strcmp(), to any of the strings in the array.
  9459. ** Otherwise, return zero.
  9460. */
  9461. static int str_in_array(const char *zStr, const char **azArray){
  9462. int i;
  9463. for(i=0; azArray[i]; i++){
  9464. if( 0==strcmp(zStr, azArray[i]) ) return 1;
  9465. }
  9466. return 0;
  9467. }
  9468. /*
  9469. ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
  9470. ** and populate the ShellState.aiIndent[] array with the number of
  9471. ** spaces each opcode should be indented before it is output.
  9472. **
  9473. ** The indenting rules are:
  9474. **
  9475. ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
  9476. ** all opcodes that occur between the p2 jump destination and the opcode
  9477. ** itself by 2 spaces.
  9478. **
  9479. ** * For each "Goto", if the jump destination is earlier in the program
  9480. ** and ends on one of:
  9481. ** Yield SeekGt SeekLt RowSetRead Rewind
  9482. ** or if the P1 parameter is one instead of zero,
  9483. ** then indent all opcodes between the earlier instruction
  9484. ** and "Goto" by 2 spaces.
  9485. */
  9486. static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
  9487. const char *zSql; /* The text of the SQL statement */
  9488. const char *z; /* Used to check if this is an EXPLAIN */
  9489. int *abYield = 0; /* True if op is an OP_Yield */
  9490. int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
  9491. int iOp; /* Index of operation in p->aiIndent[] */
  9492. const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
  9493. const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
  9494. "Rewind", 0 };
  9495. const char *azGoto[] = { "Goto", 0 };
  9496. /* Try to figure out if this is really an EXPLAIN statement. If this
  9497. ** cannot be verified, return early. */
  9498. if( sqlite3_column_count(pSql)!=8 ){
  9499. p->cMode = p->mode;
  9500. return;
  9501. }
  9502. zSql = sqlite3_sql(pSql);
  9503. if( zSql==0 ) return;
  9504. for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
  9505. if( sqlite3_strnicmp(z, "explain", 7) ){
  9506. p->cMode = p->mode;
  9507. return;
  9508. }
  9509. for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
  9510. int i;
  9511. int iAddr = sqlite3_column_int(pSql, 0);
  9512. const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
  9513. /* Set p2 to the P2 field of the current opcode. Then, assuming that
  9514. ** p2 is an instruction address, set variable p2op to the index of that
  9515. ** instruction in the aiIndent[] array. p2 and p2op may be different if
  9516. ** the current instruction is part of a sub-program generated by an
  9517. ** SQL trigger or foreign key. */
  9518. int p2 = sqlite3_column_int(pSql, 3);
  9519. int p2op = (p2 + (iOp-iAddr));
  9520. /* Grow the p->aiIndent array as required */
  9521. if( iOp>=nAlloc ){
  9522. if( iOp==0 ){
  9523. /* Do further verfication that this is explain output. Abort if
  9524. ** it is not */
  9525. static const char *explainCols[] = {
  9526. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
  9527. int jj;
  9528. for(jj=0; jj<ArraySize(explainCols); jj++){
  9529. if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
  9530. p->cMode = p->mode;
  9531. sqlite3_reset(pSql);
  9532. return;
  9533. }
  9534. }
  9535. }
  9536. nAlloc += 100;
  9537. p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
  9538. if( p->aiIndent==0 ) shell_out_of_memory();
  9539. abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
  9540. if( abYield==0 ) shell_out_of_memory();
  9541. }
  9542. abYield[iOp] = str_in_array(zOp, azYield);
  9543. p->aiIndent[iOp] = 0;
  9544. p->nIndent = iOp+1;
  9545. if( str_in_array(zOp, azNext) ){
  9546. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  9547. }
  9548. if( str_in_array(zOp, azGoto) && p2op<p->nIndent
  9549. && (abYield[p2op] || sqlite3_column_int(pSql, 2))
  9550. ){
  9551. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  9552. }
  9553. }
  9554. p->iIndent = 0;
  9555. sqlite3_free(abYield);
  9556. sqlite3_reset(pSql);
  9557. }
  9558. /*
  9559. ** Free the array allocated by explain_data_prepare().
  9560. */
  9561. static void explain_data_delete(ShellState *p){
  9562. sqlite3_free(p->aiIndent);
  9563. p->aiIndent = 0;
  9564. p->nIndent = 0;
  9565. p->iIndent = 0;
  9566. }
  9567. /*
  9568. ** Disable and restore .wheretrace and .selecttrace settings.
  9569. */
  9570. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  9571. extern int sqlite3SelectTrace;
  9572. static int savedSelectTrace;
  9573. #endif
  9574. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  9575. extern int sqlite3WhereTrace;
  9576. static int savedWhereTrace;
  9577. #endif
  9578. static void disable_debug_trace_modes(void){
  9579. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  9580. savedSelectTrace = sqlite3SelectTrace;
  9581. sqlite3SelectTrace = 0;
  9582. #endif
  9583. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  9584. savedWhereTrace = sqlite3WhereTrace;
  9585. sqlite3WhereTrace = 0;
  9586. #endif
  9587. }
  9588. static void restore_debug_trace_modes(void){
  9589. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  9590. sqlite3SelectTrace = savedSelectTrace;
  9591. #endif
  9592. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  9593. sqlite3WhereTrace = savedWhereTrace;
  9594. #endif
  9595. }
  9596. /* Create the TEMP table used to store parameter bindings */
  9597. static void bind_table_init(ShellState *p){
  9598. int wrSchema = 0;
  9599. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
  9600. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
  9601. sqlite3_exec(p->db,
  9602. "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
  9603. " key TEXT PRIMARY KEY,\n"
  9604. " value ANY\n"
  9605. ") WITHOUT ROWID;",
  9606. 0, 0, 0);
  9607. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
  9608. }
  9609. /*
  9610. ** Bind parameters on a prepared statement.
  9611. **
  9612. ** Parameter bindings are taken from a TEMP table of the form:
  9613. **
  9614. ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
  9615. ** WITHOUT ROWID;
  9616. **
  9617. ** No bindings occur if this table does not exist. The special character '$'
  9618. ** is included in the table name to help prevent collisions with actual tables.
  9619. ** The table must be in the TEMP schema.
  9620. */
  9621. static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
  9622. int nVar;
  9623. int i;
  9624. int rc;
  9625. sqlite3_stmt *pQ = 0;
  9626. nVar = sqlite3_bind_parameter_count(pStmt);
  9627. if( nVar==0 ) return; /* Nothing to do */
  9628. if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
  9629. "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
  9630. return; /* Parameter table does not exist */
  9631. }
  9632. rc = sqlite3_prepare_v2(pArg->db,
  9633. "SELECT value FROM temp.sqlite_parameters"
  9634. " WHERE key=?1", -1, &pQ, 0);
  9635. if( rc || pQ==0 ) return;
  9636. for(i=1; i<=nVar; i++){
  9637. char zNum[30];
  9638. const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
  9639. if( zVar==0 ){
  9640. sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
  9641. zVar = zNum;
  9642. }
  9643. sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
  9644. if( sqlite3_step(pQ)==SQLITE_ROW ){
  9645. sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
  9646. }else{
  9647. sqlite3_bind_null(pStmt, i);
  9648. }
  9649. sqlite3_reset(pQ);
  9650. }
  9651. sqlite3_finalize(pQ);
  9652. }
  9653. /*
  9654. ** Run a prepared statement
  9655. */
  9656. static void exec_prepared_stmt(
  9657. ShellState *pArg, /* Pointer to ShellState */
  9658. sqlite3_stmt *pStmt /* Statment to run */
  9659. ){
  9660. int rc;
  9661. /* perform the first step. this will tell us if we
  9662. ** have a result set or not and how wide it is.
  9663. */
  9664. rc = sqlite3_step(pStmt);
  9665. /* if we have a result set... */
  9666. if( SQLITE_ROW == rc ){
  9667. /* allocate space for col name ptr, value ptr, and type */
  9668. int nCol = sqlite3_column_count(pStmt);
  9669. void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
  9670. if( !pData ){
  9671. rc = SQLITE_NOMEM;
  9672. }else{
  9673. char **azCols = (char **)pData; /* Names of result columns */
  9674. char **azVals = &azCols[nCol]; /* Results */
  9675. int *aiTypes = (int *)&azVals[nCol]; /* Result types */
  9676. int i, x;
  9677. assert(sizeof(int) <= sizeof(char *));
  9678. /* save off ptrs to column names */
  9679. for(i=0; i<nCol; i++){
  9680. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  9681. }
  9682. do{
  9683. /* extract the data and data types */
  9684. for(i=0; i<nCol; i++){
  9685. aiTypes[i] = x = sqlite3_column_type(pStmt, i);
  9686. if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
  9687. azVals[i] = "";
  9688. }else{
  9689. azVals[i] = (char*)sqlite3_column_text(pStmt, i);
  9690. }
  9691. if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
  9692. rc = SQLITE_NOMEM;
  9693. break; /* from for */
  9694. }
  9695. } /* end for */
  9696. /* if data and types extracted successfully... */
  9697. if( SQLITE_ROW == rc ){
  9698. /* call the supplied callback with the result row data */
  9699. if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
  9700. rc = SQLITE_ABORT;
  9701. }else{
  9702. rc = sqlite3_step(pStmt);
  9703. }
  9704. }
  9705. } while( SQLITE_ROW == rc );
  9706. sqlite3_free(pData);
  9707. }
  9708. }
  9709. }
  9710. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9711. /*
  9712. ** This function is called to process SQL if the previous shell command
  9713. ** was ".expert". It passes the SQL in the second argument directly to
  9714. ** the sqlite3expert object.
  9715. **
  9716. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
  9717. ** code. In this case, (*pzErr) may be set to point to a buffer containing
  9718. ** an English language error message. It is the responsibility of the
  9719. ** caller to eventually free this buffer using sqlite3_free().
  9720. */
  9721. static int expertHandleSQL(
  9722. ShellState *pState,
  9723. const char *zSql,
  9724. char **pzErr
  9725. ){
  9726. assert( pState->expert.pExpert );
  9727. assert( pzErr==0 || *pzErr==0 );
  9728. return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
  9729. }
  9730. /*
  9731. ** This function is called either to silently clean up the object
  9732. ** created by the ".expert" command (if bCancel==1), or to generate a
  9733. ** report from it and then clean it up (if bCancel==0).
  9734. **
  9735. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
  9736. ** code. In this case, (*pzErr) may be set to point to a buffer containing
  9737. ** an English language error message. It is the responsibility of the
  9738. ** caller to eventually free this buffer using sqlite3_free().
  9739. */
  9740. static int expertFinish(
  9741. ShellState *pState,
  9742. int bCancel,
  9743. char **pzErr
  9744. ){
  9745. int rc = SQLITE_OK;
  9746. sqlite3expert *p = pState->expert.pExpert;
  9747. assert( p );
  9748. assert( bCancel || pzErr==0 || *pzErr==0 );
  9749. if( bCancel==0 ){
  9750. FILE *out = pState->out;
  9751. int bVerbose = pState->expert.bVerbose;
  9752. rc = sqlite3_expert_analyze(p, pzErr);
  9753. if( rc==SQLITE_OK ){
  9754. int nQuery = sqlite3_expert_count(p);
  9755. int i;
  9756. if( bVerbose ){
  9757. const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
  9758. raw_printf(out, "-- Candidates -----------------------------\n");
  9759. raw_printf(out, "%s\n", zCand);
  9760. }
  9761. for(i=0; i<nQuery; i++){
  9762. const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
  9763. const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
  9764. const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
  9765. if( zIdx==0 ) zIdx = "(no new indexes)\n";
  9766. if( bVerbose ){
  9767. raw_printf(out, "-- Query %d --------------------------------\n",i+1);
  9768. raw_printf(out, "%s\n\n", zSql);
  9769. }
  9770. raw_printf(out, "%s\n", zIdx);
  9771. raw_printf(out, "%s\n", zEQP);
  9772. }
  9773. }
  9774. }
  9775. sqlite3_expert_destroy(p);
  9776. pState->expert.pExpert = 0;
  9777. return rc;
  9778. }
  9779. /*
  9780. ** Implementation of ".expert" dot command.
  9781. */
  9782. static int expertDotCommand(
  9783. ShellState *pState, /* Current shell tool state */
  9784. char **azArg, /* Array of arguments passed to dot command */
  9785. int nArg /* Number of entries in azArg[] */
  9786. ){
  9787. int rc = SQLITE_OK;
  9788. char *zErr = 0;
  9789. int i;
  9790. int iSample = 0;
  9791. assert( pState->expert.pExpert==0 );
  9792. memset(&pState->expert, 0, sizeof(ExpertInfo));
  9793. for(i=1; rc==SQLITE_OK && i<nArg; i++){
  9794. char *z = azArg[i];
  9795. int n;
  9796. if( z[0]=='-' && z[1]=='-' ) z++;
  9797. n = strlen30(z);
  9798. if( n>=2 && 0==strncmp(z, "-verbose", n) ){
  9799. pState->expert.bVerbose = 1;
  9800. }
  9801. else if( n>=2 && 0==strncmp(z, "-sample", n) ){
  9802. if( i==(nArg-1) ){
  9803. raw_printf(stderr, "option requires an argument: %s\n", z);
  9804. rc = SQLITE_ERROR;
  9805. }else{
  9806. iSample = (int)integerValue(azArg[++i]);
  9807. if( iSample<0 || iSample>100 ){
  9808. raw_printf(stderr, "value out of range: %s\n", azArg[i]);
  9809. rc = SQLITE_ERROR;
  9810. }
  9811. }
  9812. }
  9813. else{
  9814. raw_printf(stderr, "unknown option: %s\n", z);
  9815. rc = SQLITE_ERROR;
  9816. }
  9817. }
  9818. if( rc==SQLITE_OK ){
  9819. pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
  9820. if( pState->expert.pExpert==0 ){
  9821. raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
  9822. rc = SQLITE_ERROR;
  9823. }else{
  9824. sqlite3_expert_config(
  9825. pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
  9826. );
  9827. }
  9828. }
  9829. return rc;
  9830. }
  9831. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  9832. /*
  9833. ** Execute a statement or set of statements. Print
  9834. ** any result rows/columns depending on the current mode
  9835. ** set via the supplied callback.
  9836. **
  9837. ** This is very similar to SQLite's built-in sqlite3_exec()
  9838. ** function except it takes a slightly different callback
  9839. ** and callback data argument.
  9840. */
  9841. static int shell_exec(
  9842. ShellState *pArg, /* Pointer to ShellState */
  9843. const char *zSql, /* SQL to be evaluated */
  9844. char **pzErrMsg /* Error msg written here */
  9845. ){
  9846. sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
  9847. int rc = SQLITE_OK; /* Return Code */
  9848. int rc2;
  9849. const char *zLeftover; /* Tail of unprocessed SQL */
  9850. sqlite3 *db = pArg->db;
  9851. if( pzErrMsg ){
  9852. *pzErrMsg = NULL;
  9853. }
  9854. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9855. if( pArg->expert.pExpert ){
  9856. rc = expertHandleSQL(pArg, zSql, pzErrMsg);
  9857. return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
  9858. }
  9859. #endif
  9860. while( zSql[0] && (SQLITE_OK == rc) ){
  9861. static const char *zStmtSql;
  9862. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  9863. if( SQLITE_OK != rc ){
  9864. if( pzErrMsg ){
  9865. *pzErrMsg = save_err_msg(db);
  9866. }
  9867. }else{
  9868. if( !pStmt ){
  9869. /* this happens for a comment or white-space */
  9870. zSql = zLeftover;
  9871. while( IsSpace(zSql[0]) ) zSql++;
  9872. continue;
  9873. }
  9874. zStmtSql = sqlite3_sql(pStmt);
  9875. if( zStmtSql==0 ) zStmtSql = "";
  9876. while( IsSpace(zStmtSql[0]) ) zStmtSql++;
  9877. /* save off the prepared statment handle and reset row count */
  9878. if( pArg ){
  9879. pArg->pStmt = pStmt;
  9880. pArg->cnt = 0;
  9881. }
  9882. /* echo the sql statement if echo on */
  9883. if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
  9884. utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  9885. }
  9886. /* Show the EXPLAIN QUERY PLAN if .eqp is on */
  9887. if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
  9888. sqlite3_stmt *pExplain;
  9889. char *zEQP;
  9890. int triggerEQP = 0;
  9891. disable_debug_trace_modes();
  9892. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
  9893. if( pArg->autoEQP>=AUTOEQP_trigger ){
  9894. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
  9895. }
  9896. zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
  9897. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  9898. if( rc==SQLITE_OK ){
  9899. while( sqlite3_step(pExplain)==SQLITE_ROW ){
  9900. const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
  9901. int iEqpId = sqlite3_column_int(pExplain, 0);
  9902. int iParentId = sqlite3_column_int(pExplain, 1);
  9903. if( zEQPLine[0]=='-' ) eqp_render(pArg);
  9904. eqp_append(pArg, iEqpId, iParentId, zEQPLine);
  9905. }
  9906. eqp_render(pArg);
  9907. }
  9908. sqlite3_finalize(pExplain);
  9909. sqlite3_free(zEQP);
  9910. if( pArg->autoEQP>=AUTOEQP_full ){
  9911. /* Also do an EXPLAIN for ".eqp full" mode */
  9912. zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
  9913. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  9914. if( rc==SQLITE_OK ){
  9915. pArg->cMode = MODE_Explain;
  9916. explain_data_prepare(pArg, pExplain);
  9917. exec_prepared_stmt(pArg, pExplain);
  9918. explain_data_delete(pArg);
  9919. }
  9920. sqlite3_finalize(pExplain);
  9921. sqlite3_free(zEQP);
  9922. }
  9923. if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
  9924. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
  9925. /* Reprepare pStmt before reactiving trace modes */
  9926. sqlite3_finalize(pStmt);
  9927. sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  9928. if( pArg ) pArg->pStmt = pStmt;
  9929. }
  9930. restore_debug_trace_modes();
  9931. }
  9932. if( pArg ){
  9933. pArg->cMode = pArg->mode;
  9934. if( pArg->autoExplain ){
  9935. if( sqlite3_stmt_isexplain(pStmt)==1 ){
  9936. pArg->cMode = MODE_Explain;
  9937. }
  9938. if( sqlite3_stmt_isexplain(pStmt)==2 ){
  9939. pArg->cMode = MODE_EQP;
  9940. }
  9941. }
  9942. /* If the shell is currently in ".explain" mode, gather the extra
  9943. ** data required to add indents to the output.*/
  9944. if( pArg->cMode==MODE_Explain ){
  9945. explain_data_prepare(pArg, pStmt);
  9946. }
  9947. }
  9948. bind_prepared_stmt(pArg, pStmt);
  9949. exec_prepared_stmt(pArg, pStmt);
  9950. explain_data_delete(pArg);
  9951. eqp_render(pArg);
  9952. /* print usage stats if stats on */
  9953. if( pArg && pArg->statsOn ){
  9954. display_stats(db, pArg, 0);
  9955. }
  9956. /* print loop-counters if required */
  9957. if( pArg && pArg->scanstatsOn ){
  9958. display_scanstats(db, pArg);
  9959. }
  9960. /* Finalize the statement just executed. If this fails, save a
  9961. ** copy of the error message. Otherwise, set zSql to point to the
  9962. ** next statement to execute. */
  9963. rc2 = sqlite3_finalize(pStmt);
  9964. if( rc!=SQLITE_NOMEM ) rc = rc2;
  9965. if( rc==SQLITE_OK ){
  9966. zSql = zLeftover;
  9967. while( IsSpace(zSql[0]) ) zSql++;
  9968. }else if( pzErrMsg ){
  9969. *pzErrMsg = save_err_msg(db);
  9970. }
  9971. /* clear saved stmt handle */
  9972. if( pArg ){
  9973. pArg->pStmt = NULL;
  9974. }
  9975. }
  9976. } /* end while */
  9977. return rc;
  9978. }
  9979. /*
  9980. ** Release memory previously allocated by tableColumnList().
  9981. */
  9982. static void freeColumnList(char **azCol){
  9983. int i;
  9984. for(i=1; azCol[i]; i++){
  9985. sqlite3_free(azCol[i]);
  9986. }
  9987. /* azCol[0] is a static string */
  9988. sqlite3_free(azCol);
  9989. }
  9990. /*
  9991. ** Return a list of pointers to strings which are the names of all
  9992. ** columns in table zTab. The memory to hold the names is dynamically
  9993. ** allocated and must be released by the caller using a subsequent call
  9994. ** to freeColumnList().
  9995. **
  9996. ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
  9997. ** value that needs to be preserved, then azCol[0] is filled in with the
  9998. ** name of the rowid column.
  9999. **
  10000. ** The first regular column in the table is azCol[1]. The list is terminated
  10001. ** by an entry with azCol[i]==0.
  10002. */
  10003. static char **tableColumnList(ShellState *p, const char *zTab){
  10004. char **azCol = 0;
  10005. sqlite3_stmt *pStmt;
  10006. char *zSql;
  10007. int nCol = 0;
  10008. int nAlloc = 0;
  10009. int nPK = 0; /* Number of PRIMARY KEY columns seen */
  10010. int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
  10011. int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
  10012. int rc;
  10013. zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
  10014. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  10015. sqlite3_free(zSql);
  10016. if( rc ) return 0;
  10017. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  10018. if( nCol>=nAlloc-2 ){
  10019. nAlloc = nAlloc*2 + nCol + 10;
  10020. azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
  10021. if( azCol==0 ) shell_out_of_memory();
  10022. }
  10023. azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
  10024. if( sqlite3_column_int(pStmt, 5) ){
  10025. nPK++;
  10026. if( nPK==1
  10027. && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
  10028. "INTEGER")==0
  10029. ){
  10030. isIPK = 1;
  10031. }else{
  10032. isIPK = 0;
  10033. }
  10034. }
  10035. }
  10036. sqlite3_finalize(pStmt);
  10037. if( azCol==0 ) return 0;
  10038. azCol[0] = 0;
  10039. azCol[nCol+1] = 0;
  10040. /* The decision of whether or not a rowid really needs to be preserved
  10041. ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
  10042. ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
  10043. ** rowids on tables where the rowid is inaccessible because there are other
  10044. ** columns in the table named "rowid", "_rowid_", and "oid".
  10045. */
  10046. if( preserveRowid && isIPK ){
  10047. /* If a single PRIMARY KEY column with type INTEGER was seen, then it
  10048. ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
  10049. ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
  10050. ** ROWID aliases. To distinguish these cases, check to see if
  10051. ** there is a "pk" entry in "PRAGMA index_list". There will be
  10052. ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
  10053. */
  10054. zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
  10055. " WHERE origin='pk'", zTab);
  10056. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  10057. sqlite3_free(zSql);
  10058. if( rc ){
  10059. freeColumnList(azCol);
  10060. return 0;
  10061. }
  10062. rc = sqlite3_step(pStmt);
  10063. sqlite3_finalize(pStmt);
  10064. preserveRowid = rc==SQLITE_ROW;
  10065. }
  10066. if( preserveRowid ){
  10067. /* Only preserve the rowid if we can find a name to use for the
  10068. ** rowid */
  10069. static char *azRowid[] = { "rowid", "_rowid_", "oid" };
  10070. int i, j;
  10071. for(j=0; j<3; j++){
  10072. for(i=1; i<=nCol; i++){
  10073. if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
  10074. }
  10075. if( i>nCol ){
  10076. /* At this point, we know that azRowid[j] is not the name of any
  10077. ** ordinary column in the table. Verify that azRowid[j] is a valid
  10078. ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
  10079. ** tables will fail this last check */
  10080. rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
  10081. if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
  10082. break;
  10083. }
  10084. }
  10085. }
  10086. return azCol;
  10087. }
  10088. /*
  10089. ** Toggle the reverse_unordered_selects setting.
  10090. */
  10091. static void toggleSelectOrder(sqlite3 *db){
  10092. sqlite3_stmt *pStmt = 0;
  10093. int iSetting = 0;
  10094. char zStmt[100];
  10095. sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
  10096. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  10097. iSetting = sqlite3_column_int(pStmt, 0);
  10098. }
  10099. sqlite3_finalize(pStmt);
  10100. sqlite3_snprintf(sizeof(zStmt), zStmt,
  10101. "PRAGMA reverse_unordered_selects(%d)", !iSetting);
  10102. sqlite3_exec(db, zStmt, 0, 0, 0);
  10103. }
  10104. /*
  10105. ** This is a different callback routine used for dumping the database.
  10106. ** Each row received by this callback consists of a table name,
  10107. ** the table type ("index" or "table") and SQL to create the table.
  10108. ** This routine should print text sufficient to recreate the table.
  10109. */
  10110. static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
  10111. int rc;
  10112. const char *zTable;
  10113. const char *zType;
  10114. const char *zSql;
  10115. ShellState *p = (ShellState *)pArg;
  10116. UNUSED_PARAMETER(azNotUsed);
  10117. if( nArg!=3 || azArg==0 ) return 0;
  10118. zTable = azArg[0];
  10119. zType = azArg[1];
  10120. zSql = azArg[2];
  10121. if( strcmp(zTable, "sqlite_sequence")==0 ){
  10122. raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
  10123. }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
  10124. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  10125. }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  10126. return 0;
  10127. }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  10128. char *zIns;
  10129. if( !p->writableSchema ){
  10130. raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
  10131. p->writableSchema = 1;
  10132. }
  10133. zIns = sqlite3_mprintf(
  10134. "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
  10135. "VALUES('table','%q','%q',0,'%q');",
  10136. zTable, zTable, zSql);
  10137. utf8_printf(p->out, "%s\n", zIns);
  10138. sqlite3_free(zIns);
  10139. return 0;
  10140. }else{
  10141. printSchemaLine(p->out, zSql, ";\n");
  10142. }
  10143. if( strcmp(zType, "table")==0 ){
  10144. ShellText sSelect;
  10145. ShellText sTable;
  10146. char **azCol;
  10147. int i;
  10148. char *savedDestTable;
  10149. int savedMode;
  10150. azCol = tableColumnList(p, zTable);
  10151. if( azCol==0 ){
  10152. p->nErr++;
  10153. return 0;
  10154. }
  10155. /* Always quote the table name, even if it appears to be pure ascii,
  10156. ** in case it is a keyword. Ex: INSERT INTO "table" ... */
  10157. initText(&sTable);
  10158. appendText(&sTable, zTable, quoteChar(zTable));
  10159. /* If preserving the rowid, add a column list after the table name.
  10160. ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
  10161. ** instead of the usual "INSERT INTO tab VALUES(...)".
  10162. */
  10163. if( azCol[0] ){
  10164. appendText(&sTable, "(", 0);
  10165. appendText(&sTable, azCol[0], 0);
  10166. for(i=1; azCol[i]; i++){
  10167. appendText(&sTable, ",", 0);
  10168. appendText(&sTable, azCol[i], quoteChar(azCol[i]));
  10169. }
  10170. appendText(&sTable, ")", 0);
  10171. }
  10172. /* Build an appropriate SELECT statement */
  10173. initText(&sSelect);
  10174. appendText(&sSelect, "SELECT ", 0);
  10175. if( azCol[0] ){
  10176. appendText(&sSelect, azCol[0], 0);
  10177. appendText(&sSelect, ",", 0);
  10178. }
  10179. for(i=1; azCol[i]; i++){
  10180. appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
  10181. if( azCol[i+1] ){
  10182. appendText(&sSelect, ",", 0);
  10183. }
  10184. }
  10185. freeColumnList(azCol);
  10186. appendText(&sSelect, " FROM ", 0);
  10187. appendText(&sSelect, zTable, quoteChar(zTable));
  10188. savedDestTable = p->zDestTable;
  10189. savedMode = p->mode;
  10190. p->zDestTable = sTable.z;
  10191. p->mode = p->cMode = MODE_Insert;
  10192. rc = shell_exec(p, sSelect.z, 0);
  10193. if( (rc&0xff)==SQLITE_CORRUPT ){
  10194. raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  10195. toggleSelectOrder(p->db);
  10196. shell_exec(p, sSelect.z, 0);
  10197. toggleSelectOrder(p->db);
  10198. }
  10199. p->zDestTable = savedDestTable;
  10200. p->mode = savedMode;
  10201. freeText(&sTable);
  10202. freeText(&sSelect);
  10203. if( rc ) p->nErr++;
  10204. }
  10205. return 0;
  10206. }
  10207. /*
  10208. ** Run zQuery. Use dump_callback() as the callback routine so that
  10209. ** the contents of the query are output as SQL statements.
  10210. **
  10211. ** If we get a SQLITE_CORRUPT error, rerun the query after appending
  10212. ** "ORDER BY rowid DESC" to the end.
  10213. */
  10214. static int run_schema_dump_query(
  10215. ShellState *p,
  10216. const char *zQuery
  10217. ){
  10218. int rc;
  10219. char *zErr = 0;
  10220. rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
  10221. if( rc==SQLITE_CORRUPT ){
  10222. char *zQ2;
  10223. int len = strlen30(zQuery);
  10224. raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  10225. if( zErr ){
  10226. utf8_printf(p->out, "/****** %s ******/\n", zErr);
  10227. sqlite3_free(zErr);
  10228. zErr = 0;
  10229. }
  10230. zQ2 = malloc( len+100 );
  10231. if( zQ2==0 ) return rc;
  10232. sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
  10233. rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
  10234. if( rc ){
  10235. utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
  10236. }else{
  10237. rc = SQLITE_CORRUPT;
  10238. }
  10239. sqlite3_free(zErr);
  10240. free(zQ2);
  10241. }
  10242. return rc;
  10243. }
  10244. /*
  10245. ** Text of help messages.
  10246. **
  10247. ** The help text for each individual command begins with a line that starts
  10248. ** with ".". Subsequent lines are supplimental information.
  10249. **
  10250. ** There must be two or more spaces between the end of the command and the
  10251. ** start of the description of what that command does.
  10252. */
  10253. static const char *(azHelp[]) = {
  10254. #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
  10255. ".archive ... Manage SQL archives",
  10256. " Each command must have exactly one of the following options:",
  10257. " -c, --create Create a new archive",
  10258. " -u, --update Add files or update files with changed mtime",
  10259. " -i, --insert Like -u but always add even if mtime unchanged",
  10260. " -t, --list List contents of archive",
  10261. " -x, --extract Extract files from archive",
  10262. " Optional arguments:",
  10263. " -v, --verbose Print each filename as it is processed",
  10264. " -f FILE, --file FILE Operate on archive FILE (default is current db)",
  10265. " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS",
  10266. " -C DIR, --directory DIR Change to directory DIR to read/extract files",
  10267. " -n, --dryrun Show the SQL that would have occurred",
  10268. " Examples:",
  10269. " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar",
  10270. " .ar -tf archive.sar # List members of archive.sar",
  10271. " .ar -xvf archive.sar # Verbosely extract files from archive.sar",
  10272. " See also:",
  10273. " http://sqlite.org/cli.html#sqlar_archive_support",
  10274. #endif
  10275. #ifndef SQLITE_OMIT_AUTHORIZATION
  10276. ".auth ON|OFF Show authorizer callbacks",
  10277. #endif
  10278. ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
  10279. " --append Use the appendvfs",
  10280. " --async Write to FILE without a journal and without fsync()",
  10281. ".bail on|off Stop after hitting an error. Default OFF",
  10282. ".binary on|off Turn binary output on or off. Default OFF",
  10283. ".cd DIRECTORY Change the working directory to DIRECTORY",
  10284. ".changes on|off Show number of rows changed by SQL",
  10285. ".check GLOB Fail if output since .testcase does not match",
  10286. ".clone NEWDB Clone data into NEWDB from the existing database",
  10287. ".databases List names and files of attached databases",
  10288. ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
  10289. ".dbinfo ?DB? Show status information about the database",
  10290. ".dump ?TABLE? ... Render all database content as SQL",
  10291. " Options:",
  10292. " --preserve-rowids Include ROWID values in the output",
  10293. " --newlines Allow unescaped newline characters in output",
  10294. " TABLE is LIKE pattern for the tables to dump",
  10295. ".echo on|off Turn command echo on or off",
  10296. ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
  10297. " Other Modes:",
  10298. #ifdef SQLITE_DEBUG
  10299. " test Show raw EXPLAIN QUERY PLAN output",
  10300. " trace Like \"full\" but also enable \"PRAGMA vdbe_trace\"",
  10301. #endif
  10302. " trigger Like \"full\" but also show trigger bytecode",
  10303. ".excel Display the output of next command in a spreadsheet",
  10304. ".exit ?CODE? Exit this program with return-code CODE",
  10305. ".expert EXPERIMENTAL. Suggest indexes for specified queries",
  10306. /* Because explain mode comes on automatically now, the ".explain" mode
  10307. ** is removed from the help screen. It is still supported for legacy, however */
  10308. /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic",*/
  10309. ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
  10310. ".headers on|off Turn display of headers on or off",
  10311. ".help ?-all? ?PATTERN? Show help text for PATTERN",
  10312. ".import FILE TABLE Import data from FILE into TABLE",
  10313. #ifndef SQLITE_OMIT_TEST_CONTROL
  10314. ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
  10315. #endif
  10316. ".indexes ?TABLE? Show names of indexes",
  10317. " If TABLE is specified, only show indexes for",
  10318. " tables matching TABLE using the LIKE operator.",
  10319. #ifdef SQLITE_ENABLE_IOTRACE
  10320. ".iotrace FILE Enable I/O diagnostic logging to FILE",
  10321. #endif
  10322. ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
  10323. ".lint OPTIONS Report potential schema issues.",
  10324. " Options:",
  10325. " fkey-indexes Find missing foreign key indexes",
  10326. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  10327. ".load FILE ?ENTRY? Load an extension library",
  10328. #endif
  10329. ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
  10330. ".mode MODE ?TABLE? Set output mode",
  10331. " MODE is one of:",
  10332. " ascii Columns/rows delimited by 0x1F and 0x1E",
  10333. " csv Comma-separated values",
  10334. " column Left-aligned columns. (See .width)",
  10335. " html HTML <table> code",
  10336. " insert SQL insert statements for TABLE",
  10337. " line One value per line",
  10338. " list Values delimited by \"|\"",
  10339. " quote Escape answers as for SQL",
  10340. " tabs Tab-separated values",
  10341. " tcl TCL list elements",
  10342. ".nullvalue STRING Use STRING in place of NULL values",
  10343. ".once (-e|-x|FILE) Output for the next SQL command only to FILE",
  10344. " If FILE begins with '|' then open as a pipe",
  10345. " Other options:",
  10346. " -e Invoke system text editor",
  10347. " -x Open in a spreadsheet",
  10348. ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
  10349. " Options:",
  10350. " --append Use appendvfs to append database to the end of FILE",
  10351. #ifdef SQLITE_ENABLE_DESERIALIZE
  10352. " --deserialize Load into memory useing sqlite3_deserialize()",
  10353. " --hexdb Load the output of \"dbtotxt\" as an in-memory database",
  10354. " --maxsize N Maximum size for --hexdb or --deserialized database",
  10355. #endif
  10356. " --new Initialize FILE to an empty database",
  10357. " --readonly Open FILE readonly",
  10358. " --zip FILE is a ZIP archive",
  10359. ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
  10360. " If FILE begins with '|' then open it as a pipe.",
  10361. ".parameter CMD ... Manage SQL parameter bindings",
  10362. " clear Erase all bindings",
  10363. " init Initialize the TEMP table that holds bindings",
  10364. " list List the current parameter bindings",
  10365. " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
  10366. " PARAMETER should start with '$', ':', '@', or '?'",
  10367. " unset PARAMETER Remove PARAMETER from the binding table",
  10368. ".print STRING... Print literal STRING",
  10369. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  10370. ".progress N Invoke progress handler after every N opcodes",
  10371. " --limit N Interrupt after N progress callbacks",
  10372. " --once Do no more than one progress interrupt",
  10373. " --quiet|-q No output except at interrupts",
  10374. " --reset Reset the count for each input and interrupt",
  10375. #endif
  10376. ".prompt MAIN CONTINUE Replace the standard prompts",
  10377. ".quit Exit this program",
  10378. ".read FILE Read input from FILE",
  10379. ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
  10380. ".save FILE Write in-memory database into FILE",
  10381. ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
  10382. ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
  10383. " Options:",
  10384. " --indent Try to pretty-print the schema",
  10385. ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
  10386. " Options:",
  10387. " --init Create a new SELFTEST table",
  10388. " -v Verbose output",
  10389. ".separator COL ?ROW? Change the column and row separators",
  10390. #if defined(SQLITE_ENABLE_SESSION)
  10391. ".session ?NAME? CMD ... Create or control sessions",
  10392. " Subcommands:",
  10393. " attach TABLE Attach TABLE",
  10394. " changeset FILE Write a changeset into FILE",
  10395. " close Close one session",
  10396. " enable ?BOOLEAN? Set or query the enable bit",
  10397. " filter GLOB... Reject tables matching GLOBs",
  10398. " indirect ?BOOLEAN? Mark or query the indirect status",
  10399. " isempty Query whether the session is empty",
  10400. " list List currently open session names",
  10401. " open DB NAME Open a new session on DB",
  10402. " patchset FILE Write a patchset into FILE",
  10403. " If ?NAME? is omitted, the first defined session is used.",
  10404. #endif
  10405. ".sha3sum ... Compute a SHA3 hash of database content",
  10406. " Options:",
  10407. " --schema Also hash the sqlite_master table",
  10408. " --sha3-224 Use the sha3-224 algorithm",
  10409. " --sha3-256 Use the sha3-256 algorithm. This is the default.",
  10410. " --sha3-384 Use the sha3-384 algorithm",
  10411. " --sha3-512 Use the sha3-512 algorithm",
  10412. " Any other argument is a LIKE pattern for tables to hash",
  10413. #ifndef SQLITE_NOHAVE_SYSTEM
  10414. ".shell CMD ARGS... Run CMD ARGS... in a system shell",
  10415. #endif
  10416. ".show Show the current values for various settings",
  10417. ".stats ?on|off? Show stats or turn stats on or off",
  10418. #ifndef SQLITE_NOHAVE_SYSTEM
  10419. ".system CMD ARGS... Run CMD ARGS... in a system shell",
  10420. #endif
  10421. ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
  10422. ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
  10423. ".timeout MS Try opening locked tables for MS milliseconds",
  10424. ".timer on|off Turn SQL timer on or off",
  10425. #ifndef SQLITE_OMIT_TRACE
  10426. ".trace ?OPTIONS? Output each SQL statement as it is run",
  10427. " FILE Send output to FILE",
  10428. " stdout Send output to stdout",
  10429. " stderr Send output to stderr",
  10430. " off Disable tracing",
  10431. " --expanded Expand query parameters",
  10432. #ifdef SQLITE_ENABLE_NORMALIZE
  10433. " --normalized Normal the SQL statements",
  10434. #endif
  10435. " --plain Show SQL as it is input",
  10436. " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
  10437. " --profile Profile statements (SQLITE_TRACE_PROFILE)",
  10438. " --row Trace each row (SQLITE_TRACE_ROW)",
  10439. " --close Trace connection close (SQLITE_TRACE_CLOSE)",
  10440. #endif /* SQLITE_OMIT_TRACE */
  10441. ".vfsinfo ?AUX? Information about the top-level VFS",
  10442. ".vfslist List all available VFSes",
  10443. ".vfsname ?AUX? Print the name of the VFS stack",
  10444. ".width NUM1 NUM2 ... Set column widths for \"column\" mode",
  10445. " Negative values right-justify",
  10446. };
  10447. /*
  10448. ** Output help text.
  10449. **
  10450. ** zPattern describes the set of commands for which help text is provided.
  10451. ** If zPattern is NULL, then show all commands, but only give a one-line
  10452. ** description of each.
  10453. **
  10454. ** Return the number of matches.
  10455. */
  10456. static int showHelp(FILE *out, const char *zPattern){
  10457. int i = 0;
  10458. int j = 0;
  10459. int n = 0;
  10460. char *zPat;
  10461. if( zPattern==0
  10462. || zPattern[0]=='0'
  10463. || strcmp(zPattern,"-a")==0
  10464. || strcmp(zPattern,"-all")==0
  10465. ){
  10466. /* Show all commands, but only one line per command */
  10467. if( zPattern==0 ) zPattern = "";
  10468. for(i=0; i<ArraySize(azHelp); i++){
  10469. if( azHelp[i][0]=='.' || zPattern[0] ){
  10470. utf8_printf(out, "%s\n", azHelp[i]);
  10471. n++;
  10472. }
  10473. }
  10474. }else{
  10475. /* Look for commands that for which zPattern is an exact prefix */
  10476. zPat = sqlite3_mprintf(".%s*", zPattern);
  10477. for(i=0; i<ArraySize(azHelp); i++){
  10478. if( sqlite3_strglob(zPat, azHelp[i])==0 ){
  10479. utf8_printf(out, "%s\n", azHelp[i]);
  10480. j = i+1;
  10481. n++;
  10482. }
  10483. }
  10484. sqlite3_free(zPat);
  10485. if( n ){
  10486. if( n==1 ){
  10487. /* when zPattern is a prefix of exactly one command, then include the
  10488. ** details of that command, which should begin at offset j */
  10489. while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
  10490. utf8_printf(out, "%s\n", azHelp[j]);
  10491. j++;
  10492. }
  10493. }
  10494. return n;
  10495. }
  10496. /* Look for commands that contain zPattern anywhere. Show the complete
  10497. ** text of all commands that match. */
  10498. zPat = sqlite3_mprintf("%%%s%%", zPattern);
  10499. for(i=0; i<ArraySize(azHelp); i++){
  10500. if( azHelp[i][0]=='.' ) j = i;
  10501. if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
  10502. utf8_printf(out, "%s\n", azHelp[j]);
  10503. while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
  10504. j++;
  10505. utf8_printf(out, "%s\n", azHelp[j]);
  10506. }
  10507. i = j;
  10508. n++;
  10509. }
  10510. }
  10511. sqlite3_free(zPat);
  10512. }
  10513. return n;
  10514. }
  10515. /* Forward reference */
  10516. static int process_input(ShellState *p);
  10517. /*
  10518. ** Read the content of file zName into memory obtained from sqlite3_malloc64()
  10519. ** and return a pointer to the buffer. The caller is responsible for freeing
  10520. ** the memory.
  10521. **
  10522. ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
  10523. ** read.
  10524. **
  10525. ** For convenience, a nul-terminator byte is always appended to the data read
  10526. ** from the file before the buffer is returned. This byte is not included in
  10527. ** the final value of (*pnByte), if applicable.
  10528. **
  10529. ** NULL is returned if any error is encountered. The final value of *pnByte
  10530. ** is undefined in this case.
  10531. */
  10532. static char *readFile(const char *zName, int *pnByte){
  10533. FILE *in = fopen(zName, "rb");
  10534. long nIn;
  10535. size_t nRead;
  10536. char *pBuf;
  10537. if( in==0 ) return 0;
  10538. fseek(in, 0, SEEK_END);
  10539. nIn = ftell(in);
  10540. rewind(in);
  10541. pBuf = sqlite3_malloc64( nIn+1 );
  10542. if( pBuf==0 ){ fclose(in); return 0; }
  10543. nRead = fread(pBuf, nIn, 1, in);
  10544. fclose(in);
  10545. if( nRead!=1 ){
  10546. sqlite3_free(pBuf);
  10547. return 0;
  10548. }
  10549. pBuf[nIn] = 0;
  10550. if( pnByte ) *pnByte = nIn;
  10551. return pBuf;
  10552. }
  10553. #if defined(SQLITE_ENABLE_SESSION)
  10554. /*
  10555. ** Close a single OpenSession object and release all of its associated
  10556. ** resources.
  10557. */
  10558. static void session_close(OpenSession *pSession){
  10559. int i;
  10560. sqlite3session_delete(pSession->p);
  10561. sqlite3_free(pSession->zName);
  10562. for(i=0; i<pSession->nFilter; i++){
  10563. sqlite3_free(pSession->azFilter[i]);
  10564. }
  10565. sqlite3_free(pSession->azFilter);
  10566. memset(pSession, 0, sizeof(OpenSession));
  10567. }
  10568. #endif
  10569. /*
  10570. ** Close all OpenSession objects and release all associated resources.
  10571. */
  10572. #if defined(SQLITE_ENABLE_SESSION)
  10573. static void session_close_all(ShellState *p){
  10574. int i;
  10575. for(i=0; i<p->nSession; i++){
  10576. session_close(&p->aSession[i]);
  10577. }
  10578. p->nSession = 0;
  10579. }
  10580. #else
  10581. # define session_close_all(X)
  10582. #endif
  10583. /*
  10584. ** Implementation of the xFilter function for an open session. Omit
  10585. ** any tables named by ".session filter" but let all other table through.
  10586. */
  10587. #if defined(SQLITE_ENABLE_SESSION)
  10588. static int session_filter(void *pCtx, const char *zTab){
  10589. OpenSession *pSession = (OpenSession*)pCtx;
  10590. int i;
  10591. for(i=0; i<pSession->nFilter; i++){
  10592. if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
  10593. }
  10594. return 1;
  10595. }
  10596. #endif
  10597. /*
  10598. ** Try to deduce the type of file for zName based on its content. Return
  10599. ** one of the SHELL_OPEN_* constants.
  10600. **
  10601. ** If the file does not exist or is empty but its name looks like a ZIP
  10602. ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
  10603. ** Otherwise, assume an ordinary database regardless of the filename if
  10604. ** the type cannot be determined from content.
  10605. */
  10606. int deduceDatabaseType(const char *zName, int dfltZip){
  10607. FILE *f = fopen(zName, "rb");
  10608. size_t n;
  10609. int rc = SHELL_OPEN_UNSPEC;
  10610. char zBuf[100];
  10611. if( f==0 ){
  10612. if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
  10613. return SHELL_OPEN_ZIPFILE;
  10614. }else{
  10615. return SHELL_OPEN_NORMAL;
  10616. }
  10617. }
  10618. n = fread(zBuf, 16, 1, f);
  10619. if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
  10620. fclose(f);
  10621. return SHELL_OPEN_NORMAL;
  10622. }
  10623. fseek(f, -25, SEEK_END);
  10624. n = fread(zBuf, 25, 1, f);
  10625. if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
  10626. rc = SHELL_OPEN_APPENDVFS;
  10627. }else{
  10628. fseek(f, -22, SEEK_END);
  10629. n = fread(zBuf, 22, 1, f);
  10630. if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
  10631. && zBuf[3]==0x06 ){
  10632. rc = SHELL_OPEN_ZIPFILE;
  10633. }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
  10634. rc = SHELL_OPEN_ZIPFILE;
  10635. }
  10636. }
  10637. fclose(f);
  10638. return rc;
  10639. }
  10640. #ifdef SQLITE_ENABLE_DESERIALIZE
  10641. /*
  10642. ** Reconstruct an in-memory database using the output from the "dbtotxt"
  10643. ** program. Read content from the file in p->zDbFilename. If p->zDbFilename
  10644. ** is 0, then read from standard input.
  10645. */
  10646. static unsigned char *readHexDb(ShellState *p, int *pnData){
  10647. unsigned char *a = 0;
  10648. int nLine;
  10649. int n = 0;
  10650. int pgsz = 0;
  10651. int iOffset = 0;
  10652. int j, k;
  10653. int rc;
  10654. FILE *in;
  10655. unsigned char x[16];
  10656. char zLine[1000];
  10657. if( p->zDbFilename ){
  10658. in = fopen(p->zDbFilename, "r");
  10659. if( in==0 ){
  10660. utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
  10661. return 0;
  10662. }
  10663. nLine = 0;
  10664. }else{
  10665. in = p->in;
  10666. nLine = p->lineno;
  10667. }
  10668. *pnData = 0;
  10669. nLine++;
  10670. if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
  10671. rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
  10672. if( rc!=2 ) goto readHexDb_error;
  10673. if( n<=0 ) goto readHexDb_error;
  10674. a = sqlite3_malloc( n );
  10675. if( a==0 ){
  10676. utf8_printf(stderr, "Out of memory!\n");
  10677. goto readHexDb_error;
  10678. }
  10679. memset(a, 0, n);
  10680. if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
  10681. utf8_printf(stderr, "invalid pagesize\n");
  10682. goto readHexDb_error;
  10683. }
  10684. for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
  10685. rc = sscanf(zLine, "| page %d offset %d", &j, &k);
  10686. if( rc==2 ){
  10687. iOffset = k;
  10688. continue;
  10689. }
  10690. if( strncmp(zLine, "| end ", 6)==0 ){
  10691. break;
  10692. }
  10693. rc = sscanf(zLine,"| %d: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx"
  10694. " %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx",
  10695. &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
  10696. &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
  10697. if( rc==17 ){
  10698. k = iOffset+j;
  10699. if( k+16<=n ){
  10700. memcpy(a+k, x, 16);
  10701. }
  10702. }
  10703. }
  10704. *pnData = n;
  10705. if( in!=p->in ){
  10706. fclose(in);
  10707. }else{
  10708. p->lineno = nLine;
  10709. }
  10710. return a;
  10711. readHexDb_error:
  10712. if( in!=stdin ){
  10713. fclose(in);
  10714. }else{
  10715. while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
  10716. nLine++;
  10717. if(strncmp(zLine, "| end ", 6)==0 ) break;
  10718. }
  10719. p->lineno = nLine;
  10720. }
  10721. sqlite3_free(a);
  10722. utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
  10723. return 0;
  10724. }
  10725. #endif /* SQLITE_ENABLE_DESERIALIZE */
  10726. /* Flags for open_db().
  10727. **
  10728. ** The default behavior of open_db() is to exit(1) if the database fails to
  10729. ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
  10730. ** but still returns without calling exit.
  10731. **
  10732. ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
  10733. ** ZIP archive if the file does not exist or is empty and its name matches
  10734. ** the *.zip pattern.
  10735. */
  10736. #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
  10737. #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
  10738. /*
  10739. ** Make sure the database is open. If it is not, then open it. If
  10740. ** the database fails to open, print an error message and exit.
  10741. */
  10742. static void open_db(ShellState *p, int openFlags){
  10743. if( p->db==0 ){
  10744. if( p->openMode==SHELL_OPEN_UNSPEC ){
  10745. if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
  10746. p->openMode = SHELL_OPEN_NORMAL;
  10747. }else{
  10748. p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
  10749. (openFlags & OPEN_DB_ZIPFILE)!=0);
  10750. }
  10751. }
  10752. switch( p->openMode ){
  10753. case SHELL_OPEN_APPENDVFS: {
  10754. sqlite3_open_v2(p->zDbFilename, &p->db,
  10755. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
  10756. break;
  10757. }
  10758. case SHELL_OPEN_HEXDB:
  10759. case SHELL_OPEN_DESERIALIZE: {
  10760. sqlite3_open(0, &p->db);
  10761. break;
  10762. }
  10763. case SHELL_OPEN_ZIPFILE: {
  10764. sqlite3_open(":memory:", &p->db);
  10765. break;
  10766. }
  10767. case SHELL_OPEN_READONLY: {
  10768. sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
  10769. break;
  10770. }
  10771. case SHELL_OPEN_UNSPEC:
  10772. case SHELL_OPEN_NORMAL: {
  10773. sqlite3_open(p->zDbFilename, &p->db);
  10774. break;
  10775. }
  10776. }
  10777. globalDb = p->db;
  10778. if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
  10779. utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
  10780. p->zDbFilename, sqlite3_errmsg(p->db));
  10781. if( openFlags & OPEN_DB_KEEPALIVE ){
  10782. sqlite3_open(":memory:", &p->db);
  10783. return;
  10784. }
  10785. exit(1);
  10786. }
  10787. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  10788. sqlite3_enable_load_extension(p->db, 1);
  10789. #endif
  10790. sqlite3_fileio_init(p->db, 0, 0);
  10791. sqlite3_shathree_init(p->db, 0, 0);
  10792. sqlite3_completion_init(p->db, 0, 0);
  10793. #ifdef SQLITE_HAVE_ZLIB
  10794. sqlite3_zipfile_init(p->db, 0, 0);
  10795. sqlite3_sqlar_init(p->db, 0, 0);
  10796. #endif
  10797. sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
  10798. shellAddSchemaName, 0, 0);
  10799. sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
  10800. shellModuleSchema, 0, 0);
  10801. sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
  10802. shellPutsFunc, 0, 0);
  10803. #ifndef SQLITE_NOHAVE_SYSTEM
  10804. sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
  10805. editFunc, 0, 0);
  10806. sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
  10807. editFunc, 0, 0);
  10808. #endif
  10809. if( p->openMode==SHELL_OPEN_ZIPFILE ){
  10810. char *zSql = sqlite3_mprintf(
  10811. "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
  10812. sqlite3_exec(p->db, zSql, 0, 0, 0);
  10813. sqlite3_free(zSql);
  10814. }
  10815. #ifdef SQLITE_ENABLE_DESERIALIZE
  10816. else
  10817. if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
  10818. int rc;
  10819. int nData = 0;
  10820. unsigned char *aData;
  10821. if( p->openMode==SHELL_OPEN_DESERIALIZE ){
  10822. aData = (unsigned char*)readFile(p->zDbFilename, &nData);
  10823. }else{
  10824. aData = readHexDb(p, &nData);
  10825. if( aData==0 ){
  10826. utf8_printf(stderr, "Error in hexdb input\n");
  10827. return;
  10828. }
  10829. }
  10830. rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
  10831. SQLITE_DESERIALIZE_RESIZEABLE |
  10832. SQLITE_DESERIALIZE_FREEONCLOSE);
  10833. if( rc ){
  10834. utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
  10835. }
  10836. if( p->szMax>0 ){
  10837. sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
  10838. }
  10839. }
  10840. #endif
  10841. }
  10842. }
  10843. /*
  10844. ** Attempt to close the databaes connection. Report errors.
  10845. */
  10846. void close_db(sqlite3 *db){
  10847. int rc = sqlite3_close(db);
  10848. if( rc ){
  10849. utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
  10850. rc, sqlite3_errmsg(db));
  10851. }
  10852. }
  10853. #if HAVE_READLINE || HAVE_EDITLINE
  10854. /*
  10855. ** Readline completion callbacks
  10856. */
  10857. static char *readline_completion_generator(const char *text, int state){
  10858. static sqlite3_stmt *pStmt = 0;
  10859. char *zRet;
  10860. if( state==0 ){
  10861. char *zSql;
  10862. sqlite3_finalize(pStmt);
  10863. zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
  10864. " FROM completion(%Q) ORDER BY 1", text);
  10865. sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
  10866. sqlite3_free(zSql);
  10867. }
  10868. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  10869. zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
  10870. }else{
  10871. sqlite3_finalize(pStmt);
  10872. pStmt = 0;
  10873. zRet = 0;
  10874. }
  10875. return zRet;
  10876. }
  10877. static char **readline_completion(const char *zText, int iStart, int iEnd){
  10878. rl_attempted_completion_over = 1;
  10879. return rl_completion_matches(zText, readline_completion_generator);
  10880. }
  10881. #elif HAVE_LINENOISE
  10882. /*
  10883. ** Linenoise completion callback
  10884. */
  10885. static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
  10886. int nLine = strlen30(zLine);
  10887. int i, iStart;
  10888. sqlite3_stmt *pStmt = 0;
  10889. char *zSql;
  10890. char zBuf[1000];
  10891. if( nLine>sizeof(zBuf)-30 ) return;
  10892. if( zLine[0]=='.' || zLine[0]=='#') return;
  10893. for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
  10894. if( i==nLine-1 ) return;
  10895. iStart = i+1;
  10896. memcpy(zBuf, zLine, iStart);
  10897. zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
  10898. " FROM completion(%Q,%Q) ORDER BY 1",
  10899. &zLine[iStart], zLine);
  10900. sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
  10901. sqlite3_free(zSql);
  10902. sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
  10903. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  10904. const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
  10905. int nCompletion = sqlite3_column_bytes(pStmt, 0);
  10906. if( iStart+nCompletion < sizeof(zBuf)-1 ){
  10907. memcpy(zBuf+iStart, zCompletion, nCompletion+1);
  10908. linenoiseAddCompletion(lc, zBuf);
  10909. }
  10910. }
  10911. sqlite3_finalize(pStmt);
  10912. }
  10913. #endif
  10914. /*
  10915. ** Do C-language style dequoting.
  10916. **
  10917. ** \a -> alarm
  10918. ** \b -> backspace
  10919. ** \t -> tab
  10920. ** \n -> newline
  10921. ** \v -> vertical tab
  10922. ** \f -> form feed
  10923. ** \r -> carriage return
  10924. ** \s -> space
  10925. ** \" -> "
  10926. ** \' -> '
  10927. ** \\ -> backslash
  10928. ** \NNN -> ascii character NNN in octal
  10929. */
  10930. static void resolve_backslashes(char *z){
  10931. int i, j;
  10932. char c;
  10933. while( *z && *z!='\\' ) z++;
  10934. for(i=j=0; (c = z[i])!=0; i++, j++){
  10935. if( c=='\\' && z[i+1]!=0 ){
  10936. c = z[++i];
  10937. if( c=='a' ){
  10938. c = '\a';
  10939. }else if( c=='b' ){
  10940. c = '\b';
  10941. }else if( c=='t' ){
  10942. c = '\t';
  10943. }else if( c=='n' ){
  10944. c = '\n';
  10945. }else if( c=='v' ){
  10946. c = '\v';
  10947. }else if( c=='f' ){
  10948. c = '\f';
  10949. }else if( c=='r' ){
  10950. c = '\r';
  10951. }else if( c=='"' ){
  10952. c = '"';
  10953. }else if( c=='\'' ){
  10954. c = '\'';
  10955. }else if( c=='\\' ){
  10956. c = '\\';
  10957. }else if( c>='0' && c<='7' ){
  10958. c -= '0';
  10959. if( z[i+1]>='0' && z[i+1]<='7' ){
  10960. i++;
  10961. c = (c<<3) + z[i] - '0';
  10962. if( z[i+1]>='0' && z[i+1]<='7' ){
  10963. i++;
  10964. c = (c<<3) + z[i] - '0';
  10965. }
  10966. }
  10967. }
  10968. }
  10969. z[j] = c;
  10970. }
  10971. if( j<i ) z[j] = 0;
  10972. }
  10973. /*
  10974. ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
  10975. ** for TRUE and FALSE. Return the integer value if appropriate.
  10976. */
  10977. static int booleanValue(const char *zArg){
  10978. int i;
  10979. if( zArg[0]=='0' && zArg[1]=='x' ){
  10980. for(i=2; hexDigitValue(zArg[i])>=0; i++){}
  10981. }else{
  10982. for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
  10983. }
  10984. if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
  10985. if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
  10986. return 1;
  10987. }
  10988. if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
  10989. return 0;
  10990. }
  10991. utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
  10992. zArg);
  10993. return 0;
  10994. }
  10995. /*
  10996. ** Set or clear a shell flag according to a boolean value.
  10997. */
  10998. static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
  10999. if( booleanValue(zArg) ){
  11000. ShellSetFlag(p, mFlag);
  11001. }else{
  11002. ShellClearFlag(p, mFlag);
  11003. }
  11004. }
  11005. /*
  11006. ** Close an output file, assuming it is not stderr or stdout
  11007. */
  11008. static void output_file_close(FILE *f){
  11009. if( f && f!=stdout && f!=stderr ) fclose(f);
  11010. }
  11011. /*
  11012. ** Try to open an output file. The names "stdout" and "stderr" are
  11013. ** recognized and do the right thing. NULL is returned if the output
  11014. ** filename is "off".
  11015. */
  11016. static FILE *output_file_open(const char *zFile, int bTextMode){
  11017. FILE *f;
  11018. if( strcmp(zFile,"stdout")==0 ){
  11019. f = stdout;
  11020. }else if( strcmp(zFile, "stderr")==0 ){
  11021. f = stderr;
  11022. }else if( strcmp(zFile, "off")==0 ){
  11023. f = 0;
  11024. }else{
  11025. f = fopen(zFile, bTextMode ? "w" : "wb");
  11026. if( f==0 ){
  11027. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  11028. }
  11029. }
  11030. return f;
  11031. }
  11032. #ifndef SQLITE_OMIT_TRACE
  11033. /*
  11034. ** A routine for handling output from sqlite3_trace().
  11035. */
  11036. static int sql_trace_callback(
  11037. unsigned mType, /* The trace type */
  11038. void *pArg, /* The ShellState pointer */
  11039. void *pP, /* Usually a pointer to sqlite_stmt */
  11040. void *pX /* Auxiliary output */
  11041. ){
  11042. ShellState *p = (ShellState*)pArg;
  11043. sqlite3_stmt *pStmt;
  11044. const char *zSql;
  11045. int nSql;
  11046. if( p->traceOut==0 ) return 0;
  11047. if( mType==SQLITE_TRACE_CLOSE ){
  11048. utf8_printf(p->traceOut, "-- closing database connection\n");
  11049. return 0;
  11050. }
  11051. if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
  11052. zSql = (const char*)pX;
  11053. }else{
  11054. pStmt = (sqlite3_stmt*)pP;
  11055. switch( p->eTraceType ){
  11056. case SHELL_TRACE_EXPANDED: {
  11057. zSql = sqlite3_expanded_sql(pStmt);
  11058. break;
  11059. }
  11060. #ifdef SQLITE_ENABLE_NORMALIZE
  11061. case SHELL_TRACE_NORMALIZED: {
  11062. zSql = sqlite3_normalized_sql(pStmt);
  11063. break;
  11064. }
  11065. #endif
  11066. default: {
  11067. zSql = sqlite3_sql(pStmt);
  11068. break;
  11069. }
  11070. }
  11071. }
  11072. if( zSql==0 ) return 0;
  11073. nSql = strlen30(zSql);
  11074. while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
  11075. switch( mType ){
  11076. case SQLITE_TRACE_ROW:
  11077. case SQLITE_TRACE_STMT: {
  11078. utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
  11079. break;
  11080. }
  11081. case SQLITE_TRACE_PROFILE: {
  11082. sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
  11083. utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
  11084. break;
  11085. }
  11086. }
  11087. return 0;
  11088. }
  11089. #endif
  11090. /*
  11091. ** A no-op routine that runs with the ".breakpoint" doc-command. This is
  11092. ** a useful spot to set a debugger breakpoint.
  11093. */
  11094. static void test_breakpoint(void){
  11095. static int nCall = 0;
  11096. nCall++;
  11097. }
  11098. /*
  11099. ** An object used to read a CSV and other files for import.
  11100. */
  11101. typedef struct ImportCtx ImportCtx;
  11102. struct ImportCtx {
  11103. const char *zFile; /* Name of the input file */
  11104. FILE *in; /* Read the CSV text from this input stream */
  11105. char *z; /* Accumulated text for a field */
  11106. int n; /* Number of bytes in z */
  11107. int nAlloc; /* Space allocated for z[] */
  11108. int nLine; /* Current line number */
  11109. int bNotFirst; /* True if one or more bytes already read */
  11110. int cTerm; /* Character that terminated the most recent field */
  11111. int cColSep; /* The column separator character. (Usually ",") */
  11112. int cRowSep; /* The row separator character. (Usually "\n") */
  11113. };
  11114. /* Append a single byte to z[] */
  11115. static void import_append_char(ImportCtx *p, int c){
  11116. if( p->n+1>=p->nAlloc ){
  11117. p->nAlloc += p->nAlloc + 100;
  11118. p->z = sqlite3_realloc64(p->z, p->nAlloc);
  11119. if( p->z==0 ) shell_out_of_memory();
  11120. }
  11121. p->z[p->n++] = (char)c;
  11122. }
  11123. /* Read a single field of CSV text. Compatible with rfc4180 and extended
  11124. ** with the option of having a separator other than ",".
  11125. **
  11126. ** + Input comes from p->in.
  11127. ** + Store results in p->z of length p->n. Space to hold p->z comes
  11128. ** from sqlite3_malloc64().
  11129. ** + Use p->cSep as the column separator. The default is ",".
  11130. ** + Use p->rSep as the row separator. The default is "\n".
  11131. ** + Keep track of the line number in p->nLine.
  11132. ** + Store the character that terminates the field in p->cTerm. Store
  11133. ** EOF on end-of-file.
  11134. ** + Report syntax errors on stderr
  11135. */
  11136. static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
  11137. int c;
  11138. int cSep = p->cColSep;
  11139. int rSep = p->cRowSep;
  11140. p->n = 0;
  11141. c = fgetc(p->in);
  11142. if( c==EOF || seenInterrupt ){
  11143. p->cTerm = EOF;
  11144. return 0;
  11145. }
  11146. if( c=='"' ){
  11147. int pc, ppc;
  11148. int startLine = p->nLine;
  11149. int cQuote = c;
  11150. pc = ppc = 0;
  11151. while( 1 ){
  11152. c = fgetc(p->in);
  11153. if( c==rSep ) p->nLine++;
  11154. if( c==cQuote ){
  11155. if( pc==cQuote ){
  11156. pc = 0;
  11157. continue;
  11158. }
  11159. }
  11160. if( (c==cSep && pc==cQuote)
  11161. || (c==rSep && pc==cQuote)
  11162. || (c==rSep && pc=='\r' && ppc==cQuote)
  11163. || (c==EOF && pc==cQuote)
  11164. ){
  11165. do{ p->n--; }while( p->z[p->n]!=cQuote );
  11166. p->cTerm = c;
  11167. break;
  11168. }
  11169. if( pc==cQuote && c!='\r' ){
  11170. utf8_printf(stderr, "%s:%d: unescaped %c character\n",
  11171. p->zFile, p->nLine, cQuote);
  11172. }
  11173. if( c==EOF ){
  11174. utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
  11175. p->zFile, startLine, cQuote);
  11176. p->cTerm = c;
  11177. break;
  11178. }
  11179. import_append_char(p, c);
  11180. ppc = pc;
  11181. pc = c;
  11182. }
  11183. }else{
  11184. /* If this is the first field being parsed and it begins with the
  11185. ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
  11186. if( (c&0xff)==0xef && p->bNotFirst==0 ){
  11187. import_append_char(p, c);
  11188. c = fgetc(p->in);
  11189. if( (c&0xff)==0xbb ){
  11190. import_append_char(p, c);
  11191. c = fgetc(p->in);
  11192. if( (c&0xff)==0xbf ){
  11193. p->bNotFirst = 1;
  11194. p->n = 0;
  11195. return csv_read_one_field(p);
  11196. }
  11197. }
  11198. }
  11199. while( c!=EOF && c!=cSep && c!=rSep ){
  11200. import_append_char(p, c);
  11201. c = fgetc(p->in);
  11202. }
  11203. if( c==rSep ){
  11204. p->nLine++;
  11205. if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
  11206. }
  11207. p->cTerm = c;
  11208. }
  11209. if( p->z ) p->z[p->n] = 0;
  11210. p->bNotFirst = 1;
  11211. return p->z;
  11212. }
  11213. /* Read a single field of ASCII delimited text.
  11214. **
  11215. ** + Input comes from p->in.
  11216. ** + Store results in p->z of length p->n. Space to hold p->z comes
  11217. ** from sqlite3_malloc64().
  11218. ** + Use p->cSep as the column separator. The default is "\x1F".
  11219. ** + Use p->rSep as the row separator. The default is "\x1E".
  11220. ** + Keep track of the row number in p->nLine.
  11221. ** + Store the character that terminates the field in p->cTerm. Store
  11222. ** EOF on end-of-file.
  11223. ** + Report syntax errors on stderr
  11224. */
  11225. static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
  11226. int c;
  11227. int cSep = p->cColSep;
  11228. int rSep = p->cRowSep;
  11229. p->n = 0;
  11230. c = fgetc(p->in);
  11231. if( c==EOF || seenInterrupt ){
  11232. p->cTerm = EOF;
  11233. return 0;
  11234. }
  11235. while( c!=EOF && c!=cSep && c!=rSep ){
  11236. import_append_char(p, c);
  11237. c = fgetc(p->in);
  11238. }
  11239. if( c==rSep ){
  11240. p->nLine++;
  11241. }
  11242. p->cTerm = c;
  11243. if( p->z ) p->z[p->n] = 0;
  11244. return p->z;
  11245. }
  11246. /*
  11247. ** Try to transfer data for table zTable. If an error is seen while
  11248. ** moving forward, try to go backwards. The backwards movement won't
  11249. ** work for WITHOUT ROWID tables.
  11250. */
  11251. static void tryToCloneData(
  11252. ShellState *p,
  11253. sqlite3 *newDb,
  11254. const char *zTable
  11255. ){
  11256. sqlite3_stmt *pQuery = 0;
  11257. sqlite3_stmt *pInsert = 0;
  11258. char *zQuery = 0;
  11259. char *zInsert = 0;
  11260. int rc;
  11261. int i, j, n;
  11262. int nTable = strlen30(zTable);
  11263. int k = 0;
  11264. int cnt = 0;
  11265. const int spinRate = 10000;
  11266. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
  11267. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  11268. if( rc ){
  11269. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  11270. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  11271. zQuery);
  11272. goto end_data_xfer;
  11273. }
  11274. n = sqlite3_column_count(pQuery);
  11275. zInsert = sqlite3_malloc64(200 + nTable + n*3);
  11276. if( zInsert==0 ) shell_out_of_memory();
  11277. sqlite3_snprintf(200+nTable,zInsert,
  11278. "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
  11279. i = strlen30(zInsert);
  11280. for(j=1; j<n; j++){
  11281. memcpy(zInsert+i, ",?", 2);
  11282. i += 2;
  11283. }
  11284. memcpy(zInsert+i, ");", 3);
  11285. rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
  11286. if( rc ){
  11287. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  11288. sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
  11289. zQuery);
  11290. goto end_data_xfer;
  11291. }
  11292. for(k=0; k<2; k++){
  11293. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  11294. for(i=0; i<n; i++){
  11295. switch( sqlite3_column_type(pQuery, i) ){
  11296. case SQLITE_NULL: {
  11297. sqlite3_bind_null(pInsert, i+1);
  11298. break;
  11299. }
  11300. case SQLITE_INTEGER: {
  11301. sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
  11302. break;
  11303. }
  11304. case SQLITE_FLOAT: {
  11305. sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
  11306. break;
  11307. }
  11308. case SQLITE_TEXT: {
  11309. sqlite3_bind_text(pInsert, i+1,
  11310. (const char*)sqlite3_column_text(pQuery,i),
  11311. -1, SQLITE_STATIC);
  11312. break;
  11313. }
  11314. case SQLITE_BLOB: {
  11315. sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
  11316. sqlite3_column_bytes(pQuery,i),
  11317. SQLITE_STATIC);
  11318. break;
  11319. }
  11320. }
  11321. } /* End for */
  11322. rc = sqlite3_step(pInsert);
  11323. if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  11324. utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
  11325. sqlite3_errmsg(newDb));
  11326. }
  11327. sqlite3_reset(pInsert);
  11328. cnt++;
  11329. if( (cnt%spinRate)==0 ){
  11330. printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
  11331. fflush(stdout);
  11332. }
  11333. } /* End while */
  11334. if( rc==SQLITE_DONE ) break;
  11335. sqlite3_finalize(pQuery);
  11336. sqlite3_free(zQuery);
  11337. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
  11338. zTable);
  11339. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  11340. if( rc ){
  11341. utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
  11342. break;
  11343. }
  11344. } /* End for(k=0...) */
  11345. end_data_xfer:
  11346. sqlite3_finalize(pQuery);
  11347. sqlite3_finalize(pInsert);
  11348. sqlite3_free(zQuery);
  11349. sqlite3_free(zInsert);
  11350. }
  11351. /*
  11352. ** Try to transfer all rows of the schema that match zWhere. For
  11353. ** each row, invoke xForEach() on the object defined by that row.
  11354. ** If an error is encountered while moving forward through the
  11355. ** sqlite_master table, try again moving backwards.
  11356. */
  11357. static void tryToCloneSchema(
  11358. ShellState *p,
  11359. sqlite3 *newDb,
  11360. const char *zWhere,
  11361. void (*xForEach)(ShellState*,sqlite3*,const char*)
  11362. ){
  11363. sqlite3_stmt *pQuery = 0;
  11364. char *zQuery = 0;
  11365. int rc;
  11366. const unsigned char *zName;
  11367. const unsigned char *zSql;
  11368. char *zErrMsg = 0;
  11369. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  11370. " WHERE %s", zWhere);
  11371. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  11372. if( rc ){
  11373. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  11374. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  11375. zQuery);
  11376. goto end_schema_xfer;
  11377. }
  11378. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  11379. zName = sqlite3_column_text(pQuery, 0);
  11380. zSql = sqlite3_column_text(pQuery, 1);
  11381. printf("%s... ", zName); fflush(stdout);
  11382. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  11383. if( zErrMsg ){
  11384. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  11385. sqlite3_free(zErrMsg);
  11386. zErrMsg = 0;
  11387. }
  11388. if( xForEach ){
  11389. xForEach(p, newDb, (const char*)zName);
  11390. }
  11391. printf("done\n");
  11392. }
  11393. if( rc!=SQLITE_DONE ){
  11394. sqlite3_finalize(pQuery);
  11395. sqlite3_free(zQuery);
  11396. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  11397. " WHERE %s ORDER BY rowid DESC", zWhere);
  11398. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  11399. if( rc ){
  11400. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  11401. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  11402. zQuery);
  11403. goto end_schema_xfer;
  11404. }
  11405. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  11406. zName = sqlite3_column_text(pQuery, 0);
  11407. zSql = sqlite3_column_text(pQuery, 1);
  11408. printf("%s... ", zName); fflush(stdout);
  11409. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  11410. if( zErrMsg ){
  11411. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  11412. sqlite3_free(zErrMsg);
  11413. zErrMsg = 0;
  11414. }
  11415. if( xForEach ){
  11416. xForEach(p, newDb, (const char*)zName);
  11417. }
  11418. printf("done\n");
  11419. }
  11420. }
  11421. end_schema_xfer:
  11422. sqlite3_finalize(pQuery);
  11423. sqlite3_free(zQuery);
  11424. }
  11425. /*
  11426. ** Open a new database file named "zNewDb". Try to recover as much information
  11427. ** as possible out of the main database (which might be corrupt) and write it
  11428. ** into zNewDb.
  11429. */
  11430. static void tryToClone(ShellState *p, const char *zNewDb){
  11431. int rc;
  11432. sqlite3 *newDb = 0;
  11433. if( access(zNewDb,0)==0 ){
  11434. utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
  11435. return;
  11436. }
  11437. rc = sqlite3_open(zNewDb, &newDb);
  11438. if( rc ){
  11439. utf8_printf(stderr, "Cannot create output database: %s\n",
  11440. sqlite3_errmsg(newDb));
  11441. }else{
  11442. sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
  11443. sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
  11444. tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
  11445. tryToCloneSchema(p, newDb, "type!='table'", 0);
  11446. sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
  11447. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  11448. }
  11449. close_db(newDb);
  11450. }
  11451. /*
  11452. ** Change the output file back to stdout.
  11453. **
  11454. ** If the p->doXdgOpen flag is set, that means the output was being
  11455. ** redirected to a temporary file named by p->zTempFile. In that case,
  11456. ** launch start/open/xdg-open on that temporary file.
  11457. */
  11458. static void output_reset(ShellState *p){
  11459. if( p->outfile[0]=='|' ){
  11460. #ifndef SQLITE_OMIT_POPEN
  11461. pclose(p->out);
  11462. #endif
  11463. }else{
  11464. output_file_close(p->out);
  11465. #ifndef SQLITE_NOHAVE_SYSTEM
  11466. if( p->doXdgOpen ){
  11467. const char *zXdgOpenCmd =
  11468. #if defined(_WIN32)
  11469. "start";
  11470. #elif defined(__APPLE__)
  11471. "open";
  11472. #else
  11473. "xdg-open";
  11474. #endif
  11475. char *zCmd;
  11476. zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
  11477. if( system(zCmd) ){
  11478. utf8_printf(stderr, "Failed: [%s]\n", zCmd);
  11479. }
  11480. sqlite3_free(zCmd);
  11481. outputModePop(p);
  11482. p->doXdgOpen = 0;
  11483. }
  11484. #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
  11485. }
  11486. p->outfile[0] = 0;
  11487. p->out = stdout;
  11488. }
  11489. /*
  11490. ** Run an SQL command and return the single integer result.
  11491. */
  11492. static int db_int(ShellState *p, const char *zSql){
  11493. sqlite3_stmt *pStmt;
  11494. int res = 0;
  11495. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  11496. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  11497. res = sqlite3_column_int(pStmt,0);
  11498. }
  11499. sqlite3_finalize(pStmt);
  11500. return res;
  11501. }
  11502. /*
  11503. ** Convert a 2-byte or 4-byte big-endian integer into a native integer
  11504. */
  11505. static unsigned int get2byteInt(unsigned char *a){
  11506. return (a[0]<<8) + a[1];
  11507. }
  11508. static unsigned int get4byteInt(unsigned char *a){
  11509. return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
  11510. }
  11511. /*
  11512. ** Implementation of the ".info" command.
  11513. **
  11514. ** Return 1 on error, 2 to exit, and 0 otherwise.
  11515. */
  11516. static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
  11517. static const struct { const char *zName; int ofst; } aField[] = {
  11518. { "file change counter:", 24 },
  11519. { "database page count:", 28 },
  11520. { "freelist page count:", 36 },
  11521. { "schema cookie:", 40 },
  11522. { "schema format:", 44 },
  11523. { "default cache size:", 48 },
  11524. { "autovacuum top root:", 52 },
  11525. { "incremental vacuum:", 64 },
  11526. { "text encoding:", 56 },
  11527. { "user version:", 60 },
  11528. { "application id:", 68 },
  11529. { "software version:", 96 },
  11530. };
  11531. static const struct { const char *zName; const char *zSql; } aQuery[] = {
  11532. { "number of tables:",
  11533. "SELECT count(*) FROM %s WHERE type='table'" },
  11534. { "number of indexes:",
  11535. "SELECT count(*) FROM %s WHERE type='index'" },
  11536. { "number of triggers:",
  11537. "SELECT count(*) FROM %s WHERE type='trigger'" },
  11538. { "number of views:",
  11539. "SELECT count(*) FROM %s WHERE type='view'" },
  11540. { "schema size:",
  11541. "SELECT total(length(sql)) FROM %s" },
  11542. };
  11543. int i, rc;
  11544. unsigned iDataVersion;
  11545. char *zSchemaTab;
  11546. char *zDb = nArg>=2 ? azArg[1] : "main";
  11547. sqlite3_stmt *pStmt = 0;
  11548. unsigned char aHdr[100];
  11549. open_db(p, 0);
  11550. if( p->db==0 ) return 1;
  11551. rc = sqlite3_prepare_v2(p->db,
  11552. "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
  11553. -1, &pStmt, 0);
  11554. if( rc ){
  11555. if( !sqlite3_compileoption_used("ENABLE_DBPAGE_VTAB") ){
  11556. utf8_printf(stderr, "the \".dbinfo\" command requires the "
  11557. "-DSQLITE_ENABLE_DBPAGE_VTAB compile-time options\n");
  11558. }else{
  11559. utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
  11560. }
  11561. sqlite3_finalize(pStmt);
  11562. return 1;
  11563. }
  11564. sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
  11565. if( sqlite3_step(pStmt)==SQLITE_ROW
  11566. && sqlite3_column_bytes(pStmt,0)>100
  11567. ){
  11568. memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
  11569. sqlite3_finalize(pStmt);
  11570. }else{
  11571. raw_printf(stderr, "unable to read database header\n");
  11572. sqlite3_finalize(pStmt);
  11573. return 1;
  11574. }
  11575. i = get2byteInt(aHdr+16);
  11576. if( i==1 ) i = 65536;
  11577. utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
  11578. utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
  11579. utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
  11580. utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
  11581. for(i=0; i<ArraySize(aField); i++){
  11582. int ofst = aField[i].ofst;
  11583. unsigned int val = get4byteInt(aHdr + ofst);
  11584. utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
  11585. switch( ofst ){
  11586. case 56: {
  11587. if( val==1 ) raw_printf(p->out, " (utf8)");
  11588. if( val==2 ) raw_printf(p->out, " (utf16le)");
  11589. if( val==3 ) raw_printf(p->out, " (utf16be)");
  11590. }
  11591. }
  11592. raw_printf(p->out, "\n");
  11593. }
  11594. if( zDb==0 ){
  11595. zSchemaTab = sqlite3_mprintf("main.sqlite_master");
  11596. }else if( strcmp(zDb,"temp")==0 ){
  11597. zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
  11598. }else{
  11599. zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
  11600. }
  11601. for(i=0; i<ArraySize(aQuery); i++){
  11602. char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
  11603. int val = db_int(p, zSql);
  11604. sqlite3_free(zSql);
  11605. utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
  11606. }
  11607. sqlite3_free(zSchemaTab);
  11608. sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
  11609. utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
  11610. return 0;
  11611. }
  11612. /*
  11613. ** Print the current sqlite3_errmsg() value to stderr and return 1.
  11614. */
  11615. static int shellDatabaseError(sqlite3 *db){
  11616. const char *zErr = sqlite3_errmsg(db);
  11617. utf8_printf(stderr, "Error: %s\n", zErr);
  11618. return 1;
  11619. }
  11620. /*
  11621. ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
  11622. ** if they match and FALSE (0) if they do not match.
  11623. **
  11624. ** Globbing rules:
  11625. **
  11626. ** '*' Matches any sequence of zero or more characters.
  11627. **
  11628. ** '?' Matches exactly one character.
  11629. **
  11630. ** [...] Matches one character from the enclosed list of
  11631. ** characters.
  11632. **
  11633. ** [^...] Matches one character not in the enclosed list.
  11634. **
  11635. ** '#' Matches any sequence of one or more digits with an
  11636. ** optional + or - sign in front
  11637. **
  11638. ** ' ' Any span of whitespace matches any other span of
  11639. ** whitespace.
  11640. **
  11641. ** Extra whitespace at the end of z[] is ignored.
  11642. */
  11643. static int testcase_glob(const char *zGlob, const char *z){
  11644. int c, c2;
  11645. int invert;
  11646. int seen;
  11647. while( (c = (*(zGlob++)))!=0 ){
  11648. if( IsSpace(c) ){
  11649. if( !IsSpace(*z) ) return 0;
  11650. while( IsSpace(*zGlob) ) zGlob++;
  11651. while( IsSpace(*z) ) z++;
  11652. }else if( c=='*' ){
  11653. while( (c=(*(zGlob++))) == '*' || c=='?' ){
  11654. if( c=='?' && (*(z++))==0 ) return 0;
  11655. }
  11656. if( c==0 ){
  11657. return 1;
  11658. }else if( c=='[' ){
  11659. while( *z && testcase_glob(zGlob-1,z)==0 ){
  11660. z++;
  11661. }
  11662. return (*z)!=0;
  11663. }
  11664. while( (c2 = (*(z++)))!=0 ){
  11665. while( c2!=c ){
  11666. c2 = *(z++);
  11667. if( c2==0 ) return 0;
  11668. }
  11669. if( testcase_glob(zGlob,z) ) return 1;
  11670. }
  11671. return 0;
  11672. }else if( c=='?' ){
  11673. if( (*(z++))==0 ) return 0;
  11674. }else if( c=='[' ){
  11675. int prior_c = 0;
  11676. seen = 0;
  11677. invert = 0;
  11678. c = *(z++);
  11679. if( c==0 ) return 0;
  11680. c2 = *(zGlob++);
  11681. if( c2=='^' ){
  11682. invert = 1;
  11683. c2 = *(zGlob++);
  11684. }
  11685. if( c2==']' ){
  11686. if( c==']' ) seen = 1;
  11687. c2 = *(zGlob++);
  11688. }
  11689. while( c2 && c2!=']' ){
  11690. if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
  11691. c2 = *(zGlob++);
  11692. if( c>=prior_c && c<=c2 ) seen = 1;
  11693. prior_c = 0;
  11694. }else{
  11695. if( c==c2 ){
  11696. seen = 1;
  11697. }
  11698. prior_c = c2;
  11699. }
  11700. c2 = *(zGlob++);
  11701. }
  11702. if( c2==0 || (seen ^ invert)==0 ) return 0;
  11703. }else if( c=='#' ){
  11704. if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
  11705. if( !IsDigit(z[0]) ) return 0;
  11706. z++;
  11707. while( IsDigit(z[0]) ){ z++; }
  11708. }else{
  11709. if( c!=(*(z++)) ) return 0;
  11710. }
  11711. }
  11712. while( IsSpace(*z) ){ z++; }
  11713. return *z==0;
  11714. }
  11715. /*
  11716. ** Compare the string as a command-line option with either one or two
  11717. ** initial "-" characters.
  11718. */
  11719. static int optionMatch(const char *zStr, const char *zOpt){
  11720. if( zStr[0]!='-' ) return 0;
  11721. zStr++;
  11722. if( zStr[0]=='-' ) zStr++;
  11723. return strcmp(zStr, zOpt)==0;
  11724. }
  11725. /*
  11726. ** Delete a file.
  11727. */
  11728. int shellDeleteFile(const char *zFilename){
  11729. int rc;
  11730. #ifdef _WIN32
  11731. wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
  11732. rc = _wunlink(z);
  11733. sqlite3_free(z);
  11734. #else
  11735. rc = unlink(zFilename);
  11736. #endif
  11737. return rc;
  11738. }
  11739. /*
  11740. ** Try to delete the temporary file (if there is one) and free the
  11741. ** memory used to hold the name of the temp file.
  11742. */
  11743. static void clearTempFile(ShellState *p){
  11744. if( p->zTempFile==0 ) return;
  11745. if( p->doXdgOpen ) return;
  11746. if( shellDeleteFile(p->zTempFile) ) return;
  11747. sqlite3_free(p->zTempFile);
  11748. p->zTempFile = 0;
  11749. }
  11750. /*
  11751. ** Create a new temp file name with the given suffix.
  11752. */
  11753. static void newTempFile(ShellState *p, const char *zSuffix){
  11754. clearTempFile(p);
  11755. sqlite3_free(p->zTempFile);
  11756. p->zTempFile = 0;
  11757. if( p->db ){
  11758. sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
  11759. }
  11760. if( p->zTempFile==0 ){
  11761. sqlite3_uint64 r;
  11762. sqlite3_randomness(sizeof(r), &r);
  11763. p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
  11764. }else{
  11765. p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
  11766. }
  11767. if( p->zTempFile==0 ){
  11768. raw_printf(stderr, "out of memory\n");
  11769. exit(1);
  11770. }
  11771. }
  11772. /*
  11773. ** The implementation of SQL scalar function fkey_collate_clause(), used
  11774. ** by the ".lint fkey-indexes" command. This scalar function is always
  11775. ** called with four arguments - the parent table name, the parent column name,
  11776. ** the child table name and the child column name.
  11777. **
  11778. ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
  11779. **
  11780. ** If either of the named tables or columns do not exist, this function
  11781. ** returns an empty string. An empty string is also returned if both tables
  11782. ** and columns exist but have the same default collation sequence. Or,
  11783. ** if both exist but the default collation sequences are different, this
  11784. ** function returns the string " COLLATE <parent-collation>", where
  11785. ** <parent-collation> is the default collation sequence of the parent column.
  11786. */
  11787. static void shellFkeyCollateClause(
  11788. sqlite3_context *pCtx,
  11789. int nVal,
  11790. sqlite3_value **apVal
  11791. ){
  11792. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  11793. const char *zParent;
  11794. const char *zParentCol;
  11795. const char *zParentSeq;
  11796. const char *zChild;
  11797. const char *zChildCol;
  11798. const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
  11799. int rc;
  11800. assert( nVal==4 );
  11801. zParent = (const char*)sqlite3_value_text(apVal[0]);
  11802. zParentCol = (const char*)sqlite3_value_text(apVal[1]);
  11803. zChild = (const char*)sqlite3_value_text(apVal[2]);
  11804. zChildCol = (const char*)sqlite3_value_text(apVal[3]);
  11805. sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
  11806. rc = sqlite3_table_column_metadata(
  11807. db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
  11808. );
  11809. if( rc==SQLITE_OK ){
  11810. rc = sqlite3_table_column_metadata(
  11811. db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
  11812. );
  11813. }
  11814. if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
  11815. char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
  11816. sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
  11817. sqlite3_free(z);
  11818. }
  11819. }
  11820. /*
  11821. ** The implementation of dot-command ".lint fkey-indexes".
  11822. */
  11823. static int lintFkeyIndexes(
  11824. ShellState *pState, /* Current shell tool state */
  11825. char **azArg, /* Array of arguments passed to dot command */
  11826. int nArg /* Number of entries in azArg[] */
  11827. ){
  11828. sqlite3 *db = pState->db; /* Database handle to query "main" db of */
  11829. FILE *out = pState->out; /* Stream to write non-error output to */
  11830. int bVerbose = 0; /* If -verbose is present */
  11831. int bGroupByParent = 0; /* If -groupbyparent is present */
  11832. int i; /* To iterate through azArg[] */
  11833. const char *zIndent = ""; /* How much to indent CREATE INDEX by */
  11834. int rc; /* Return code */
  11835. sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
  11836. /*
  11837. ** This SELECT statement returns one row for each foreign key constraint
  11838. ** in the schema of the main database. The column values are:
  11839. **
  11840. ** 0. The text of an SQL statement similar to:
  11841. **
  11842. ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
  11843. **
  11844. ** This SELECT is similar to the one that the foreign keys implementation
  11845. ** needs to run internally on child tables. If there is an index that can
  11846. ** be used to optimize this query, then it can also be used by the FK
  11847. ** implementation to optimize DELETE or UPDATE statements on the parent
  11848. ** table.
  11849. **
  11850. ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
  11851. ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
  11852. ** contains an index that can be used to optimize the query.
  11853. **
  11854. ** 2. Human readable text that describes the child table and columns. e.g.
  11855. **
  11856. ** "child_table(child_key1, child_key2)"
  11857. **
  11858. ** 3. Human readable text that describes the parent table and columns. e.g.
  11859. **
  11860. ** "parent_table(parent_key1, parent_key2)"
  11861. **
  11862. ** 4. A full CREATE INDEX statement for an index that could be used to
  11863. ** optimize DELETE or UPDATE statements on the parent table. e.g.
  11864. **
  11865. ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
  11866. **
  11867. ** 5. The name of the parent table.
  11868. **
  11869. ** These six values are used by the C logic below to generate the report.
  11870. */
  11871. const char *zSql =
  11872. "SELECT "
  11873. " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
  11874. " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
  11875. " || fkey_collate_clause("
  11876. " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
  11877. ", "
  11878. " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
  11879. " || group_concat('*=?', ' AND ') || ')'"
  11880. ", "
  11881. " s.name || '(' || group_concat(f.[from], ', ') || ')'"
  11882. ", "
  11883. " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
  11884. ", "
  11885. " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
  11886. " || ' ON ' || quote(s.name) || '('"
  11887. " || group_concat(quote(f.[from]) ||"
  11888. " fkey_collate_clause("
  11889. " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
  11890. " || ');'"
  11891. ", "
  11892. " f.[table] "
  11893. "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
  11894. "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
  11895. "GROUP BY s.name, f.id "
  11896. "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
  11897. ;
  11898. const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
  11899. for(i=2; i<nArg; i++){
  11900. int n = strlen30(azArg[i]);
  11901. if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
  11902. bVerbose = 1;
  11903. }
  11904. else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
  11905. bGroupByParent = 1;
  11906. zIndent = " ";
  11907. }
  11908. else{
  11909. raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
  11910. azArg[0], azArg[1]
  11911. );
  11912. return SQLITE_ERROR;
  11913. }
  11914. }
  11915. /* Register the fkey_collate_clause() SQL function */
  11916. rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
  11917. 0, shellFkeyCollateClause, 0, 0
  11918. );
  11919. if( rc==SQLITE_OK ){
  11920. rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
  11921. }
  11922. if( rc==SQLITE_OK ){
  11923. sqlite3_bind_int(pSql, 1, bGroupByParent);
  11924. }
  11925. if( rc==SQLITE_OK ){
  11926. int rc2;
  11927. char *zPrev = 0;
  11928. while( SQLITE_ROW==sqlite3_step(pSql) ){
  11929. int res = -1;
  11930. sqlite3_stmt *pExplain = 0;
  11931. const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
  11932. const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
  11933. const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
  11934. const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
  11935. const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
  11936. const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
  11937. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  11938. if( rc!=SQLITE_OK ) break;
  11939. if( SQLITE_ROW==sqlite3_step(pExplain) ){
  11940. const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
  11941. res = (
  11942. 0==sqlite3_strglob(zGlob, zPlan)
  11943. || 0==sqlite3_strglob(zGlobIPK, zPlan)
  11944. );
  11945. }
  11946. rc = sqlite3_finalize(pExplain);
  11947. if( rc!=SQLITE_OK ) break;
  11948. if( res<0 ){
  11949. raw_printf(stderr, "Error: internal error");
  11950. break;
  11951. }else{
  11952. if( bGroupByParent
  11953. && (bVerbose || res==0)
  11954. && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
  11955. ){
  11956. raw_printf(out, "-- Parent table %s\n", zParent);
  11957. sqlite3_free(zPrev);
  11958. zPrev = sqlite3_mprintf("%s", zParent);
  11959. }
  11960. if( res==0 ){
  11961. raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
  11962. }else if( bVerbose ){
  11963. raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
  11964. zIndent, zFrom, zTarget
  11965. );
  11966. }
  11967. }
  11968. }
  11969. sqlite3_free(zPrev);
  11970. if( rc!=SQLITE_OK ){
  11971. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  11972. }
  11973. rc2 = sqlite3_finalize(pSql);
  11974. if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
  11975. rc = rc2;
  11976. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  11977. }
  11978. }else{
  11979. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  11980. }
  11981. return rc;
  11982. }
  11983. /*
  11984. ** Implementation of ".lint" dot command.
  11985. */
  11986. static int lintDotCommand(
  11987. ShellState *pState, /* Current shell tool state */
  11988. char **azArg, /* Array of arguments passed to dot command */
  11989. int nArg /* Number of entries in azArg[] */
  11990. ){
  11991. int n;
  11992. n = (nArg>=2 ? strlen30(azArg[1]) : 0);
  11993. if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
  11994. return lintFkeyIndexes(pState, azArg, nArg);
  11995. usage:
  11996. raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
  11997. raw_printf(stderr, "Where sub-commands are:\n");
  11998. raw_printf(stderr, " fkey-indexes\n");
  11999. return SQLITE_ERROR;
  12000. }
  12001. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  12002. /*********************************************************************************
  12003. ** The ".archive" or ".ar" command.
  12004. */
  12005. static void shellPrepare(
  12006. sqlite3 *db,
  12007. int *pRc,
  12008. const char *zSql,
  12009. sqlite3_stmt **ppStmt
  12010. ){
  12011. *ppStmt = 0;
  12012. if( *pRc==SQLITE_OK ){
  12013. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  12014. if( rc!=SQLITE_OK ){
  12015. raw_printf(stderr, "sql error: %s (%d)\n",
  12016. sqlite3_errmsg(db), sqlite3_errcode(db)
  12017. );
  12018. *pRc = rc;
  12019. }
  12020. }
  12021. }
  12022. static void shellPreparePrintf(
  12023. sqlite3 *db,
  12024. int *pRc,
  12025. sqlite3_stmt **ppStmt,
  12026. const char *zFmt,
  12027. ...
  12028. ){
  12029. *ppStmt = 0;
  12030. if( *pRc==SQLITE_OK ){
  12031. va_list ap;
  12032. char *z;
  12033. va_start(ap, zFmt);
  12034. z = sqlite3_vmprintf(zFmt, ap);
  12035. va_end(ap);
  12036. if( z==0 ){
  12037. *pRc = SQLITE_NOMEM;
  12038. }else{
  12039. shellPrepare(db, pRc, z, ppStmt);
  12040. sqlite3_free(z);
  12041. }
  12042. }
  12043. }
  12044. static void shellFinalize(
  12045. int *pRc,
  12046. sqlite3_stmt *pStmt
  12047. ){
  12048. if( pStmt ){
  12049. sqlite3 *db = sqlite3_db_handle(pStmt);
  12050. int rc = sqlite3_finalize(pStmt);
  12051. if( *pRc==SQLITE_OK ){
  12052. if( rc!=SQLITE_OK ){
  12053. raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
  12054. }
  12055. *pRc = rc;
  12056. }
  12057. }
  12058. }
  12059. static void shellReset(
  12060. int *pRc,
  12061. sqlite3_stmt *pStmt
  12062. ){
  12063. int rc = sqlite3_reset(pStmt);
  12064. if( *pRc==SQLITE_OK ){
  12065. if( rc!=SQLITE_OK ){
  12066. sqlite3 *db = sqlite3_db_handle(pStmt);
  12067. raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
  12068. }
  12069. *pRc = rc;
  12070. }
  12071. }
  12072. /*
  12073. ** Structure representing a single ".ar" command.
  12074. */
  12075. typedef struct ArCommand ArCommand;
  12076. struct ArCommand {
  12077. u8 eCmd; /* An AR_CMD_* value */
  12078. u8 bVerbose; /* True if --verbose */
  12079. u8 bZip; /* True if the archive is a ZIP */
  12080. u8 bDryRun; /* True if --dry-run */
  12081. u8 bAppend; /* True if --append */
  12082. u8 fromCmdLine; /* Run from -A instead of .archive */
  12083. int nArg; /* Number of command arguments */
  12084. char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
  12085. const char *zFile; /* --file argument, or NULL */
  12086. const char *zDir; /* --directory argument, or NULL */
  12087. char **azArg; /* Array of command arguments */
  12088. ShellState *p; /* Shell state */
  12089. sqlite3 *db; /* Database containing the archive */
  12090. };
  12091. /*
  12092. ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
  12093. */
  12094. static int arUsage(FILE *f){
  12095. showHelp(f,"archive");
  12096. return SQLITE_ERROR;
  12097. }
  12098. /*
  12099. ** Print an error message for the .ar command to stderr and return
  12100. ** SQLITE_ERROR.
  12101. */
  12102. static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
  12103. va_list ap;
  12104. char *z;
  12105. va_start(ap, zFmt);
  12106. z = sqlite3_vmprintf(zFmt, ap);
  12107. va_end(ap);
  12108. utf8_printf(stderr, "Error: %s\n", z);
  12109. if( pAr->fromCmdLine ){
  12110. utf8_printf(stderr, "Use \"-A\" for more help\n");
  12111. }else{
  12112. utf8_printf(stderr, "Use \".archive --help\" for more help\n");
  12113. }
  12114. sqlite3_free(z);
  12115. return SQLITE_ERROR;
  12116. }
  12117. /*
  12118. ** Values for ArCommand.eCmd.
  12119. */
  12120. #define AR_CMD_CREATE 1
  12121. #define AR_CMD_UPDATE 2
  12122. #define AR_CMD_INSERT 3
  12123. #define AR_CMD_EXTRACT 4
  12124. #define AR_CMD_LIST 5
  12125. #define AR_CMD_HELP 6
  12126. /*
  12127. ** Other (non-command) switches.
  12128. */
  12129. #define AR_SWITCH_VERBOSE 7
  12130. #define AR_SWITCH_FILE 8
  12131. #define AR_SWITCH_DIRECTORY 9
  12132. #define AR_SWITCH_APPEND 10
  12133. #define AR_SWITCH_DRYRUN 11
  12134. static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
  12135. switch( eSwitch ){
  12136. case AR_CMD_CREATE:
  12137. case AR_CMD_EXTRACT:
  12138. case AR_CMD_LIST:
  12139. case AR_CMD_UPDATE:
  12140. case AR_CMD_INSERT:
  12141. case AR_CMD_HELP:
  12142. if( pAr->eCmd ){
  12143. return arErrorMsg(pAr, "multiple command options");
  12144. }
  12145. pAr->eCmd = eSwitch;
  12146. break;
  12147. case AR_SWITCH_DRYRUN:
  12148. pAr->bDryRun = 1;
  12149. break;
  12150. case AR_SWITCH_VERBOSE:
  12151. pAr->bVerbose = 1;
  12152. break;
  12153. case AR_SWITCH_APPEND:
  12154. pAr->bAppend = 1;
  12155. /* Fall thru into --file */
  12156. case AR_SWITCH_FILE:
  12157. pAr->zFile = zArg;
  12158. break;
  12159. case AR_SWITCH_DIRECTORY:
  12160. pAr->zDir = zArg;
  12161. break;
  12162. }
  12163. return SQLITE_OK;
  12164. }
  12165. /*
  12166. ** Parse the command line for an ".ar" command. The results are written into
  12167. ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
  12168. ** successfully, otherwise an error message is written to stderr and
  12169. ** SQLITE_ERROR returned.
  12170. */
  12171. static int arParseCommand(
  12172. char **azArg, /* Array of arguments passed to dot command */
  12173. int nArg, /* Number of entries in azArg[] */
  12174. ArCommand *pAr /* Populate this object */
  12175. ){
  12176. struct ArSwitch {
  12177. const char *zLong;
  12178. char cShort;
  12179. u8 eSwitch;
  12180. u8 bArg;
  12181. } aSwitch[] = {
  12182. { "create", 'c', AR_CMD_CREATE, 0 },
  12183. { "extract", 'x', AR_CMD_EXTRACT, 0 },
  12184. { "insert", 'i', AR_CMD_INSERT, 0 },
  12185. { "list", 't', AR_CMD_LIST, 0 },
  12186. { "update", 'u', AR_CMD_UPDATE, 0 },
  12187. { "help", 'h', AR_CMD_HELP, 0 },
  12188. { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
  12189. { "file", 'f', AR_SWITCH_FILE, 1 },
  12190. { "append", 'a', AR_SWITCH_APPEND, 1 },
  12191. { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
  12192. { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
  12193. };
  12194. int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
  12195. struct ArSwitch *pEnd = &aSwitch[nSwitch];
  12196. if( nArg<=1 ){
  12197. utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
  12198. return arUsage(stderr);
  12199. }else{
  12200. char *z = azArg[1];
  12201. if( z[0]!='-' ){
  12202. /* Traditional style [tar] invocation */
  12203. int i;
  12204. int iArg = 2;
  12205. for(i=0; z[i]; i++){
  12206. const char *zArg = 0;
  12207. struct ArSwitch *pOpt;
  12208. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  12209. if( z[i]==pOpt->cShort ) break;
  12210. }
  12211. if( pOpt==pEnd ){
  12212. return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
  12213. }
  12214. if( pOpt->bArg ){
  12215. if( iArg>=nArg ){
  12216. return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
  12217. }
  12218. zArg = azArg[iArg++];
  12219. }
  12220. if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
  12221. }
  12222. pAr->nArg = nArg-iArg;
  12223. if( pAr->nArg>0 ){
  12224. pAr->azArg = &azArg[iArg];
  12225. }
  12226. }else{
  12227. /* Non-traditional invocation */
  12228. int iArg;
  12229. for(iArg=1; iArg<nArg; iArg++){
  12230. int n;
  12231. z = azArg[iArg];
  12232. if( z[0]!='-' ){
  12233. /* All remaining command line words are command arguments. */
  12234. pAr->azArg = &azArg[iArg];
  12235. pAr->nArg = nArg-iArg;
  12236. break;
  12237. }
  12238. n = strlen30(z);
  12239. if( z[1]!='-' ){
  12240. int i;
  12241. /* One or more short options */
  12242. for(i=1; i<n; i++){
  12243. const char *zArg = 0;
  12244. struct ArSwitch *pOpt;
  12245. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  12246. if( z[i]==pOpt->cShort ) break;
  12247. }
  12248. if( pOpt==pEnd ){
  12249. return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
  12250. }
  12251. if( pOpt->bArg ){
  12252. if( i<(n-1) ){
  12253. zArg = &z[i+1];
  12254. i = n;
  12255. }else{
  12256. if( iArg>=(nArg-1) ){
  12257. return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
  12258. }
  12259. zArg = azArg[++iArg];
  12260. }
  12261. }
  12262. if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
  12263. }
  12264. }else if( z[2]=='\0' ){
  12265. /* A -- option, indicating that all remaining command line words
  12266. ** are command arguments. */
  12267. pAr->azArg = &azArg[iArg+1];
  12268. pAr->nArg = nArg-iArg-1;
  12269. break;
  12270. }else{
  12271. /* A long option */
  12272. const char *zArg = 0; /* Argument for option, if any */
  12273. struct ArSwitch *pMatch = 0; /* Matching option */
  12274. struct ArSwitch *pOpt; /* Iterator */
  12275. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  12276. const char *zLong = pOpt->zLong;
  12277. if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
  12278. if( pMatch ){
  12279. return arErrorMsg(pAr, "ambiguous option: %s",z);
  12280. }else{
  12281. pMatch = pOpt;
  12282. }
  12283. }
  12284. }
  12285. if( pMatch==0 ){
  12286. return arErrorMsg(pAr, "unrecognized option: %s", z);
  12287. }
  12288. if( pMatch->bArg ){
  12289. if( iArg>=(nArg-1) ){
  12290. return arErrorMsg(pAr, "option requires an argument: %s", z);
  12291. }
  12292. zArg = azArg[++iArg];
  12293. }
  12294. if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
  12295. }
  12296. }
  12297. }
  12298. }
  12299. return SQLITE_OK;
  12300. }
  12301. /*
  12302. ** This function assumes that all arguments within the ArCommand.azArg[]
  12303. ** array refer to archive members, as for the --extract or --list commands.
  12304. ** It checks that each of them are present. If any specified file is not
  12305. ** present in the archive, an error is printed to stderr and an error
  12306. ** code returned. Otherwise, if all specified arguments are present in
  12307. ** the archive, SQLITE_OK is returned.
  12308. **
  12309. ** This function strips any trailing '/' characters from each argument.
  12310. ** This is consistent with the way the [tar] command seems to work on
  12311. ** Linux.
  12312. */
  12313. static int arCheckEntries(ArCommand *pAr){
  12314. int rc = SQLITE_OK;
  12315. if( pAr->nArg ){
  12316. int i, j;
  12317. sqlite3_stmt *pTest = 0;
  12318. shellPreparePrintf(pAr->db, &rc, &pTest,
  12319. "SELECT name FROM %s WHERE name=$name",
  12320. pAr->zSrcTable
  12321. );
  12322. j = sqlite3_bind_parameter_index(pTest, "$name");
  12323. for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
  12324. char *z = pAr->azArg[i];
  12325. int n = strlen30(z);
  12326. int bOk = 0;
  12327. while( n>0 && z[n-1]=='/' ) n--;
  12328. z[n] = '\0';
  12329. sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
  12330. if( SQLITE_ROW==sqlite3_step(pTest) ){
  12331. bOk = 1;
  12332. }
  12333. shellReset(&rc, pTest);
  12334. if( rc==SQLITE_OK && bOk==0 ){
  12335. utf8_printf(stderr, "not found in archive: %s\n", z);
  12336. rc = SQLITE_ERROR;
  12337. }
  12338. }
  12339. shellFinalize(&rc, pTest);
  12340. }
  12341. return rc;
  12342. }
  12343. /*
  12344. ** Format a WHERE clause that can be used against the "sqlar" table to
  12345. ** identify all archive members that match the command arguments held
  12346. ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
  12347. ** The caller is responsible for eventually calling sqlite3_free() on
  12348. ** any non-NULL (*pzWhere) value.
  12349. */
  12350. static void arWhereClause(
  12351. int *pRc,
  12352. ArCommand *pAr,
  12353. char **pzWhere /* OUT: New WHERE clause */
  12354. ){
  12355. char *zWhere = 0;
  12356. if( *pRc==SQLITE_OK ){
  12357. if( pAr->nArg==0 ){
  12358. zWhere = sqlite3_mprintf("1");
  12359. }else{
  12360. int i;
  12361. const char *zSep = "";
  12362. for(i=0; i<pAr->nArg; i++){
  12363. const char *z = pAr->azArg[i];
  12364. zWhere = sqlite3_mprintf(
  12365. "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
  12366. zWhere, zSep, z, strlen30(z)+1, z
  12367. );
  12368. if( zWhere==0 ){
  12369. *pRc = SQLITE_NOMEM;
  12370. break;
  12371. }
  12372. zSep = " OR ";
  12373. }
  12374. }
  12375. }
  12376. *pzWhere = zWhere;
  12377. }
  12378. /*
  12379. ** Implementation of .ar "lisT" command.
  12380. */
  12381. static int arListCommand(ArCommand *pAr){
  12382. const char *zSql = "SELECT %s FROM %s WHERE %s";
  12383. const char *azCols[] = {
  12384. "name",
  12385. "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
  12386. };
  12387. char *zWhere = 0;
  12388. sqlite3_stmt *pSql = 0;
  12389. int rc;
  12390. rc = arCheckEntries(pAr);
  12391. arWhereClause(&rc, pAr, &zWhere);
  12392. shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
  12393. pAr->zSrcTable, zWhere);
  12394. if( pAr->bDryRun ){
  12395. utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
  12396. }else{
  12397. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  12398. if( pAr->bVerbose ){
  12399. utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
  12400. sqlite3_column_text(pSql, 0),
  12401. sqlite3_column_int(pSql, 1),
  12402. sqlite3_column_text(pSql, 2),
  12403. sqlite3_column_text(pSql, 3)
  12404. );
  12405. }else{
  12406. utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
  12407. }
  12408. }
  12409. }
  12410. shellFinalize(&rc, pSql);
  12411. sqlite3_free(zWhere);
  12412. return rc;
  12413. }
  12414. /*
  12415. ** Implementation of .ar "eXtract" command.
  12416. */
  12417. static int arExtractCommand(ArCommand *pAr){
  12418. const char *zSql1 =
  12419. "SELECT "
  12420. " ($dir || name),"
  12421. " writefile(($dir || name), %s, mode, mtime) "
  12422. "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
  12423. " AND name NOT GLOB '*..[/\\]*'";
  12424. const char *azExtraArg[] = {
  12425. "sqlar_uncompress(data, sz)",
  12426. "data"
  12427. };
  12428. sqlite3_stmt *pSql = 0;
  12429. int rc = SQLITE_OK;
  12430. char *zDir = 0;
  12431. char *zWhere = 0;
  12432. int i, j;
  12433. /* If arguments are specified, check that they actually exist within
  12434. ** the archive before proceeding. And formulate a WHERE clause to
  12435. ** match them. */
  12436. rc = arCheckEntries(pAr);
  12437. arWhereClause(&rc, pAr, &zWhere);
  12438. if( rc==SQLITE_OK ){
  12439. if( pAr->zDir ){
  12440. zDir = sqlite3_mprintf("%s/", pAr->zDir);
  12441. }else{
  12442. zDir = sqlite3_mprintf("");
  12443. }
  12444. if( zDir==0 ) rc = SQLITE_NOMEM;
  12445. }
  12446. shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
  12447. azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
  12448. );
  12449. if( rc==SQLITE_OK ){
  12450. j = sqlite3_bind_parameter_index(pSql, "$dir");
  12451. sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
  12452. /* Run the SELECT statement twice. The first time, writefile() is called
  12453. ** for all archive members that should be extracted. The second time,
  12454. ** only for the directories. This is because the timestamps for
  12455. ** extracted directories must be reset after they are populated (as
  12456. ** populating them changes the timestamp). */
  12457. for(i=0; i<2; i++){
  12458. j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
  12459. sqlite3_bind_int(pSql, j, i);
  12460. if( pAr->bDryRun ){
  12461. utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
  12462. }else{
  12463. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  12464. if( i==0 && pAr->bVerbose ){
  12465. utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
  12466. }
  12467. }
  12468. }
  12469. shellReset(&rc, pSql);
  12470. }
  12471. shellFinalize(&rc, pSql);
  12472. }
  12473. sqlite3_free(zDir);
  12474. sqlite3_free(zWhere);
  12475. return rc;
  12476. }
  12477. /*
  12478. ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
  12479. */
  12480. static int arExecSql(ArCommand *pAr, const char *zSql){
  12481. int rc;
  12482. if( pAr->bDryRun ){
  12483. utf8_printf(pAr->p->out, "%s\n", zSql);
  12484. rc = SQLITE_OK;
  12485. }else{
  12486. char *zErr = 0;
  12487. rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
  12488. if( zErr ){
  12489. utf8_printf(stdout, "ERROR: %s\n", zErr);
  12490. sqlite3_free(zErr);
  12491. }
  12492. }
  12493. return rc;
  12494. }
  12495. /*
  12496. ** Implementation of .ar "create", "insert", and "update" commands.
  12497. **
  12498. ** create -> Create a new SQL archive
  12499. ** insert -> Insert or reinsert all files listed
  12500. ** update -> Insert files that have changed or that were not
  12501. ** previously in the archive
  12502. **
  12503. ** Create the "sqlar" table in the database if it does not already exist.
  12504. ** Then add each file in the azFile[] array to the archive. Directories
  12505. ** are added recursively. If argument bVerbose is non-zero, a message is
  12506. ** printed on stdout for each file archived.
  12507. **
  12508. ** The create command is the same as update, except that it drops
  12509. ** any existing "sqlar" table before beginning. The "insert" command
  12510. ** always overwrites every file named on the command-line, where as
  12511. ** "update" only overwrites if the size or mtime or mode has changed.
  12512. */
  12513. static int arCreateOrUpdateCommand(
  12514. ArCommand *pAr, /* Command arguments and options */
  12515. int bUpdate, /* true for a --create. */
  12516. int bOnlyIfChanged /* Only update if file has changed */
  12517. ){
  12518. const char *zCreate =
  12519. "CREATE TABLE IF NOT EXISTS sqlar(\n"
  12520. " name TEXT PRIMARY KEY, -- name of the file\n"
  12521. " mode INT, -- access permissions\n"
  12522. " mtime INT, -- last modification time\n"
  12523. " sz INT, -- original file size\n"
  12524. " data BLOB -- compressed content\n"
  12525. ")";
  12526. const char *zDrop = "DROP TABLE IF EXISTS sqlar";
  12527. const char *zInsertFmt[2] = {
  12528. "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
  12529. " SELECT\n"
  12530. " %s,\n"
  12531. " mode,\n"
  12532. " mtime,\n"
  12533. " CASE substr(lsmode(mode),1,1)\n"
  12534. " WHEN '-' THEN length(data)\n"
  12535. " WHEN 'd' THEN 0\n"
  12536. " ELSE -1 END,\n"
  12537. " sqlar_compress(data)\n"
  12538. " FROM fsdir(%Q,%Q) AS disk\n"
  12539. " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
  12540. ,
  12541. "REPLACE INTO %s(name,mode,mtime,data)\n"
  12542. " SELECT\n"
  12543. " %s,\n"
  12544. " mode,\n"
  12545. " mtime,\n"
  12546. " data\n"
  12547. " FROM fsdir(%Q,%Q) AS disk\n"
  12548. " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
  12549. };
  12550. int i; /* For iterating through azFile[] */
  12551. int rc; /* Return code */
  12552. const char *zTab = 0; /* SQL table into which to insert */
  12553. char *zSql;
  12554. char zTemp[50];
  12555. char *zExists = 0;
  12556. arExecSql(pAr, "PRAGMA page_size=512");
  12557. rc = arExecSql(pAr, "SAVEPOINT ar;");
  12558. if( rc!=SQLITE_OK ) return rc;
  12559. zTemp[0] = 0;
  12560. if( pAr->bZip ){
  12561. /* Initialize the zipfile virtual table, if necessary */
  12562. if( pAr->zFile ){
  12563. sqlite3_uint64 r;
  12564. sqlite3_randomness(sizeof(r),&r);
  12565. sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
  12566. zTab = zTemp;
  12567. zSql = sqlite3_mprintf(
  12568. "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
  12569. zTab, pAr->zFile
  12570. );
  12571. rc = arExecSql(pAr, zSql);
  12572. sqlite3_free(zSql);
  12573. }else{
  12574. zTab = "zip";
  12575. }
  12576. }else{
  12577. /* Initialize the table for an SQLAR */
  12578. zTab = "sqlar";
  12579. if( bUpdate==0 ){
  12580. rc = arExecSql(pAr, zDrop);
  12581. if( rc!=SQLITE_OK ) goto end_ar_transaction;
  12582. }
  12583. rc = arExecSql(pAr, zCreate);
  12584. }
  12585. if( bOnlyIfChanged ){
  12586. zExists = sqlite3_mprintf(
  12587. " AND NOT EXISTS("
  12588. "SELECT 1 FROM %s AS mem"
  12589. " WHERE mem.name=disk.name"
  12590. " AND mem.mtime=disk.mtime"
  12591. " AND mem.mode=disk.mode)", zTab);
  12592. }else{
  12593. zExists = sqlite3_mprintf("");
  12594. }
  12595. if( zExists==0 ) rc = SQLITE_NOMEM;
  12596. for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
  12597. char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
  12598. pAr->bVerbose ? "shell_putsnl(name)" : "name",
  12599. pAr->azArg[i], pAr->zDir, zExists);
  12600. rc = arExecSql(pAr, zSql2);
  12601. sqlite3_free(zSql2);
  12602. }
  12603. end_ar_transaction:
  12604. if( rc!=SQLITE_OK ){
  12605. sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
  12606. }else{
  12607. rc = arExecSql(pAr, "RELEASE ar;");
  12608. if( pAr->bZip && pAr->zFile ){
  12609. zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
  12610. arExecSql(pAr, zSql);
  12611. sqlite3_free(zSql);
  12612. }
  12613. }
  12614. sqlite3_free(zExists);
  12615. return rc;
  12616. }
  12617. /*
  12618. ** Implementation of ".ar" dot command.
  12619. */
  12620. static int arDotCommand(
  12621. ShellState *pState, /* Current shell tool state */
  12622. int fromCmdLine, /* True if -A command-line option, not .ar cmd */
  12623. char **azArg, /* Array of arguments passed to dot command */
  12624. int nArg /* Number of entries in azArg[] */
  12625. ){
  12626. ArCommand cmd;
  12627. int rc;
  12628. memset(&cmd, 0, sizeof(cmd));
  12629. cmd.fromCmdLine = fromCmdLine;
  12630. rc = arParseCommand(azArg, nArg, &cmd);
  12631. if( rc==SQLITE_OK ){
  12632. int eDbType = SHELL_OPEN_UNSPEC;
  12633. cmd.p = pState;
  12634. cmd.db = pState->db;
  12635. if( cmd.zFile ){
  12636. eDbType = deduceDatabaseType(cmd.zFile, 1);
  12637. }else{
  12638. eDbType = pState->openMode;
  12639. }
  12640. if( eDbType==SHELL_OPEN_ZIPFILE ){
  12641. if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
  12642. if( cmd.zFile==0 ){
  12643. cmd.zSrcTable = sqlite3_mprintf("zip");
  12644. }else{
  12645. cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
  12646. }
  12647. }
  12648. cmd.bZip = 1;
  12649. }else if( cmd.zFile ){
  12650. int flags;
  12651. if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
  12652. if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
  12653. || cmd.eCmd==AR_CMD_UPDATE ){
  12654. flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
  12655. }else{
  12656. flags = SQLITE_OPEN_READONLY;
  12657. }
  12658. cmd.db = 0;
  12659. if( cmd.bDryRun ){
  12660. utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
  12661. eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
  12662. }
  12663. rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
  12664. eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
  12665. if( rc!=SQLITE_OK ){
  12666. utf8_printf(stderr, "cannot open file: %s (%s)\n",
  12667. cmd.zFile, sqlite3_errmsg(cmd.db)
  12668. );
  12669. goto end_ar_command;
  12670. }
  12671. sqlite3_fileio_init(cmd.db, 0, 0);
  12672. sqlite3_sqlar_init(cmd.db, 0, 0);
  12673. sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
  12674. shellPutsFunc, 0, 0);
  12675. }
  12676. if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
  12677. if( cmd.eCmd!=AR_CMD_CREATE
  12678. && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
  12679. ){
  12680. utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
  12681. rc = SQLITE_ERROR;
  12682. goto end_ar_command;
  12683. }
  12684. cmd.zSrcTable = sqlite3_mprintf("sqlar");
  12685. }
  12686. switch( cmd.eCmd ){
  12687. case AR_CMD_CREATE:
  12688. rc = arCreateOrUpdateCommand(&cmd, 0, 0);
  12689. break;
  12690. case AR_CMD_EXTRACT:
  12691. rc = arExtractCommand(&cmd);
  12692. break;
  12693. case AR_CMD_LIST:
  12694. rc = arListCommand(&cmd);
  12695. break;
  12696. case AR_CMD_HELP:
  12697. arUsage(pState->out);
  12698. break;
  12699. case AR_CMD_INSERT:
  12700. rc = arCreateOrUpdateCommand(&cmd, 1, 0);
  12701. break;
  12702. default:
  12703. assert( cmd.eCmd==AR_CMD_UPDATE );
  12704. rc = arCreateOrUpdateCommand(&cmd, 1, 1);
  12705. break;
  12706. }
  12707. }
  12708. end_ar_command:
  12709. if( cmd.db!=pState->db ){
  12710. close_db(cmd.db);
  12711. }
  12712. sqlite3_free(cmd.zSrcTable);
  12713. return rc;
  12714. }
  12715. /* End of the ".archive" or ".ar" command logic
  12716. **********************************************************************************/
  12717. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
  12718. /*
  12719. ** If an input line begins with "." then invoke this routine to
  12720. ** process that line.
  12721. **
  12722. ** Return 1 on error, 2 to exit, and 0 otherwise.
  12723. */
  12724. static int do_meta_command(char *zLine, ShellState *p){
  12725. int h = 1;
  12726. int nArg = 0;
  12727. int n, c;
  12728. int rc = 0;
  12729. char *azArg[50];
  12730. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12731. if( p->expert.pExpert ){
  12732. expertFinish(p, 1, 0);
  12733. }
  12734. #endif
  12735. /* Parse the input line into tokens.
  12736. */
  12737. while( zLine[h] && nArg<ArraySize(azArg) ){
  12738. while( IsSpace(zLine[h]) ){ h++; }
  12739. if( zLine[h]==0 ) break;
  12740. if( zLine[h]=='\'' || zLine[h]=='"' ){
  12741. int delim = zLine[h++];
  12742. azArg[nArg++] = &zLine[h];
  12743. while( zLine[h] && zLine[h]!=delim ){
  12744. if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
  12745. h++;
  12746. }
  12747. if( zLine[h]==delim ){
  12748. zLine[h++] = 0;
  12749. }
  12750. if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  12751. }else{
  12752. azArg[nArg++] = &zLine[h];
  12753. while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
  12754. if( zLine[h] ) zLine[h++] = 0;
  12755. resolve_backslashes(azArg[nArg-1]);
  12756. }
  12757. }
  12758. /* Process the input line.
  12759. */
  12760. if( nArg==0 ) return 0; /* no tokens, no error */
  12761. n = strlen30(azArg[0]);
  12762. c = azArg[0][0];
  12763. clearTempFile(p);
  12764. #ifndef SQLITE_OMIT_AUTHORIZATION
  12765. if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
  12766. if( nArg!=2 ){
  12767. raw_printf(stderr, "Usage: .auth ON|OFF\n");
  12768. rc = 1;
  12769. goto meta_command_exit;
  12770. }
  12771. open_db(p, 0);
  12772. if( booleanValue(azArg[1]) ){
  12773. sqlite3_set_authorizer(p->db, shellAuth, p);
  12774. }else{
  12775. sqlite3_set_authorizer(p->db, 0, 0);
  12776. }
  12777. }else
  12778. #endif
  12779. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  12780. if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
  12781. open_db(p, 0);
  12782. rc = arDotCommand(p, 0, azArg, nArg);
  12783. }else
  12784. #endif
  12785. if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
  12786. || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
  12787. ){
  12788. const char *zDestFile = 0;
  12789. const char *zDb = 0;
  12790. sqlite3 *pDest;
  12791. sqlite3_backup *pBackup;
  12792. int j;
  12793. int bAsync = 0;
  12794. const char *zVfs = 0;
  12795. for(j=1; j<nArg; j++){
  12796. const char *z = azArg[j];
  12797. if( z[0]=='-' ){
  12798. if( z[1]=='-' ) z++;
  12799. if( strcmp(z, "-append")==0 ){
  12800. zVfs = "apndvfs";
  12801. }else
  12802. if( strcmp(z, "-async")==0 ){
  12803. bAsync = 1;
  12804. }else
  12805. {
  12806. utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
  12807. return 1;
  12808. }
  12809. }else if( zDestFile==0 ){
  12810. zDestFile = azArg[j];
  12811. }else if( zDb==0 ){
  12812. zDb = zDestFile;
  12813. zDestFile = azArg[j];
  12814. }else{
  12815. raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
  12816. return 1;
  12817. }
  12818. }
  12819. if( zDestFile==0 ){
  12820. raw_printf(stderr, "missing FILENAME argument on .backup\n");
  12821. return 1;
  12822. }
  12823. if( zDb==0 ) zDb = "main";
  12824. rc = sqlite3_open_v2(zDestFile, &pDest,
  12825. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
  12826. if( rc!=SQLITE_OK ){
  12827. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  12828. close_db(pDest);
  12829. return 1;
  12830. }
  12831. if( bAsync ){
  12832. sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
  12833. 0, 0, 0);
  12834. }
  12835. open_db(p, 0);
  12836. pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  12837. if( pBackup==0 ){
  12838. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  12839. close_db(pDest);
  12840. return 1;
  12841. }
  12842. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  12843. sqlite3_backup_finish(pBackup);
  12844. if( rc==SQLITE_DONE ){
  12845. rc = 0;
  12846. }else{
  12847. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  12848. rc = 1;
  12849. }
  12850. close_db(pDest);
  12851. }else
  12852. if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
  12853. if( nArg==2 ){
  12854. bail_on_error = booleanValue(azArg[1]);
  12855. }else{
  12856. raw_printf(stderr, "Usage: .bail on|off\n");
  12857. rc = 1;
  12858. }
  12859. }else
  12860. if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
  12861. if( nArg==2 ){
  12862. if( booleanValue(azArg[1]) ){
  12863. setBinaryMode(p->out, 1);
  12864. }else{
  12865. setTextMode(p->out, 1);
  12866. }
  12867. }else{
  12868. raw_printf(stderr, "Usage: .binary on|off\n");
  12869. rc = 1;
  12870. }
  12871. }else
  12872. if( c=='c' && strcmp(azArg[0],"cd")==0 ){
  12873. if( nArg==2 ){
  12874. #if defined(_WIN32) || defined(WIN32)
  12875. wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
  12876. rc = !SetCurrentDirectoryW(z);
  12877. sqlite3_free(z);
  12878. #else
  12879. rc = chdir(azArg[1]);
  12880. #endif
  12881. if( rc ){
  12882. utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
  12883. rc = 1;
  12884. }
  12885. }else{
  12886. raw_printf(stderr, "Usage: .cd DIRECTORY\n");
  12887. rc = 1;
  12888. }
  12889. }else
  12890. /* The undocumented ".breakpoint" command causes a call to the no-op
  12891. ** routine named test_breakpoint().
  12892. */
  12893. if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
  12894. test_breakpoint();
  12895. }else
  12896. if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
  12897. if( nArg==2 ){
  12898. setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
  12899. }else{
  12900. raw_printf(stderr, "Usage: .changes on|off\n");
  12901. rc = 1;
  12902. }
  12903. }else
  12904. /* Cancel output redirection, if it is currently set (by .testcase)
  12905. ** Then read the content of the testcase-out.txt file and compare against
  12906. ** azArg[1]. If there are differences, report an error and exit.
  12907. */
  12908. if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
  12909. char *zRes = 0;
  12910. output_reset(p);
  12911. if( nArg!=2 ){
  12912. raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
  12913. rc = 2;
  12914. }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
  12915. raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
  12916. rc = 2;
  12917. }else if( testcase_glob(azArg[1],zRes)==0 ){
  12918. utf8_printf(stderr,
  12919. "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
  12920. p->zTestcase, azArg[1], zRes);
  12921. rc = 1;
  12922. }else{
  12923. utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
  12924. p->nCheck++;
  12925. }
  12926. sqlite3_free(zRes);
  12927. }else
  12928. if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
  12929. if( nArg==2 ){
  12930. tryToClone(p, azArg[1]);
  12931. }else{
  12932. raw_printf(stderr, "Usage: .clone FILENAME\n");
  12933. rc = 1;
  12934. }
  12935. }else
  12936. if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
  12937. ShellState data;
  12938. char *zErrMsg = 0;
  12939. open_db(p, 0);
  12940. memcpy(&data, p, sizeof(data));
  12941. data.showHeader = 0;
  12942. data.cMode = data.mode = MODE_List;
  12943. sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
  12944. data.cnt = 0;
  12945. sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
  12946. callback, &data, &zErrMsg);
  12947. if( zErrMsg ){
  12948. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  12949. sqlite3_free(zErrMsg);
  12950. rc = 1;
  12951. }
  12952. }else
  12953. if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
  12954. static const struct DbConfigChoices {
  12955. const char *zName;
  12956. int op;
  12957. } aDbConfig[] = {
  12958. { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
  12959. { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
  12960. { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
  12961. { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
  12962. { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
  12963. { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
  12964. { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
  12965. { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
  12966. { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
  12967. };
  12968. int ii, v;
  12969. open_db(p, 0);
  12970. for(ii=0; ii<ArraySize(aDbConfig); ii++){
  12971. if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
  12972. if( nArg>=3 ){
  12973. sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
  12974. }
  12975. sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
  12976. utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
  12977. if( nArg>1 ) break;
  12978. }
  12979. if( nArg>1 && ii==ArraySize(aDbConfig) ){
  12980. utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
  12981. utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
  12982. }
  12983. }else
  12984. if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
  12985. rc = shell_dbinfo_command(p, nArg, azArg);
  12986. }else
  12987. if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
  12988. const char *zLike = 0;
  12989. int i;
  12990. int savedShowHeader = p->showHeader;
  12991. int savedShellFlags = p->shellFlgs;
  12992. ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
  12993. for(i=1; i<nArg; i++){
  12994. if( azArg[i][0]=='-' ){
  12995. const char *z = azArg[i]+1;
  12996. if( z[0]=='-' ) z++;
  12997. if( strcmp(z,"preserve-rowids")==0 ){
  12998. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12999. raw_printf(stderr, "The --preserve-rowids option is not compatible"
  13000. " with SQLITE_OMIT_VIRTUALTABLE\n");
  13001. rc = 1;
  13002. goto meta_command_exit;
  13003. #else
  13004. ShellSetFlag(p, SHFLG_PreserveRowid);
  13005. #endif
  13006. }else
  13007. if( strcmp(z,"newlines")==0 ){
  13008. ShellSetFlag(p, SHFLG_Newlines);
  13009. }else
  13010. {
  13011. raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
  13012. rc = 1;
  13013. goto meta_command_exit;
  13014. }
  13015. }else if( zLike ){
  13016. raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
  13017. "?--newlines? ?LIKE-PATTERN?\n");
  13018. rc = 1;
  13019. goto meta_command_exit;
  13020. }else{
  13021. zLike = azArg[i];
  13022. }
  13023. }
  13024. open_db(p, 0);
  13025. /* When playing back a "dump", the content might appear in an order
  13026. ** which causes immediate foreign key constraints to be violated.
  13027. ** So disable foreign-key constraint enforcement to prevent problems. */
  13028. raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
  13029. raw_printf(p->out, "BEGIN TRANSACTION;\n");
  13030. p->writableSchema = 0;
  13031. p->showHeader = 0;
  13032. /* Set writable_schema=ON since doing so forces SQLite to initialize
  13033. ** as much of the schema as it can even if the sqlite_master table is
  13034. ** corrupt. */
  13035. sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
  13036. p->nErr = 0;
  13037. if( zLike==0 ){
  13038. run_schema_dump_query(p,
  13039. "SELECT name, type, sql FROM sqlite_master "
  13040. "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
  13041. );
  13042. run_schema_dump_query(p,
  13043. "SELECT name, type, sql FROM sqlite_master "
  13044. "WHERE name=='sqlite_sequence'"
  13045. );
  13046. run_table_dump_query(p,
  13047. "SELECT sql FROM sqlite_master "
  13048. "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
  13049. );
  13050. }else{
  13051. char *zSql;
  13052. zSql = sqlite3_mprintf(
  13053. "SELECT name, type, sql FROM sqlite_master "
  13054. "WHERE tbl_name LIKE %Q AND type=='table'"
  13055. " AND sql NOT NULL", zLike);
  13056. run_schema_dump_query(p,zSql);
  13057. sqlite3_free(zSql);
  13058. zSql = sqlite3_mprintf(
  13059. "SELECT sql FROM sqlite_master "
  13060. "WHERE sql NOT NULL"
  13061. " AND type IN ('index','trigger','view')"
  13062. " AND tbl_name LIKE %Q", zLike);
  13063. run_table_dump_query(p, zSql, 0);
  13064. sqlite3_free(zSql);
  13065. }
  13066. if( p->writableSchema ){
  13067. raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
  13068. p->writableSchema = 0;
  13069. }
  13070. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  13071. sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
  13072. raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
  13073. p->showHeader = savedShowHeader;
  13074. p->shellFlgs = savedShellFlags;
  13075. }else
  13076. if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
  13077. if( nArg==2 ){
  13078. setOrClearFlag(p, SHFLG_Echo, azArg[1]);
  13079. }else{
  13080. raw_printf(stderr, "Usage: .echo on|off\n");
  13081. rc = 1;
  13082. }
  13083. }else
  13084. if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
  13085. if( nArg==2 ){
  13086. p->autoEQPtest = 0;
  13087. if( p->autoEQPtrace ){
  13088. if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
  13089. p->autoEQPtrace = 0;
  13090. }
  13091. if( strcmp(azArg[1],"full")==0 ){
  13092. p->autoEQP = AUTOEQP_full;
  13093. }else if( strcmp(azArg[1],"trigger")==0 ){
  13094. p->autoEQP = AUTOEQP_trigger;
  13095. #ifdef SQLITE_DEBUG
  13096. }else if( strcmp(azArg[1],"test")==0 ){
  13097. p->autoEQP = AUTOEQP_on;
  13098. p->autoEQPtest = 1;
  13099. }else if( strcmp(azArg[1],"trace")==0 ){
  13100. p->autoEQP = AUTOEQP_full;
  13101. p->autoEQPtrace = 1;
  13102. open_db(p, 0);
  13103. sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0);
  13104. sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
  13105. #endif
  13106. }else{
  13107. p->autoEQP = (u8)booleanValue(azArg[1]);
  13108. }
  13109. }else{
  13110. raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
  13111. rc = 1;
  13112. }
  13113. }else
  13114. if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
  13115. if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
  13116. rc = 2;
  13117. }else
  13118. /* The ".explain" command is automatic now. It is largely pointless. It
  13119. ** retained purely for backwards compatibility */
  13120. if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
  13121. int val = 1;
  13122. if( nArg>=2 ){
  13123. if( strcmp(azArg[1],"auto")==0 ){
  13124. val = 99;
  13125. }else{
  13126. val = booleanValue(azArg[1]);
  13127. }
  13128. }
  13129. if( val==1 && p->mode!=MODE_Explain ){
  13130. p->normalMode = p->mode;
  13131. p->mode = MODE_Explain;
  13132. p->autoExplain = 0;
  13133. }else if( val==0 ){
  13134. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  13135. p->autoExplain = 0;
  13136. }else if( val==99 ){
  13137. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  13138. p->autoExplain = 1;
  13139. }
  13140. }else
  13141. #ifndef SQLITE_OMIT_VIRTUALTABLE
  13142. if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
  13143. open_db(p, 0);
  13144. expertDotCommand(p, azArg, nArg);
  13145. }else
  13146. #endif
  13147. if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
  13148. ShellState data;
  13149. char *zErrMsg = 0;
  13150. int doStats = 0;
  13151. memcpy(&data, p, sizeof(data));
  13152. data.showHeader = 0;
  13153. data.cMode = data.mode = MODE_Semi;
  13154. if( nArg==2 && optionMatch(azArg[1], "indent") ){
  13155. data.cMode = data.mode = MODE_Pretty;
  13156. nArg = 1;
  13157. }
  13158. if( nArg!=1 ){
  13159. raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
  13160. rc = 1;
  13161. goto meta_command_exit;
  13162. }
  13163. open_db(p, 0);
  13164. rc = sqlite3_exec(p->db,
  13165. "SELECT sql FROM"
  13166. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  13167. " FROM sqlite_master UNION ALL"
  13168. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  13169. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  13170. "ORDER BY rowid",
  13171. callback, &data, &zErrMsg
  13172. );
  13173. if( rc==SQLITE_OK ){
  13174. sqlite3_stmt *pStmt;
  13175. rc = sqlite3_prepare_v2(p->db,
  13176. "SELECT rowid FROM sqlite_master"
  13177. " WHERE name GLOB 'sqlite_stat[134]'",
  13178. -1, &pStmt, 0);
  13179. doStats = sqlite3_step(pStmt)==SQLITE_ROW;
  13180. sqlite3_finalize(pStmt);
  13181. }
  13182. if( doStats==0 ){
  13183. raw_printf(p->out, "/* No STAT tables available */\n");
  13184. }else{
  13185. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  13186. sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
  13187. callback, &data, &zErrMsg);
  13188. data.cMode = data.mode = MODE_Insert;
  13189. data.zDestTable = "sqlite_stat1";
  13190. shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
  13191. data.zDestTable = "sqlite_stat3";
  13192. shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
  13193. data.zDestTable = "sqlite_stat4";
  13194. shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
  13195. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  13196. }
  13197. }else
  13198. if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
  13199. if( nArg==2 ){
  13200. p->showHeader = booleanValue(azArg[1]);
  13201. }else{
  13202. raw_printf(stderr, "Usage: .headers on|off\n");
  13203. rc = 1;
  13204. }
  13205. }else
  13206. if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  13207. if( nArg>=2 ){
  13208. n = showHelp(p->out, azArg[1]);
  13209. if( n==0 ){
  13210. utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
  13211. }
  13212. }else{
  13213. showHelp(p->out, 0);
  13214. }
  13215. }else
  13216. if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
  13217. char *zTable; /* Insert data into this table */
  13218. char *zFile; /* Name of file to extra content from */
  13219. sqlite3_stmt *pStmt = NULL; /* A statement */
  13220. int nCol; /* Number of columns in the table */
  13221. int nByte; /* Number of bytes in an SQL string */
  13222. int i, j; /* Loop counters */
  13223. int needCommit; /* True to COMMIT or ROLLBACK at end */
  13224. int nSep; /* Number of bytes in p->colSeparator[] */
  13225. char *zSql; /* An SQL statement */
  13226. ImportCtx sCtx; /* Reader context */
  13227. char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
  13228. int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
  13229. if( nArg!=3 ){
  13230. raw_printf(stderr, "Usage: .import FILE TABLE\n");
  13231. goto meta_command_exit;
  13232. }
  13233. zFile = azArg[1];
  13234. zTable = azArg[2];
  13235. seenInterrupt = 0;
  13236. memset(&sCtx, 0, sizeof(sCtx));
  13237. open_db(p, 0);
  13238. nSep = strlen30(p->colSeparator);
  13239. if( nSep==0 ){
  13240. raw_printf(stderr,
  13241. "Error: non-null column separator required for import\n");
  13242. return 1;
  13243. }
  13244. if( nSep>1 ){
  13245. raw_printf(stderr, "Error: multi-character column separators not allowed"
  13246. " for import\n");
  13247. return 1;
  13248. }
  13249. nSep = strlen30(p->rowSeparator);
  13250. if( nSep==0 ){
  13251. raw_printf(stderr, "Error: non-null row separator required for import\n");
  13252. return 1;
  13253. }
  13254. if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
  13255. /* When importing CSV (only), if the row separator is set to the
  13256. ** default output row separator, change it to the default input
  13257. ** row separator. This avoids having to maintain different input
  13258. ** and output row separators. */
  13259. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  13260. nSep = strlen30(p->rowSeparator);
  13261. }
  13262. if( nSep>1 ){
  13263. raw_printf(stderr, "Error: multi-character row separators not allowed"
  13264. " for import\n");
  13265. return 1;
  13266. }
  13267. sCtx.zFile = zFile;
  13268. sCtx.nLine = 1;
  13269. if( sCtx.zFile[0]=='|' ){
  13270. #ifdef SQLITE_OMIT_POPEN
  13271. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  13272. return 1;
  13273. #else
  13274. sCtx.in = popen(sCtx.zFile+1, "r");
  13275. sCtx.zFile = "<pipe>";
  13276. xCloser = pclose;
  13277. #endif
  13278. }else{
  13279. sCtx.in = fopen(sCtx.zFile, "rb");
  13280. xCloser = fclose;
  13281. }
  13282. if( p->mode==MODE_Ascii ){
  13283. xRead = ascii_read_one_field;
  13284. }else{
  13285. xRead = csv_read_one_field;
  13286. }
  13287. if( sCtx.in==0 ){
  13288. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  13289. return 1;
  13290. }
  13291. sCtx.cColSep = p->colSeparator[0];
  13292. sCtx.cRowSep = p->rowSeparator[0];
  13293. zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
  13294. if( zSql==0 ){
  13295. xCloser(sCtx.in);
  13296. shell_out_of_memory();
  13297. }
  13298. nByte = strlen30(zSql);
  13299. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  13300. import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
  13301. if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
  13302. char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
  13303. char cSep = '(';
  13304. while( xRead(&sCtx) ){
  13305. zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
  13306. cSep = ',';
  13307. if( sCtx.cTerm!=sCtx.cColSep ) break;
  13308. }
  13309. if( cSep=='(' ){
  13310. sqlite3_free(zCreate);
  13311. sqlite3_free(sCtx.z);
  13312. xCloser(sCtx.in);
  13313. utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
  13314. return 1;
  13315. }
  13316. zCreate = sqlite3_mprintf("%z\n)", zCreate);
  13317. rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
  13318. sqlite3_free(zCreate);
  13319. if( rc ){
  13320. utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
  13321. sqlite3_errmsg(p->db));
  13322. sqlite3_free(sCtx.z);
  13323. xCloser(sCtx.in);
  13324. return 1;
  13325. }
  13326. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  13327. }
  13328. sqlite3_free(zSql);
  13329. if( rc ){
  13330. if (pStmt) sqlite3_finalize(pStmt);
  13331. utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
  13332. xCloser(sCtx.in);
  13333. return 1;
  13334. }
  13335. nCol = sqlite3_column_count(pStmt);
  13336. sqlite3_finalize(pStmt);
  13337. pStmt = 0;
  13338. if( nCol==0 ) return 0; /* no columns, no error */
  13339. zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
  13340. if( zSql==0 ){
  13341. xCloser(sCtx.in);
  13342. shell_out_of_memory();
  13343. }
  13344. sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
  13345. j = strlen30(zSql);
  13346. for(i=1; i<nCol; i++){
  13347. zSql[j++] = ',';
  13348. zSql[j++] = '?';
  13349. }
  13350. zSql[j++] = ')';
  13351. zSql[j] = 0;
  13352. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  13353. sqlite3_free(zSql);
  13354. if( rc ){
  13355. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  13356. if (pStmt) sqlite3_finalize(pStmt);
  13357. xCloser(sCtx.in);
  13358. return 1;
  13359. }
  13360. needCommit = sqlite3_get_autocommit(p->db);
  13361. if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
  13362. do{
  13363. int startLine = sCtx.nLine;
  13364. for(i=0; i<nCol; i++){
  13365. char *z = xRead(&sCtx);
  13366. /*
  13367. ** Did we reach end-of-file before finding any columns?
  13368. ** If so, stop instead of NULL filling the remaining columns.
  13369. */
  13370. if( z==0 && i==0 ) break;
  13371. /*
  13372. ** Did we reach end-of-file OR end-of-line before finding any
  13373. ** columns in ASCII mode? If so, stop instead of NULL filling
  13374. ** the remaining columns.
  13375. */
  13376. if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
  13377. sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
  13378. if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
  13379. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  13380. "filling the rest with NULL\n",
  13381. sCtx.zFile, startLine, nCol, i+1);
  13382. i += 2;
  13383. while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
  13384. }
  13385. }
  13386. if( sCtx.cTerm==sCtx.cColSep ){
  13387. do{
  13388. xRead(&sCtx);
  13389. i++;
  13390. }while( sCtx.cTerm==sCtx.cColSep );
  13391. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  13392. "extras ignored\n",
  13393. sCtx.zFile, startLine, nCol, i);
  13394. }
  13395. if( i>=nCol ){
  13396. sqlite3_step(pStmt);
  13397. rc = sqlite3_reset(pStmt);
  13398. if( rc!=SQLITE_OK ){
  13399. utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
  13400. startLine, sqlite3_errmsg(p->db));
  13401. }
  13402. }
  13403. }while( sCtx.cTerm!=EOF );
  13404. xCloser(sCtx.in);
  13405. sqlite3_free(sCtx.z);
  13406. sqlite3_finalize(pStmt);
  13407. if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
  13408. }else
  13409. #ifndef SQLITE_UNTESTABLE
  13410. if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
  13411. char *zSql;
  13412. char *zCollist = 0;
  13413. sqlite3_stmt *pStmt;
  13414. int tnum = 0;
  13415. int i;
  13416. if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
  13417. utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
  13418. " .imposter off\n");
  13419. rc = 1;
  13420. goto meta_command_exit;
  13421. }
  13422. open_db(p, 0);
  13423. if( nArg==2 ){
  13424. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
  13425. goto meta_command_exit;
  13426. }
  13427. zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
  13428. " WHERE name='%q' AND type='index'", azArg[1]);
  13429. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  13430. sqlite3_free(zSql);
  13431. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  13432. tnum = sqlite3_column_int(pStmt, 0);
  13433. }
  13434. sqlite3_finalize(pStmt);
  13435. if( tnum==0 ){
  13436. utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
  13437. rc = 1;
  13438. goto meta_command_exit;
  13439. }
  13440. zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
  13441. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  13442. sqlite3_free(zSql);
  13443. i = 0;
  13444. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  13445. char zLabel[20];
  13446. const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
  13447. i++;
  13448. if( zCol==0 ){
  13449. if( sqlite3_column_int(pStmt,1)==-1 ){
  13450. zCol = "_ROWID_";
  13451. }else{
  13452. sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
  13453. zCol = zLabel;
  13454. }
  13455. }
  13456. if( zCollist==0 ){
  13457. zCollist = sqlite3_mprintf("\"%w\"", zCol);
  13458. }else{
  13459. zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
  13460. }
  13461. }
  13462. sqlite3_finalize(pStmt);
  13463. zSql = sqlite3_mprintf(
  13464. "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
  13465. azArg[2], zCollist, zCollist);
  13466. sqlite3_free(zCollist);
  13467. rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
  13468. if( rc==SQLITE_OK ){
  13469. rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
  13470. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
  13471. if( rc ){
  13472. utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
  13473. }else{
  13474. utf8_printf(stdout, "%s;\n", zSql);
  13475. raw_printf(stdout,
  13476. "WARNING: writing to an imposter table will corrupt the index!\n"
  13477. );
  13478. }
  13479. }else{
  13480. raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
  13481. rc = 1;
  13482. }
  13483. sqlite3_free(zSql);
  13484. }else
  13485. #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
  13486. #ifdef SQLITE_ENABLE_IOTRACE
  13487. if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
  13488. SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
  13489. if( iotrace && iotrace!=stdout ) fclose(iotrace);
  13490. iotrace = 0;
  13491. if( nArg<2 ){
  13492. sqlite3IoTrace = 0;
  13493. }else if( strcmp(azArg[1], "-")==0 ){
  13494. sqlite3IoTrace = iotracePrintf;
  13495. iotrace = stdout;
  13496. }else{
  13497. iotrace = fopen(azArg[1], "w");
  13498. if( iotrace==0 ){
  13499. utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  13500. sqlite3IoTrace = 0;
  13501. rc = 1;
  13502. }else{
  13503. sqlite3IoTrace = iotracePrintf;
  13504. }
  13505. }
  13506. }else
  13507. #endif
  13508. if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
  13509. static const struct {
  13510. const char *zLimitName; /* Name of a limit */
  13511. int limitCode; /* Integer code for that limit */
  13512. } aLimit[] = {
  13513. { "length", SQLITE_LIMIT_LENGTH },
  13514. { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
  13515. { "column", SQLITE_LIMIT_COLUMN },
  13516. { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
  13517. { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
  13518. { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
  13519. { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
  13520. { "attached", SQLITE_LIMIT_ATTACHED },
  13521. { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
  13522. { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
  13523. { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
  13524. { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
  13525. };
  13526. int i, n2;
  13527. open_db(p, 0);
  13528. if( nArg==1 ){
  13529. for(i=0; i<ArraySize(aLimit); i++){
  13530. printf("%20s %d\n", aLimit[i].zLimitName,
  13531. sqlite3_limit(p->db, aLimit[i].limitCode, -1));
  13532. }
  13533. }else if( nArg>3 ){
  13534. raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
  13535. rc = 1;
  13536. goto meta_command_exit;
  13537. }else{
  13538. int iLimit = -1;
  13539. n2 = strlen30(azArg[1]);
  13540. for(i=0; i<ArraySize(aLimit); i++){
  13541. if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
  13542. if( iLimit<0 ){
  13543. iLimit = i;
  13544. }else{
  13545. utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
  13546. rc = 1;
  13547. goto meta_command_exit;
  13548. }
  13549. }
  13550. }
  13551. if( iLimit<0 ){
  13552. utf8_printf(stderr, "unknown limit: \"%s\"\n"
  13553. "enter \".limits\" with no arguments for a list.\n",
  13554. azArg[1]);
  13555. rc = 1;
  13556. goto meta_command_exit;
  13557. }
  13558. if( nArg==3 ){
  13559. sqlite3_limit(p->db, aLimit[iLimit].limitCode,
  13560. (int)integerValue(azArg[2]));
  13561. }
  13562. printf("%20s %d\n", aLimit[iLimit].zLimitName,
  13563. sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
  13564. }
  13565. }else
  13566. if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
  13567. open_db(p, 0);
  13568. lintDotCommand(p, azArg, nArg);
  13569. }else
  13570. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  13571. if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
  13572. const char *zFile, *zProc;
  13573. char *zErrMsg = 0;
  13574. if( nArg<2 ){
  13575. raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
  13576. rc = 1;
  13577. goto meta_command_exit;
  13578. }
  13579. zFile = azArg[1];
  13580. zProc = nArg>=3 ? azArg[2] : 0;
  13581. open_db(p, 0);
  13582. rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  13583. if( rc!=SQLITE_OK ){
  13584. utf8_printf(stderr, "Error: %s\n", zErrMsg);
  13585. sqlite3_free(zErrMsg);
  13586. rc = 1;
  13587. }
  13588. }else
  13589. #endif
  13590. if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
  13591. if( nArg!=2 ){
  13592. raw_printf(stderr, "Usage: .log FILENAME\n");
  13593. rc = 1;
  13594. }else{
  13595. const char *zFile = azArg[1];
  13596. output_file_close(p->pLog);
  13597. p->pLog = output_file_open(zFile, 0);
  13598. }
  13599. }else
  13600. if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
  13601. const char *zMode = nArg>=2 ? azArg[1] : "";
  13602. int n2 = strlen30(zMode);
  13603. int c2 = zMode[0];
  13604. if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
  13605. p->mode = MODE_Line;
  13606. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  13607. }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
  13608. p->mode = MODE_Column;
  13609. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  13610. }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
  13611. p->mode = MODE_List;
  13612. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
  13613. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  13614. }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
  13615. p->mode = MODE_Html;
  13616. }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
  13617. p->mode = MODE_Tcl;
  13618. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
  13619. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  13620. }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
  13621. p->mode = MODE_Csv;
  13622. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  13623. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  13624. }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
  13625. p->mode = MODE_List;
  13626. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
  13627. }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
  13628. p->mode = MODE_Insert;
  13629. set_table_name(p, nArg>=3 ? azArg[2] : "table");
  13630. }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
  13631. p->mode = MODE_Quote;
  13632. }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
  13633. p->mode = MODE_Ascii;
  13634. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
  13635. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
  13636. }else if( nArg==1 ){
  13637. raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
  13638. }else{
  13639. raw_printf(stderr, "Error: mode should be one of: "
  13640. "ascii column csv html insert line list quote tabs tcl\n");
  13641. rc = 1;
  13642. }
  13643. p->cMode = p->mode;
  13644. }else
  13645. if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
  13646. if( nArg==2 ){
  13647. sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
  13648. "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
  13649. }else{
  13650. raw_printf(stderr, "Usage: .nullvalue STRING\n");
  13651. rc = 1;
  13652. }
  13653. }else
  13654. if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
  13655. char *zNewFilename; /* Name of the database file to open */
  13656. int iName = 1; /* Index in azArg[] of the filename */
  13657. int newFlag = 0; /* True to delete file before opening */
  13658. /* Close the existing database */
  13659. session_close_all(p);
  13660. close_db(p->db);
  13661. p->db = 0;
  13662. p->zDbFilename = 0;
  13663. sqlite3_free(p->zFreeOnClose);
  13664. p->zFreeOnClose = 0;
  13665. p->openMode = SHELL_OPEN_UNSPEC;
  13666. p->szMax = 0;
  13667. /* Check for command-line arguments */
  13668. for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
  13669. const char *z = azArg[iName];
  13670. if( optionMatch(z,"new") ){
  13671. newFlag = 1;
  13672. #ifdef SQLITE_HAVE_ZLIB
  13673. }else if( optionMatch(z, "zip") ){
  13674. p->openMode = SHELL_OPEN_ZIPFILE;
  13675. #endif
  13676. }else if( optionMatch(z, "append") ){
  13677. p->openMode = SHELL_OPEN_APPENDVFS;
  13678. }else if( optionMatch(z, "readonly") ){
  13679. p->openMode = SHELL_OPEN_READONLY;
  13680. #ifdef SQLITE_ENABLE_DESERIALIZE
  13681. }else if( optionMatch(z, "deserialize") ){
  13682. p->openMode = SHELL_OPEN_DESERIALIZE;
  13683. }else if( optionMatch(z, "hexdb") ){
  13684. p->openMode = SHELL_OPEN_HEXDB;
  13685. }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
  13686. p->szMax = integerValue(azArg[++iName]);
  13687. #endif /* SQLITE_ENABLE_DESERIALIZE */
  13688. }else if( z[0]=='-' ){
  13689. utf8_printf(stderr, "unknown option: %s\n", z);
  13690. rc = 1;
  13691. goto meta_command_exit;
  13692. }
  13693. }
  13694. /* If a filename is specified, try to open it first */
  13695. zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
  13696. if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
  13697. if( newFlag ) shellDeleteFile(zNewFilename);
  13698. p->zDbFilename = zNewFilename;
  13699. open_db(p, OPEN_DB_KEEPALIVE);
  13700. if( p->db==0 ){
  13701. utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
  13702. sqlite3_free(zNewFilename);
  13703. }else{
  13704. p->zFreeOnClose = zNewFilename;
  13705. }
  13706. }
  13707. if( p->db==0 ){
  13708. /* As a fall-back open a TEMP database */
  13709. p->zDbFilename = 0;
  13710. open_db(p, 0);
  13711. }
  13712. }else
  13713. if( (c=='o'
  13714. && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
  13715. || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
  13716. ){
  13717. const char *zFile = nArg>=2 ? azArg[1] : "stdout";
  13718. int bTxtMode = 0;
  13719. if( azArg[0][0]=='e' ){
  13720. /* Transform the ".excel" command into ".once -x" */
  13721. nArg = 2;
  13722. azArg[0] = "once";
  13723. zFile = azArg[1] = "-x";
  13724. n = 4;
  13725. }
  13726. if( nArg>2 ){
  13727. utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
  13728. rc = 1;
  13729. goto meta_command_exit;
  13730. }
  13731. if( n>1 && strncmp(azArg[0], "once", n)==0 ){
  13732. if( nArg<2 ){
  13733. raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
  13734. rc = 1;
  13735. goto meta_command_exit;
  13736. }
  13737. p->outCount = 2;
  13738. }else{
  13739. p->outCount = 0;
  13740. }
  13741. output_reset(p);
  13742. if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
  13743. #ifndef SQLITE_NOHAVE_SYSTEM
  13744. if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
  13745. p->doXdgOpen = 1;
  13746. outputModePush(p);
  13747. if( zFile[1]=='x' ){
  13748. newTempFile(p, "csv");
  13749. p->mode = MODE_Csv;
  13750. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  13751. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  13752. }else{
  13753. newTempFile(p, "txt");
  13754. bTxtMode = 1;
  13755. }
  13756. zFile = p->zTempFile;
  13757. }
  13758. #endif /* SQLITE_NOHAVE_SYSTEM */
  13759. if( zFile[0]=='|' ){
  13760. #ifdef SQLITE_OMIT_POPEN
  13761. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  13762. rc = 1;
  13763. p->out = stdout;
  13764. #else
  13765. p->out = popen(zFile + 1, "w");
  13766. if( p->out==0 ){
  13767. utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
  13768. p->out = stdout;
  13769. rc = 1;
  13770. }else{
  13771. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  13772. }
  13773. #endif
  13774. }else{
  13775. p->out = output_file_open(zFile, bTxtMode);
  13776. if( p->out==0 ){
  13777. if( strcmp(zFile,"off")!=0 ){
  13778. utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
  13779. }
  13780. p->out = stdout;
  13781. rc = 1;
  13782. } else {
  13783. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  13784. }
  13785. }
  13786. }else
  13787. if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
  13788. open_db(p,0);
  13789. if( nArg<=1 ) goto parameter_syntax_error;
  13790. /* .parameter clear
  13791. ** Clear all bind parameters by dropping the TEMP table that holds them.
  13792. */
  13793. if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
  13794. int wrSchema = 0;
  13795. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
  13796. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
  13797. sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
  13798. 0, 0, 0);
  13799. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
  13800. }else
  13801. /* .parameter list
  13802. ** List all bind parameters.
  13803. */
  13804. if( nArg==2 && strcmp(azArg[1],"list")==0 ){
  13805. sqlite3_stmt *pStmt = 0;
  13806. int rx;
  13807. int len = 0;
  13808. rx = sqlite3_prepare_v2(p->db,
  13809. "SELECT max(length(key)) "
  13810. "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
  13811. if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
  13812. len = sqlite3_column_int(pStmt, 0);
  13813. if( len>40 ) len = 40;
  13814. }
  13815. sqlite3_finalize(pStmt);
  13816. pStmt = 0;
  13817. if( len ){
  13818. rx = sqlite3_prepare_v2(p->db,
  13819. "SELECT key, quote(value) "
  13820. "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
  13821. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  13822. utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
  13823. sqlite3_column_text(pStmt,1));
  13824. }
  13825. sqlite3_finalize(pStmt);
  13826. }
  13827. }else
  13828. /* .parameter init
  13829. ** Make sure the TEMP table used to hold bind parameters exists.
  13830. ** Create it if necessary.
  13831. */
  13832. if( nArg==2 && strcmp(azArg[1],"init")==0 ){
  13833. bind_table_init(p);
  13834. }else
  13835. /* .parameter set NAME VALUE
  13836. ** Set or reset a bind parameter. NAME should be the full parameter
  13837. ** name exactly as it appears in the query. (ex: $abc, @def). The
  13838. ** VALUE can be in either SQL literal notation, or if not it will be
  13839. ** understood to be a text string.
  13840. */
  13841. if( nArg==4 && strcmp(azArg[1],"set")==0 ){
  13842. int rx;
  13843. char *zSql;
  13844. sqlite3_stmt *pStmt;
  13845. const char *zKey = azArg[2];
  13846. const char *zValue = azArg[3];
  13847. bind_table_init(p);
  13848. zSql = sqlite3_mprintf(
  13849. "REPLACE INTO temp.sqlite_parameters(key,value)"
  13850. "VALUES(%Q,%s);", zKey, zValue);
  13851. if( zSql==0 ) shell_out_of_memory();
  13852. pStmt = 0;
  13853. rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  13854. sqlite3_free(zSql);
  13855. if( rx!=SQLITE_OK ){
  13856. sqlite3_finalize(pStmt);
  13857. pStmt = 0;
  13858. zSql = sqlite3_mprintf(
  13859. "REPLACE INTO temp.sqlite_parameters(key,value)"
  13860. "VALUES(%Q,%Q);", zKey, zValue);
  13861. if( zSql==0 ) shell_out_of_memory();
  13862. rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  13863. sqlite3_free(zSql);
  13864. if( rx!=SQLITE_OK ){
  13865. utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
  13866. sqlite3_finalize(pStmt);
  13867. pStmt = 0;
  13868. rc = 1;
  13869. }
  13870. }
  13871. sqlite3_step(pStmt);
  13872. sqlite3_finalize(pStmt);
  13873. }else
  13874. /* .parameter unset NAME
  13875. ** Remove the NAME binding from the parameter binding table, if it
  13876. ** exists.
  13877. */
  13878. if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
  13879. char *zSql = sqlite3_mprintf(
  13880. "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
  13881. if( zSql==0 ) shell_out_of_memory();
  13882. sqlite3_exec(p->db, zSql, 0, 0, 0);
  13883. sqlite3_free(zSql);
  13884. }else
  13885. /* If no command name matches, show a syntax error */
  13886. parameter_syntax_error:
  13887. showHelp(p->out, "parameter");
  13888. }else
  13889. if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
  13890. int i;
  13891. for(i=1; i<nArg; i++){
  13892. if( i>1 ) raw_printf(p->out, " ");
  13893. utf8_printf(p->out, "%s", azArg[i]);
  13894. }
  13895. raw_printf(p->out, "\n");
  13896. }else
  13897. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  13898. if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
  13899. int i;
  13900. int nn = 0;
  13901. p->flgProgress = 0;
  13902. p->mxProgress = 0;
  13903. p->nProgress = 0;
  13904. for(i=1; i<nArg; i++){
  13905. const char *z = azArg[i];
  13906. if( z[0]=='-' ){
  13907. z++;
  13908. if( z[0]=='-' ) z++;
  13909. if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
  13910. p->flgProgress |= SHELL_PROGRESS_QUIET;
  13911. continue;
  13912. }
  13913. if( strcmp(z,"reset")==0 ){
  13914. p->flgProgress |= SHELL_PROGRESS_RESET;
  13915. continue;
  13916. }
  13917. if( strcmp(z,"once")==0 ){
  13918. p->flgProgress |= SHELL_PROGRESS_ONCE;
  13919. continue;
  13920. }
  13921. if( strcmp(z,"limit")==0 ){
  13922. if( i+1>=nArg ){
  13923. utf8_printf(stderr, "Error: missing argument on --limit\n");
  13924. rc = 1;
  13925. goto meta_command_exit;
  13926. }else{
  13927. p->mxProgress = (int)integerValue(azArg[++i]);
  13928. }
  13929. continue;
  13930. }
  13931. utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
  13932. rc = 1;
  13933. goto meta_command_exit;
  13934. }else{
  13935. nn = (int)integerValue(z);
  13936. }
  13937. }
  13938. open_db(p, 0);
  13939. sqlite3_progress_handler(p->db, nn, progress_handler, p);
  13940. }else
  13941. #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
  13942. if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
  13943. if( nArg >= 2) {
  13944. strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  13945. }
  13946. if( nArg >= 3) {
  13947. strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  13948. }
  13949. }else
  13950. if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
  13951. rc = 2;
  13952. }else
  13953. if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
  13954. FILE *inSaved = p->in;
  13955. int savedLineno = p->lineno;
  13956. if( nArg!=2 ){
  13957. raw_printf(stderr, "Usage: .read FILE\n");
  13958. rc = 1;
  13959. goto meta_command_exit;
  13960. }
  13961. p->in = fopen(azArg[1], "rb");
  13962. if( p->in==0 ){
  13963. utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
  13964. rc = 1;
  13965. }else{
  13966. rc = process_input(p);
  13967. fclose(p->in);
  13968. }
  13969. p->in = inSaved;
  13970. p->lineno = savedLineno;
  13971. }else
  13972. if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
  13973. const char *zSrcFile;
  13974. const char *zDb;
  13975. sqlite3 *pSrc;
  13976. sqlite3_backup *pBackup;
  13977. int nTimeout = 0;
  13978. if( nArg==2 ){
  13979. zSrcFile = azArg[1];
  13980. zDb = "main";
  13981. }else if( nArg==3 ){
  13982. zSrcFile = azArg[2];
  13983. zDb = azArg[1];
  13984. }else{
  13985. raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
  13986. rc = 1;
  13987. goto meta_command_exit;
  13988. }
  13989. rc = sqlite3_open(zSrcFile, &pSrc);
  13990. if( rc!=SQLITE_OK ){
  13991. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  13992. close_db(pSrc);
  13993. return 1;
  13994. }
  13995. open_db(p, 0);
  13996. pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  13997. if( pBackup==0 ){
  13998. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  13999. close_db(pSrc);
  14000. return 1;
  14001. }
  14002. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  14003. || rc==SQLITE_BUSY ){
  14004. if( rc==SQLITE_BUSY ){
  14005. if( nTimeout++ >= 3 ) break;
  14006. sqlite3_sleep(100);
  14007. }
  14008. }
  14009. sqlite3_backup_finish(pBackup);
  14010. if( rc==SQLITE_DONE ){
  14011. rc = 0;
  14012. }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  14013. raw_printf(stderr, "Error: source database is busy\n");
  14014. rc = 1;
  14015. }else{
  14016. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  14017. rc = 1;
  14018. }
  14019. close_db(pSrc);
  14020. }else
  14021. if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
  14022. if( nArg==2 ){
  14023. p->scanstatsOn = (u8)booleanValue(azArg[1]);
  14024. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  14025. raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
  14026. #endif
  14027. }else{
  14028. raw_printf(stderr, "Usage: .scanstats on|off\n");
  14029. rc = 1;
  14030. }
  14031. }else
  14032. if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
  14033. ShellText sSelect;
  14034. ShellState data;
  14035. char *zErrMsg = 0;
  14036. const char *zDiv = "(";
  14037. const char *zName = 0;
  14038. int iSchema = 0;
  14039. int bDebug = 0;
  14040. int ii;
  14041. open_db(p, 0);
  14042. memcpy(&data, p, sizeof(data));
  14043. data.showHeader = 0;
  14044. data.cMode = data.mode = MODE_Semi;
  14045. initText(&sSelect);
  14046. for(ii=1; ii<nArg; ii++){
  14047. if( optionMatch(azArg[ii],"indent") ){
  14048. data.cMode = data.mode = MODE_Pretty;
  14049. }else if( optionMatch(azArg[ii],"debug") ){
  14050. bDebug = 1;
  14051. }else if( zName==0 ){
  14052. zName = azArg[ii];
  14053. }else{
  14054. raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
  14055. rc = 1;
  14056. goto meta_command_exit;
  14057. }
  14058. }
  14059. if( zName!=0 ){
  14060. int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
  14061. if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
  14062. char *new_argv[2], *new_colv[2];
  14063. new_argv[0] = sqlite3_mprintf(
  14064. "CREATE TABLE %s (\n"
  14065. " type text,\n"
  14066. " name text,\n"
  14067. " tbl_name text,\n"
  14068. " rootpage integer,\n"
  14069. " sql text\n"
  14070. ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
  14071. new_argv[1] = 0;
  14072. new_colv[0] = "sql";
  14073. new_colv[1] = 0;
  14074. callback(&data, 1, new_argv, new_colv);
  14075. sqlite3_free(new_argv[0]);
  14076. }
  14077. }
  14078. if( zDiv ){
  14079. sqlite3_stmt *pStmt = 0;
  14080. rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
  14081. -1, &pStmt, 0);
  14082. if( rc ){
  14083. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  14084. sqlite3_finalize(pStmt);
  14085. rc = 1;
  14086. goto meta_command_exit;
  14087. }
  14088. appendText(&sSelect, "SELECT sql FROM", 0);
  14089. iSchema = 0;
  14090. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  14091. const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
  14092. char zScNum[30];
  14093. sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
  14094. appendText(&sSelect, zDiv, 0);
  14095. zDiv = " UNION ALL ";
  14096. appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
  14097. if( sqlite3_stricmp(zDb, "main")!=0 ){
  14098. appendText(&sSelect, zDb, '"');
  14099. }else{
  14100. appendText(&sSelect, "NULL", 0);
  14101. }
  14102. appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
  14103. appendText(&sSelect, zScNum, 0);
  14104. appendText(&sSelect, " AS snum, ", 0);
  14105. appendText(&sSelect, zDb, '\'');
  14106. appendText(&sSelect, " AS sname FROM ", 0);
  14107. appendText(&sSelect, zDb, '"');
  14108. appendText(&sSelect, ".sqlite_master", 0);
  14109. }
  14110. sqlite3_finalize(pStmt);
  14111. #ifdef SQLITE_INTROSPECTION_PRAGMAS
  14112. if( zName ){
  14113. appendText(&sSelect,
  14114. " UNION ALL SELECT shell_module_schema(name),"
  14115. " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
  14116. }
  14117. #endif
  14118. appendText(&sSelect, ") WHERE ", 0);
  14119. if( zName ){
  14120. char *zQarg = sqlite3_mprintf("%Q", zName);
  14121. int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
  14122. strchr(zName, '[') != 0;
  14123. if( strchr(zName, '.') ){
  14124. appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
  14125. }else{
  14126. appendText(&sSelect, "lower(tbl_name)", 0);
  14127. }
  14128. appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
  14129. appendText(&sSelect, zQarg, 0);
  14130. if( !bGlob ){
  14131. appendText(&sSelect, " ESCAPE '\\' ", 0);
  14132. }
  14133. appendText(&sSelect, " AND ", 0);
  14134. sqlite3_free(zQarg);
  14135. }
  14136. appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
  14137. " ORDER BY snum, rowid", 0);
  14138. if( bDebug ){
  14139. utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
  14140. }else{
  14141. rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
  14142. }
  14143. freeText(&sSelect);
  14144. }
  14145. if( zErrMsg ){
  14146. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  14147. sqlite3_free(zErrMsg);
  14148. rc = 1;
  14149. }else if( rc != SQLITE_OK ){
  14150. raw_printf(stderr,"Error: querying schema information\n");
  14151. rc = 1;
  14152. }else{
  14153. rc = 0;
  14154. }
  14155. }else
  14156. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  14157. if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
  14158. sqlite3SelectTrace = (int)integerValue(azArg[1]);
  14159. }else
  14160. #endif
  14161. #if defined(SQLITE_ENABLE_SESSION)
  14162. if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
  14163. OpenSession *pSession = &p->aSession[0];
  14164. char **azCmd = &azArg[1];
  14165. int iSes = 0;
  14166. int nCmd = nArg - 1;
  14167. int i;
  14168. if( nArg<=1 ) goto session_syntax_error;
  14169. open_db(p, 0);
  14170. if( nArg>=3 ){
  14171. for(iSes=0; iSes<p->nSession; iSes++){
  14172. if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
  14173. }
  14174. if( iSes<p->nSession ){
  14175. pSession = &p->aSession[iSes];
  14176. azCmd++;
  14177. nCmd--;
  14178. }else{
  14179. pSession = &p->aSession[0];
  14180. iSes = 0;
  14181. }
  14182. }
  14183. /* .session attach TABLE
  14184. ** Invoke the sqlite3session_attach() interface to attach a particular
  14185. ** table so that it is never filtered.
  14186. */
  14187. if( strcmp(azCmd[0],"attach")==0 ){
  14188. if( nCmd!=2 ) goto session_syntax_error;
  14189. if( pSession->p==0 ){
  14190. session_not_open:
  14191. raw_printf(stderr, "ERROR: No sessions are open\n");
  14192. }else{
  14193. rc = sqlite3session_attach(pSession->p, azCmd[1]);
  14194. if( rc ){
  14195. raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
  14196. rc = 0;
  14197. }
  14198. }
  14199. }else
  14200. /* .session changeset FILE
  14201. ** .session patchset FILE
  14202. ** Write a changeset or patchset into a file. The file is overwritten.
  14203. */
  14204. if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
  14205. FILE *out = 0;
  14206. if( nCmd!=2 ) goto session_syntax_error;
  14207. if( pSession->p==0 ) goto session_not_open;
  14208. out = fopen(azCmd[1], "wb");
  14209. if( out==0 ){
  14210. utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
  14211. }else{
  14212. int szChng;
  14213. void *pChng;
  14214. if( azCmd[0][0]=='c' ){
  14215. rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
  14216. }else{
  14217. rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
  14218. }
  14219. if( rc ){
  14220. printf("Error: error code %d\n", rc);
  14221. rc = 0;
  14222. }
  14223. if( pChng
  14224. && fwrite(pChng, szChng, 1, out)!=1 ){
  14225. raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
  14226. szChng);
  14227. }
  14228. sqlite3_free(pChng);
  14229. fclose(out);
  14230. }
  14231. }else
  14232. /* .session close
  14233. ** Close the identified session
  14234. */
  14235. if( strcmp(azCmd[0], "close")==0 ){
  14236. if( nCmd!=1 ) goto session_syntax_error;
  14237. if( p->nSession ){
  14238. session_close(pSession);
  14239. p->aSession[iSes] = p->aSession[--p->nSession];
  14240. }
  14241. }else
  14242. /* .session enable ?BOOLEAN?
  14243. ** Query or set the enable flag
  14244. */
  14245. if( strcmp(azCmd[0], "enable")==0 ){
  14246. int ii;
  14247. if( nCmd>2 ) goto session_syntax_error;
  14248. ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  14249. if( p->nSession ){
  14250. ii = sqlite3session_enable(pSession->p, ii);
  14251. utf8_printf(p->out, "session %s enable flag = %d\n",
  14252. pSession->zName, ii);
  14253. }
  14254. }else
  14255. /* .session filter GLOB ....
  14256. ** Set a list of GLOB patterns of table names to be excluded.
  14257. */
  14258. if( strcmp(azCmd[0], "filter")==0 ){
  14259. int ii, nByte;
  14260. if( nCmd<2 ) goto session_syntax_error;
  14261. if( p->nSession ){
  14262. for(ii=0; ii<pSession->nFilter; ii++){
  14263. sqlite3_free(pSession->azFilter[ii]);
  14264. }
  14265. sqlite3_free(pSession->azFilter);
  14266. nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
  14267. pSession->azFilter = sqlite3_malloc( nByte );
  14268. if( pSession->azFilter==0 ){
  14269. raw_printf(stderr, "Error: out or memory\n");
  14270. exit(1);
  14271. }
  14272. for(ii=1; ii<nCmd; ii++){
  14273. pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
  14274. }
  14275. pSession->nFilter = ii-1;
  14276. }
  14277. }else
  14278. /* .session indirect ?BOOLEAN?
  14279. ** Query or set the indirect flag
  14280. */
  14281. if( strcmp(azCmd[0], "indirect")==0 ){
  14282. int ii;
  14283. if( nCmd>2 ) goto session_syntax_error;
  14284. ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  14285. if( p->nSession ){
  14286. ii = sqlite3session_indirect(pSession->p, ii);
  14287. utf8_printf(p->out, "session %s indirect flag = %d\n",
  14288. pSession->zName, ii);
  14289. }
  14290. }else
  14291. /* .session isempty
  14292. ** Determine if the session is empty
  14293. */
  14294. if( strcmp(azCmd[0], "isempty")==0 ){
  14295. int ii;
  14296. if( nCmd!=1 ) goto session_syntax_error;
  14297. if( p->nSession ){
  14298. ii = sqlite3session_isempty(pSession->p);
  14299. utf8_printf(p->out, "session %s isempty flag = %d\n",
  14300. pSession->zName, ii);
  14301. }
  14302. }else
  14303. /* .session list
  14304. ** List all currently open sessions
  14305. */
  14306. if( strcmp(azCmd[0],"list")==0 ){
  14307. for(i=0; i<p->nSession; i++){
  14308. utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
  14309. }
  14310. }else
  14311. /* .session open DB NAME
  14312. ** Open a new session called NAME on the attached database DB.
  14313. ** DB is normally "main".
  14314. */
  14315. if( strcmp(azCmd[0],"open")==0 ){
  14316. char *zName;
  14317. if( nCmd!=3 ) goto session_syntax_error;
  14318. zName = azCmd[2];
  14319. if( zName[0]==0 ) goto session_syntax_error;
  14320. for(i=0; i<p->nSession; i++){
  14321. if( strcmp(p->aSession[i].zName,zName)==0 ){
  14322. utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
  14323. goto meta_command_exit;
  14324. }
  14325. }
  14326. if( p->nSession>=ArraySize(p->aSession) ){
  14327. raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
  14328. goto meta_command_exit;
  14329. }
  14330. pSession = &p->aSession[p->nSession];
  14331. rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
  14332. if( rc ){
  14333. raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
  14334. rc = 0;
  14335. goto meta_command_exit;
  14336. }
  14337. pSession->nFilter = 0;
  14338. sqlite3session_table_filter(pSession->p, session_filter, pSession);
  14339. p->nSession++;
  14340. pSession->zName = sqlite3_mprintf("%s", zName);
  14341. }else
  14342. /* If no command name matches, show a syntax error */
  14343. session_syntax_error:
  14344. showHelp(p->out, "session");
  14345. }else
  14346. #endif
  14347. #ifdef SQLITE_DEBUG
  14348. /* Undocumented commands for internal testing. Subject to change
  14349. ** without notice. */
  14350. if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
  14351. if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
  14352. int i, v;
  14353. for(i=1; i<nArg; i++){
  14354. v = booleanValue(azArg[i]);
  14355. utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
  14356. }
  14357. }
  14358. if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
  14359. int i; sqlite3_int64 v;
  14360. for(i=1; i<nArg; i++){
  14361. char zBuf[200];
  14362. v = integerValue(azArg[i]);
  14363. sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
  14364. utf8_printf(p->out, "%s", zBuf);
  14365. }
  14366. }
  14367. }else
  14368. #endif
  14369. if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
  14370. int bIsInit = 0; /* True to initialize the SELFTEST table */
  14371. int bVerbose = 0; /* Verbose output */
  14372. int bSelftestExists; /* True if SELFTEST already exists */
  14373. int i, k; /* Loop counters */
  14374. int nTest = 0; /* Number of tests runs */
  14375. int nErr = 0; /* Number of errors seen */
  14376. ShellText str; /* Answer for a query */
  14377. sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
  14378. open_db(p,0);
  14379. for(i=1; i<nArg; i++){
  14380. const char *z = azArg[i];
  14381. if( z[0]=='-' && z[1]=='-' ) z++;
  14382. if( strcmp(z,"-init")==0 ){
  14383. bIsInit = 1;
  14384. }else
  14385. if( strcmp(z,"-v")==0 ){
  14386. bVerbose++;
  14387. }else
  14388. {
  14389. utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
  14390. azArg[i], azArg[0]);
  14391. raw_printf(stderr, "Should be one of: --init -v\n");
  14392. rc = 1;
  14393. goto meta_command_exit;
  14394. }
  14395. }
  14396. if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
  14397. != SQLITE_OK ){
  14398. bSelftestExists = 0;
  14399. }else{
  14400. bSelftestExists = 1;
  14401. }
  14402. if( bIsInit ){
  14403. createSelftestTable(p);
  14404. bSelftestExists = 1;
  14405. }
  14406. initText(&str);
  14407. appendText(&str, "x", 0);
  14408. for(k=bSelftestExists; k>=0; k--){
  14409. if( k==1 ){
  14410. rc = sqlite3_prepare_v2(p->db,
  14411. "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
  14412. -1, &pStmt, 0);
  14413. }else{
  14414. rc = sqlite3_prepare_v2(p->db,
  14415. "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
  14416. " (1,'run','PRAGMA integrity_check','ok')",
  14417. -1, &pStmt, 0);
  14418. }
  14419. if( rc ){
  14420. raw_printf(stderr, "Error querying the selftest table\n");
  14421. rc = 1;
  14422. sqlite3_finalize(pStmt);
  14423. goto meta_command_exit;
  14424. }
  14425. for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
  14426. int tno = sqlite3_column_int(pStmt, 0);
  14427. const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
  14428. const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
  14429. const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
  14430. k = 0;
  14431. if( bVerbose>0 ){
  14432. char *zQuote = sqlite3_mprintf("%q", zSql);
  14433. printf("%d: %s %s\n", tno, zOp, zSql);
  14434. sqlite3_free(zQuote);
  14435. }
  14436. if( strcmp(zOp,"memo")==0 ){
  14437. utf8_printf(p->out, "%s\n", zSql);
  14438. }else
  14439. if( strcmp(zOp,"run")==0 ){
  14440. char *zErrMsg = 0;
  14441. str.n = 0;
  14442. str.z[0] = 0;
  14443. rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
  14444. nTest++;
  14445. if( bVerbose ){
  14446. utf8_printf(p->out, "Result: %s\n", str.z);
  14447. }
  14448. if( rc || zErrMsg ){
  14449. nErr++;
  14450. rc = 1;
  14451. utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
  14452. sqlite3_free(zErrMsg);
  14453. }else if( strcmp(zAns,str.z)!=0 ){
  14454. nErr++;
  14455. rc = 1;
  14456. utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
  14457. utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
  14458. }
  14459. }else
  14460. {
  14461. utf8_printf(stderr,
  14462. "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
  14463. rc = 1;
  14464. break;
  14465. }
  14466. } /* End loop over rows of content from SELFTEST */
  14467. sqlite3_finalize(pStmt);
  14468. } /* End loop over k */
  14469. freeText(&str);
  14470. utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
  14471. }else
  14472. if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
  14473. if( nArg<2 || nArg>3 ){
  14474. raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
  14475. rc = 1;
  14476. }
  14477. if( nArg>=2 ){
  14478. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
  14479. "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
  14480. }
  14481. if( nArg>=3 ){
  14482. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
  14483. "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
  14484. }
  14485. }else
  14486. if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
  14487. const char *zLike = 0; /* Which table to checksum. 0 means everything */
  14488. int i; /* Loop counter */
  14489. int bSchema = 0; /* Also hash the schema */
  14490. int bSeparate = 0; /* Hash each table separately */
  14491. int iSize = 224; /* Hash algorithm to use */
  14492. int bDebug = 0; /* Only show the query that would have run */
  14493. sqlite3_stmt *pStmt; /* For querying tables names */
  14494. char *zSql; /* SQL to be run */
  14495. char *zSep; /* Separator */
  14496. ShellText sSql; /* Complete SQL for the query to run the hash */
  14497. ShellText sQuery; /* Set of queries used to read all content */
  14498. open_db(p, 0);
  14499. for(i=1; i<nArg; i++){
  14500. const char *z = azArg[i];
  14501. if( z[0]=='-' ){
  14502. z++;
  14503. if( z[0]=='-' ) z++;
  14504. if( strcmp(z,"schema")==0 ){
  14505. bSchema = 1;
  14506. }else
  14507. if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
  14508. || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
  14509. ){
  14510. iSize = atoi(&z[5]);
  14511. }else
  14512. if( strcmp(z,"debug")==0 ){
  14513. bDebug = 1;
  14514. }else
  14515. {
  14516. utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
  14517. azArg[i], azArg[0]);
  14518. raw_printf(stderr, "Should be one of: --schema"
  14519. " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
  14520. rc = 1;
  14521. goto meta_command_exit;
  14522. }
  14523. }else if( zLike ){
  14524. raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
  14525. rc = 1;
  14526. goto meta_command_exit;
  14527. }else{
  14528. zLike = z;
  14529. bSeparate = 1;
  14530. if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
  14531. }
  14532. }
  14533. if( bSchema ){
  14534. zSql = "SELECT lower(name) FROM sqlite_master"
  14535. " WHERE type='table' AND coalesce(rootpage,0)>1"
  14536. " UNION ALL SELECT 'sqlite_master'"
  14537. " ORDER BY 1 collate nocase";
  14538. }else{
  14539. zSql = "SELECT lower(name) FROM sqlite_master"
  14540. " WHERE type='table' AND coalesce(rootpage,0)>1"
  14541. " AND name NOT LIKE 'sqlite_%'"
  14542. " ORDER BY 1 collate nocase";
  14543. }
  14544. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  14545. initText(&sQuery);
  14546. initText(&sSql);
  14547. appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
  14548. zSep = "VALUES(";
  14549. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  14550. const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
  14551. if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
  14552. if( strncmp(zTab, "sqlite_",7)!=0 ){
  14553. appendText(&sQuery,"SELECT * FROM ", 0);
  14554. appendText(&sQuery,zTab,'"');
  14555. appendText(&sQuery," NOT INDEXED;", 0);
  14556. }else if( strcmp(zTab, "sqlite_master")==0 ){
  14557. appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
  14558. " ORDER BY name;", 0);
  14559. }else if( strcmp(zTab, "sqlite_sequence")==0 ){
  14560. appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
  14561. " ORDER BY name;", 0);
  14562. }else if( strcmp(zTab, "sqlite_stat1")==0 ){
  14563. appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
  14564. " ORDER BY tbl,idx;", 0);
  14565. }else if( strcmp(zTab, "sqlite_stat3")==0
  14566. || strcmp(zTab, "sqlite_stat4")==0 ){
  14567. appendText(&sQuery, "SELECT * FROM ", 0);
  14568. appendText(&sQuery, zTab, 0);
  14569. appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
  14570. }
  14571. appendText(&sSql, zSep, 0);
  14572. appendText(&sSql, sQuery.z, '\'');
  14573. sQuery.n = 0;
  14574. appendText(&sSql, ",", 0);
  14575. appendText(&sSql, zTab, '\'');
  14576. zSep = "),(";
  14577. }
  14578. sqlite3_finalize(pStmt);
  14579. if( bSeparate ){
  14580. zSql = sqlite3_mprintf(
  14581. "%s))"
  14582. " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
  14583. " FROM [sha3sum$query]",
  14584. sSql.z, iSize);
  14585. }else{
  14586. zSql = sqlite3_mprintf(
  14587. "%s))"
  14588. " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
  14589. " FROM [sha3sum$query]",
  14590. sSql.z, iSize);
  14591. }
  14592. freeText(&sQuery);
  14593. freeText(&sSql);
  14594. if( bDebug ){
  14595. utf8_printf(p->out, "%s\n", zSql);
  14596. }else{
  14597. shell_exec(p, zSql, 0);
  14598. }
  14599. sqlite3_free(zSql);
  14600. }else
  14601. #ifndef SQLITE_NOHAVE_SYSTEM
  14602. if( c=='s'
  14603. && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
  14604. ){
  14605. char *zCmd;
  14606. int i, x;
  14607. if( nArg<2 ){
  14608. raw_printf(stderr, "Usage: .system COMMAND\n");
  14609. rc = 1;
  14610. goto meta_command_exit;
  14611. }
  14612. zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
  14613. for(i=2; i<nArg; i++){
  14614. zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
  14615. zCmd, azArg[i]);
  14616. }
  14617. x = system(zCmd);
  14618. sqlite3_free(zCmd);
  14619. if( x ) raw_printf(stderr, "System command returns %d\n", x);
  14620. }else
  14621. #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
  14622. if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
  14623. static const char *azBool[] = { "off", "on", "trigger", "full"};
  14624. int i;
  14625. if( nArg!=1 ){
  14626. raw_printf(stderr, "Usage: .show\n");
  14627. rc = 1;
  14628. goto meta_command_exit;
  14629. }
  14630. utf8_printf(p->out, "%12.12s: %s\n","echo",
  14631. azBool[ShellHasFlag(p, SHFLG_Echo)]);
  14632. utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
  14633. utf8_printf(p->out, "%12.12s: %s\n","explain",
  14634. p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
  14635. utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
  14636. utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
  14637. utf8_printf(p->out, "%12.12s: ", "nullvalue");
  14638. output_c_string(p->out, p->nullValue);
  14639. raw_printf(p->out, "\n");
  14640. utf8_printf(p->out,"%12.12s: %s\n","output",
  14641. strlen30(p->outfile) ? p->outfile : "stdout");
  14642. utf8_printf(p->out,"%12.12s: ", "colseparator");
  14643. output_c_string(p->out, p->colSeparator);
  14644. raw_printf(p->out, "\n");
  14645. utf8_printf(p->out,"%12.12s: ", "rowseparator");
  14646. output_c_string(p->out, p->rowSeparator);
  14647. raw_printf(p->out, "\n");
  14648. utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
  14649. utf8_printf(p->out, "%12.12s: ", "width");
  14650. for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
  14651. raw_printf(p->out, "%d ", p->colWidth[i]);
  14652. }
  14653. raw_printf(p->out, "\n");
  14654. utf8_printf(p->out, "%12.12s: %s\n", "filename",
  14655. p->zDbFilename ? p->zDbFilename : "");
  14656. }else
  14657. if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
  14658. if( nArg==2 ){
  14659. p->statsOn = (u8)booleanValue(azArg[1]);
  14660. }else if( nArg==1 ){
  14661. display_stats(p->db, p, 0);
  14662. }else{
  14663. raw_printf(stderr, "Usage: .stats ?on|off?\n");
  14664. rc = 1;
  14665. }
  14666. }else
  14667. if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
  14668. || (c=='i' && (strncmp(azArg[0], "indices", n)==0
  14669. || strncmp(azArg[0], "indexes", n)==0) )
  14670. ){
  14671. sqlite3_stmt *pStmt;
  14672. char **azResult;
  14673. int nRow, nAlloc;
  14674. int ii;
  14675. ShellText s;
  14676. initText(&s);
  14677. open_db(p, 0);
  14678. rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
  14679. if( rc ){
  14680. sqlite3_finalize(pStmt);
  14681. return shellDatabaseError(p->db);
  14682. }
  14683. if( nArg>2 && c=='i' ){
  14684. /* It is an historical accident that the .indexes command shows an error
  14685. ** when called with the wrong number of arguments whereas the .tables
  14686. ** command does not. */
  14687. raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
  14688. rc = 1;
  14689. sqlite3_finalize(pStmt);
  14690. goto meta_command_exit;
  14691. }
  14692. for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
  14693. const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
  14694. if( zDbName==0 ) continue;
  14695. if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
  14696. if( sqlite3_stricmp(zDbName, "main")==0 ){
  14697. appendText(&s, "SELECT name FROM ", 0);
  14698. }else{
  14699. appendText(&s, "SELECT ", 0);
  14700. appendText(&s, zDbName, '\'');
  14701. appendText(&s, "||'.'||name FROM ", 0);
  14702. }
  14703. appendText(&s, zDbName, '"');
  14704. appendText(&s, ".sqlite_master ", 0);
  14705. if( c=='t' ){
  14706. appendText(&s," WHERE type IN ('table','view')"
  14707. " AND name NOT LIKE 'sqlite_%'"
  14708. " AND name LIKE ?1", 0);
  14709. }else{
  14710. appendText(&s," WHERE type='index'"
  14711. " AND tbl_name LIKE ?1", 0);
  14712. }
  14713. }
  14714. rc = sqlite3_finalize(pStmt);
  14715. appendText(&s, " ORDER BY 1", 0);
  14716. rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
  14717. freeText(&s);
  14718. if( rc ) return shellDatabaseError(p->db);
  14719. /* Run the SQL statement prepared by the above block. Store the results
  14720. ** as an array of nul-terminated strings in azResult[]. */
  14721. nRow = nAlloc = 0;
  14722. azResult = 0;
  14723. if( nArg>1 ){
  14724. sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
  14725. }else{
  14726. sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
  14727. }
  14728. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  14729. if( nRow>=nAlloc ){
  14730. char **azNew;
  14731. int n2 = nAlloc*2 + 10;
  14732. azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
  14733. if( azNew==0 ) shell_out_of_memory();
  14734. nAlloc = n2;
  14735. azResult = azNew;
  14736. }
  14737. azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  14738. if( 0==azResult[nRow] ) shell_out_of_memory();
  14739. nRow++;
  14740. }
  14741. if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
  14742. rc = shellDatabaseError(p->db);
  14743. }
  14744. /* Pretty-print the contents of array azResult[] to the output */
  14745. if( rc==0 && nRow>0 ){
  14746. int len, maxlen = 0;
  14747. int i, j;
  14748. int nPrintCol, nPrintRow;
  14749. for(i=0; i<nRow; i++){
  14750. len = strlen30(azResult[i]);
  14751. if( len>maxlen ) maxlen = len;
  14752. }
  14753. nPrintCol = 80/(maxlen+2);
  14754. if( nPrintCol<1 ) nPrintCol = 1;
  14755. nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  14756. for(i=0; i<nPrintRow; i++){
  14757. for(j=i; j<nRow; j+=nPrintRow){
  14758. char *zSp = j<nPrintRow ? "" : " ";
  14759. utf8_printf(p->out, "%s%-*s", zSp, maxlen,
  14760. azResult[j] ? azResult[j]:"");
  14761. }
  14762. raw_printf(p->out, "\n");
  14763. }
  14764. }
  14765. for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
  14766. sqlite3_free(azResult);
  14767. }else
  14768. /* Begin redirecting output to the file "testcase-out.txt" */
  14769. if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
  14770. output_reset(p);
  14771. p->out = output_file_open("testcase-out.txt", 0);
  14772. if( p->out==0 ){
  14773. raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
  14774. }
  14775. if( nArg>=2 ){
  14776. sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
  14777. }else{
  14778. sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
  14779. }
  14780. }else
  14781. #ifndef SQLITE_UNTESTABLE
  14782. if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
  14783. static const struct {
  14784. const char *zCtrlName; /* Name of a test-control option */
  14785. int ctrlCode; /* Integer code for that option */
  14786. const char *zUsage; /* Usage notes */
  14787. } aCtrl[] = {
  14788. { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
  14789. { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
  14790. /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
  14791. /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
  14792. { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
  14793. /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
  14794. { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
  14795. { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN" },
  14796. { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
  14797. { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
  14798. { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
  14799. #ifdef YYCOVERAGE
  14800. { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
  14801. #endif
  14802. { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
  14803. { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
  14804. { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
  14805. { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
  14806. { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
  14807. };
  14808. int testctrl = -1;
  14809. int iCtrl = -1;
  14810. int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
  14811. int isOk = 0;
  14812. int i, n2;
  14813. const char *zCmd = 0;
  14814. open_db(p, 0);
  14815. zCmd = nArg>=2 ? azArg[1] : "help";
  14816. /* The argument can optionally begin with "-" or "--" */
  14817. if( zCmd[0]=='-' && zCmd[1] ){
  14818. zCmd++;
  14819. if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
  14820. }
  14821. /* --help lists all test-controls */
  14822. if( strcmp(zCmd,"help")==0 ){
  14823. utf8_printf(p->out, "Available test-controls:\n");
  14824. for(i=0; i<ArraySize(aCtrl); i++){
  14825. utf8_printf(p->out, " .testctrl %s %s\n",
  14826. aCtrl[i].zCtrlName, aCtrl[i].zUsage);
  14827. }
  14828. rc = 1;
  14829. goto meta_command_exit;
  14830. }
  14831. /* convert testctrl text option to value. allow any unique prefix
  14832. ** of the option name, or a numerical value. */
  14833. n2 = strlen30(zCmd);
  14834. for(i=0; i<ArraySize(aCtrl); i++){
  14835. if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
  14836. if( testctrl<0 ){
  14837. testctrl = aCtrl[i].ctrlCode;
  14838. iCtrl = i;
  14839. }else{
  14840. utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
  14841. "Use \".testctrl --help\" for help\n", zCmd);
  14842. rc = 1;
  14843. goto meta_command_exit;
  14844. }
  14845. }
  14846. }
  14847. if( testctrl<0 ){
  14848. utf8_printf(stderr,"Error: unknown test-control: %s\n"
  14849. "Use \".testctrl --help\" for help\n", zCmd);
  14850. }else{
  14851. switch(testctrl){
  14852. /* sqlite3_test_control(int, db, int) */
  14853. case SQLITE_TESTCTRL_OPTIMIZATIONS:
  14854. case SQLITE_TESTCTRL_RESERVE:
  14855. if( nArg==3 ){
  14856. int opt = (int)strtol(azArg[2], 0, 0);
  14857. rc2 = sqlite3_test_control(testctrl, p->db, opt);
  14858. isOk = 3;
  14859. }
  14860. break;
  14861. /* sqlite3_test_control(int) */
  14862. case SQLITE_TESTCTRL_PRNG_SAVE:
  14863. case SQLITE_TESTCTRL_PRNG_RESTORE:
  14864. case SQLITE_TESTCTRL_PRNG_RESET:
  14865. case SQLITE_TESTCTRL_BYTEORDER:
  14866. if( nArg==2 ){
  14867. rc2 = sqlite3_test_control(testctrl);
  14868. isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
  14869. }
  14870. break;
  14871. /* sqlite3_test_control(int, uint) */
  14872. case SQLITE_TESTCTRL_PENDING_BYTE:
  14873. if( nArg==3 ){
  14874. unsigned int opt = (unsigned int)integerValue(azArg[2]);
  14875. rc2 = sqlite3_test_control(testctrl, opt);
  14876. isOk = 3;
  14877. }
  14878. break;
  14879. /* sqlite3_test_control(int, int) */
  14880. case SQLITE_TESTCTRL_ASSERT:
  14881. case SQLITE_TESTCTRL_ALWAYS:
  14882. case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
  14883. if( nArg==3 ){
  14884. int opt = booleanValue(azArg[2]);
  14885. rc2 = sqlite3_test_control(testctrl, opt);
  14886. isOk = 1;
  14887. }
  14888. break;
  14889. /* sqlite3_test_control(int, int) */
  14890. case SQLITE_TESTCTRL_LOCALTIME_FAULT:
  14891. case SQLITE_TESTCTRL_NEVER_CORRUPT:
  14892. if( nArg==3 ){
  14893. int opt = booleanValue(azArg[2]);
  14894. rc2 = sqlite3_test_control(testctrl, opt);
  14895. isOk = 3;
  14896. }
  14897. break;
  14898. case SQLITE_TESTCTRL_IMPOSTER:
  14899. if( nArg==5 ){
  14900. rc2 = sqlite3_test_control(testctrl, p->db,
  14901. azArg[2],
  14902. integerValue(azArg[3]),
  14903. integerValue(azArg[4]));
  14904. isOk = 3;
  14905. }
  14906. break;
  14907. #ifdef YYCOVERAGE
  14908. case SQLITE_TESTCTRL_PARSER_COVERAGE:
  14909. if( nArg==2 ){
  14910. sqlite3_test_control(testctrl, p->out);
  14911. isOk = 3;
  14912. }
  14913. #endif
  14914. }
  14915. }
  14916. if( isOk==0 && iCtrl>=0 ){
  14917. utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
  14918. rc = 1;
  14919. }else if( isOk==1 ){
  14920. raw_printf(p->out, "%d\n", rc2);
  14921. }else if( isOk==2 ){
  14922. raw_printf(p->out, "0x%08x\n", rc2);
  14923. }
  14924. }else
  14925. #endif /* !defined(SQLITE_UNTESTABLE) */
  14926. if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
  14927. open_db(p, 0);
  14928. sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
  14929. }else
  14930. if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
  14931. if( nArg==2 ){
  14932. enableTimer = booleanValue(azArg[1]);
  14933. if( enableTimer && !HAS_TIMER ){
  14934. raw_printf(stderr, "Error: timer not available on this system.\n");
  14935. enableTimer = 0;
  14936. }
  14937. }else{
  14938. raw_printf(stderr, "Usage: .timer on|off\n");
  14939. rc = 1;
  14940. }
  14941. }else
  14942. #ifndef SQLITE_OMIT_TRACE
  14943. if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
  14944. int mType = 0;
  14945. int jj;
  14946. open_db(p, 0);
  14947. for(jj=1; jj<nArg; jj++){
  14948. const char *z = azArg[jj];
  14949. if( z[0]=='-' ){
  14950. if( optionMatch(z, "expanded") ){
  14951. p->eTraceType = SHELL_TRACE_EXPANDED;
  14952. }
  14953. #ifdef SQLITE_ENABLE_NORMALIZE
  14954. else if( optionMatch(z, "normalized") ){
  14955. p->eTraceType = SHELL_TRACE_NORMALIZED;
  14956. }
  14957. #endif
  14958. else if( optionMatch(z, "plain") ){
  14959. p->eTraceType = SHELL_TRACE_PLAIN;
  14960. }
  14961. else if( optionMatch(z, "profile") ){
  14962. mType |= SQLITE_TRACE_PROFILE;
  14963. }
  14964. else if( optionMatch(z, "row") ){
  14965. mType |= SQLITE_TRACE_ROW;
  14966. }
  14967. else if( optionMatch(z, "stmt") ){
  14968. mType |= SQLITE_TRACE_STMT;
  14969. }
  14970. else if( optionMatch(z, "close") ){
  14971. mType |= SQLITE_TRACE_CLOSE;
  14972. }
  14973. else {
  14974. raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
  14975. rc = 1;
  14976. goto meta_command_exit;
  14977. }
  14978. }else{
  14979. output_file_close(p->traceOut);
  14980. p->traceOut = output_file_open(azArg[1], 0);
  14981. }
  14982. }
  14983. if( p->traceOut==0 ){
  14984. sqlite3_trace_v2(p->db, 0, 0, 0);
  14985. }else{
  14986. if( mType==0 ) mType = SQLITE_TRACE_STMT;
  14987. sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
  14988. }
  14989. }else
  14990. #endif /* !defined(SQLITE_OMIT_TRACE) */
  14991. #if SQLITE_USER_AUTHENTICATION
  14992. if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
  14993. if( nArg<2 ){
  14994. raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
  14995. rc = 1;
  14996. goto meta_command_exit;
  14997. }
  14998. open_db(p, 0);
  14999. if( strcmp(azArg[1],"login")==0 ){
  15000. if( nArg!=4 ){
  15001. raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
  15002. rc = 1;
  15003. goto meta_command_exit;
  15004. }
  15005. rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
  15006. if( rc ){
  15007. utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
  15008. rc = 1;
  15009. }
  15010. }else if( strcmp(azArg[1],"add")==0 ){
  15011. if( nArg!=5 ){
  15012. raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
  15013. rc = 1;
  15014. goto meta_command_exit;
  15015. }
  15016. rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
  15017. booleanValue(azArg[4]));
  15018. if( rc ){
  15019. raw_printf(stderr, "User-Add failed: %d\n", rc);
  15020. rc = 1;
  15021. }
  15022. }else if( strcmp(azArg[1],"edit")==0 ){
  15023. if( nArg!=5 ){
  15024. raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
  15025. rc = 1;
  15026. goto meta_command_exit;
  15027. }
  15028. rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
  15029. booleanValue(azArg[4]));
  15030. if( rc ){
  15031. raw_printf(stderr, "User-Edit failed: %d\n", rc);
  15032. rc = 1;
  15033. }
  15034. }else if( strcmp(azArg[1],"delete")==0 ){
  15035. if( nArg!=3 ){
  15036. raw_printf(stderr, "Usage: .user delete USER\n");
  15037. rc = 1;
  15038. goto meta_command_exit;
  15039. }
  15040. rc = sqlite3_user_delete(p->db, azArg[2]);
  15041. if( rc ){
  15042. raw_printf(stderr, "User-Delete failed: %d\n", rc);
  15043. rc = 1;
  15044. }
  15045. }else{
  15046. raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
  15047. rc = 1;
  15048. goto meta_command_exit;
  15049. }
  15050. }else
  15051. #endif /* SQLITE_USER_AUTHENTICATION */
  15052. if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
  15053. utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
  15054. sqlite3_libversion(), sqlite3_sourceid());
  15055. #if SQLITE_HAVE_ZLIB
  15056. utf8_printf(p->out, "zlib version %s\n", zlibVersion());
  15057. #endif
  15058. #define CTIMEOPT_VAL_(opt) #opt
  15059. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  15060. #if defined(__clang__) && defined(__clang_major__)
  15061. utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
  15062. CTIMEOPT_VAL(__clang_minor__) "."
  15063. CTIMEOPT_VAL(__clang_patchlevel__) "\n");
  15064. #elif defined(_MSC_VER)
  15065. utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
  15066. #elif defined(__GNUC__) && defined(__VERSION__)
  15067. utf8_printf(p->out, "gcc-" __VERSION__ "\n");
  15068. #endif
  15069. }else
  15070. if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
  15071. const char *zDbName = nArg==2 ? azArg[1] : "main";
  15072. sqlite3_vfs *pVfs = 0;
  15073. if( p->db ){
  15074. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
  15075. if( pVfs ){
  15076. utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
  15077. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  15078. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  15079. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  15080. }
  15081. }
  15082. }else
  15083. if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
  15084. sqlite3_vfs *pVfs;
  15085. sqlite3_vfs *pCurrent = 0;
  15086. if( p->db ){
  15087. sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
  15088. }
  15089. for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
  15090. utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
  15091. pVfs==pCurrent ? " <--- CURRENT" : "");
  15092. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  15093. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  15094. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  15095. if( pVfs->pNext ){
  15096. raw_printf(p->out, "-----------------------------------\n");
  15097. }
  15098. }
  15099. }else
  15100. if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
  15101. const char *zDbName = nArg==2 ? azArg[1] : "main";
  15102. char *zVfsName = 0;
  15103. if( p->db ){
  15104. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
  15105. if( zVfsName ){
  15106. utf8_printf(p->out, "%s\n", zVfsName);
  15107. sqlite3_free(zVfsName);
  15108. }
  15109. }
  15110. }else
  15111. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  15112. if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
  15113. sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
  15114. }else
  15115. #endif
  15116. if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
  15117. int j;
  15118. assert( nArg<=ArraySize(azArg) );
  15119. for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
  15120. p->colWidth[j-1] = (int)integerValue(azArg[j]);
  15121. }
  15122. }else
  15123. {
  15124. utf8_printf(stderr, "Error: unknown command or invalid arguments: "
  15125. " \"%s\". Enter \".help\" for help\n", azArg[0]);
  15126. rc = 1;
  15127. }
  15128. meta_command_exit:
  15129. if( p->outCount ){
  15130. p->outCount--;
  15131. if( p->outCount==0 ) output_reset(p);
  15132. }
  15133. return rc;
  15134. }
  15135. /*
  15136. ** Return TRUE if a semicolon occurs anywhere in the first N characters
  15137. ** of string z[].
  15138. */
  15139. static int line_contains_semicolon(const char *z, int N){
  15140. int i;
  15141. for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
  15142. return 0;
  15143. }
  15144. /*
  15145. ** Test to see if a line consists entirely of whitespace.
  15146. */
  15147. static int _all_whitespace(const char *z){
  15148. for(; *z; z++){
  15149. if( IsSpace(z[0]) ) continue;
  15150. if( *z=='/' && z[1]=='*' ){
  15151. z += 2;
  15152. while( *z && (*z!='*' || z[1]!='/') ){ z++; }
  15153. if( *z==0 ) return 0;
  15154. z++;
  15155. continue;
  15156. }
  15157. if( *z=='-' && z[1]=='-' ){
  15158. z += 2;
  15159. while( *z && *z!='\n' ){ z++; }
  15160. if( *z==0 ) return 1;
  15161. continue;
  15162. }
  15163. return 0;
  15164. }
  15165. return 1;
  15166. }
  15167. /*
  15168. ** Return TRUE if the line typed in is an SQL command terminator other
  15169. ** than a semi-colon. The SQL Server style "go" command is understood
  15170. ** as is the Oracle "/".
  15171. */
  15172. static int line_is_command_terminator(const char *zLine){
  15173. while( IsSpace(zLine[0]) ){ zLine++; };
  15174. if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
  15175. return 1; /* Oracle */
  15176. }
  15177. if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
  15178. && _all_whitespace(&zLine[2]) ){
  15179. return 1; /* SQL Server */
  15180. }
  15181. return 0;
  15182. }
  15183. /*
  15184. ** We need a default sqlite3_complete() implementation to use in case
  15185. ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
  15186. ** any arbitrary text is a complete SQL statement. This is not very
  15187. ** user-friendly, but it does seem to work.
  15188. */
  15189. #ifdef SQLITE_OMIT_COMPLETE
  15190. #define sqlite3_complete(x) 1
  15191. #endif
  15192. /*
  15193. ** Return true if zSql is a complete SQL statement. Return false if it
  15194. ** ends in the middle of a string literal or C-style comment.
  15195. */
  15196. static int line_is_complete(char *zSql, int nSql){
  15197. int rc;
  15198. if( zSql==0 ) return 1;
  15199. zSql[nSql] = ';';
  15200. zSql[nSql+1] = 0;
  15201. rc = sqlite3_complete(zSql);
  15202. zSql[nSql] = 0;
  15203. return rc;
  15204. }
  15205. /*
  15206. ** Run a single line of SQL. Return the number of errors.
  15207. */
  15208. static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
  15209. int rc;
  15210. char *zErrMsg = 0;
  15211. open_db(p, 0);
  15212. if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
  15213. if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
  15214. BEGIN_TIMER;
  15215. rc = shell_exec(p, zSql, &zErrMsg);
  15216. END_TIMER;
  15217. if( rc || zErrMsg ){
  15218. char zPrefix[100];
  15219. if( in!=0 || !stdin_is_interactive ){
  15220. sqlite3_snprintf(sizeof(zPrefix), zPrefix,
  15221. "Error: near line %d:", startline);
  15222. }else{
  15223. sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
  15224. }
  15225. if( zErrMsg!=0 ){
  15226. utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
  15227. sqlite3_free(zErrMsg);
  15228. zErrMsg = 0;
  15229. }else{
  15230. utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
  15231. }
  15232. return 1;
  15233. }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
  15234. raw_printf(p->out, "changes: %3d total_changes: %d\n",
  15235. sqlite3_changes(p->db), sqlite3_total_changes(p->db));
  15236. }
  15237. return 0;
  15238. }
  15239. /*
  15240. ** Read input from *in and process it. If *in==0 then input
  15241. ** is interactive - the user is typing it it. Otherwise, input
  15242. ** is coming from a file or device. A prompt is issued and history
  15243. ** is saved only if input is interactive. An interrupt signal will
  15244. ** cause this routine to exit immediately, unless input is interactive.
  15245. **
  15246. ** Return the number of errors.
  15247. */
  15248. static int process_input(ShellState *p){
  15249. char *zLine = 0; /* A single input line */
  15250. char *zSql = 0; /* Accumulated SQL text */
  15251. int nLine; /* Length of current line */
  15252. int nSql = 0; /* Bytes of zSql[] used */
  15253. int nAlloc = 0; /* Allocated zSql[] space */
  15254. int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
  15255. int rc; /* Error code */
  15256. int errCnt = 0; /* Number of errors seen */
  15257. int startline = 0; /* Line number for start of current input */
  15258. p->lineno = 0;
  15259. while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
  15260. fflush(p->out);
  15261. zLine = one_input_line(p->in, zLine, nSql>0);
  15262. if( zLine==0 ){
  15263. /* End of input */
  15264. if( p->in==0 && stdin_is_interactive ) printf("\n");
  15265. break;
  15266. }
  15267. if( seenInterrupt ){
  15268. if( p->in!=0 ) break;
  15269. seenInterrupt = 0;
  15270. }
  15271. p->lineno++;
  15272. if( nSql==0 && _all_whitespace(zLine) ){
  15273. if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
  15274. continue;
  15275. }
  15276. if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
  15277. if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
  15278. if( zLine[0]=='.' ){
  15279. rc = do_meta_command(zLine, p);
  15280. if( rc==2 ){ /* exit requested */
  15281. break;
  15282. }else if( rc ){
  15283. errCnt++;
  15284. }
  15285. }
  15286. continue;
  15287. }
  15288. if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
  15289. memcpy(zLine,";",2);
  15290. }
  15291. nLine = strlen30(zLine);
  15292. if( nSql+nLine+2>=nAlloc ){
  15293. nAlloc = nSql+nLine+100;
  15294. zSql = realloc(zSql, nAlloc);
  15295. if( zSql==0 ) shell_out_of_memory();
  15296. }
  15297. nSqlPrior = nSql;
  15298. if( nSql==0 ){
  15299. int i;
  15300. for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
  15301. assert( nAlloc>0 && zSql!=0 );
  15302. memcpy(zSql, zLine+i, nLine+1-i);
  15303. startline = p->lineno;
  15304. nSql = nLine-i;
  15305. }else{
  15306. zSql[nSql++] = '\n';
  15307. memcpy(zSql+nSql, zLine, nLine+1);
  15308. nSql += nLine;
  15309. }
  15310. if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  15311. && sqlite3_complete(zSql) ){
  15312. errCnt += runOneSqlLine(p, zSql, p->in, startline);
  15313. nSql = 0;
  15314. if( p->outCount ){
  15315. output_reset(p);
  15316. p->outCount = 0;
  15317. }else{
  15318. clearTempFile(p);
  15319. }
  15320. }else if( nSql && _all_whitespace(zSql) ){
  15321. if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
  15322. nSql = 0;
  15323. }
  15324. }
  15325. if( nSql && !_all_whitespace(zSql) ){
  15326. errCnt += runOneSqlLine(p, zSql, p->in, startline);
  15327. }
  15328. free(zSql);
  15329. free(zLine);
  15330. return errCnt>0;
  15331. }
  15332. /*
  15333. ** Return a pathname which is the user's home directory. A
  15334. ** 0 return indicates an error of some kind.
  15335. */
  15336. static char *find_home_dir(int clearFlag){
  15337. static char *home_dir = NULL;
  15338. if( clearFlag ){
  15339. free(home_dir);
  15340. home_dir = 0;
  15341. return 0;
  15342. }
  15343. if( home_dir ) return home_dir;
  15344. #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
  15345. && !defined(__RTP__) && !defined(_WRS_KERNEL)
  15346. {
  15347. struct passwd *pwent;
  15348. uid_t uid = getuid();
  15349. if( (pwent=getpwuid(uid)) != NULL) {
  15350. home_dir = pwent->pw_dir;
  15351. }
  15352. }
  15353. #endif
  15354. #if defined(_WIN32_WCE)
  15355. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  15356. */
  15357. home_dir = "/";
  15358. #else
  15359. #if defined(_WIN32) || defined(WIN32)
  15360. if (!home_dir) {
  15361. home_dir = getenv("USERPROFILE");
  15362. }
  15363. #endif
  15364. if (!home_dir) {
  15365. home_dir = getenv("HOME");
  15366. }
  15367. #if defined(_WIN32) || defined(WIN32)
  15368. if (!home_dir) {
  15369. char *zDrive, *zPath;
  15370. int n;
  15371. zDrive = getenv("HOMEDRIVE");
  15372. zPath = getenv("HOMEPATH");
  15373. if( zDrive && zPath ){
  15374. n = strlen30(zDrive) + strlen30(zPath) + 1;
  15375. home_dir = malloc( n );
  15376. if( home_dir==0 ) return 0;
  15377. sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  15378. return home_dir;
  15379. }
  15380. home_dir = "c:\\";
  15381. }
  15382. #endif
  15383. #endif /* !_WIN32_WCE */
  15384. if( home_dir ){
  15385. int n = strlen30(home_dir) + 1;
  15386. char *z = malloc( n );
  15387. if( z ) memcpy(z, home_dir, n);
  15388. home_dir = z;
  15389. }
  15390. return home_dir;
  15391. }
  15392. /*
  15393. ** Read input from the file given by sqliterc_override. Or if that
  15394. ** parameter is NULL, take input from ~/.sqliterc
  15395. **
  15396. ** Returns the number of errors.
  15397. */
  15398. static void process_sqliterc(
  15399. ShellState *p, /* Configuration data */
  15400. const char *sqliterc_override /* Name of config file. NULL to use default */
  15401. ){
  15402. char *home_dir = NULL;
  15403. const char *sqliterc = sqliterc_override;
  15404. char *zBuf = 0;
  15405. FILE *inSaved = p->in;
  15406. int savedLineno = p->lineno;
  15407. if (sqliterc == NULL) {
  15408. home_dir = find_home_dir(0);
  15409. if( home_dir==0 ){
  15410. raw_printf(stderr, "-- warning: cannot find home directory;"
  15411. " cannot read ~/.sqliterc\n");
  15412. return;
  15413. }
  15414. zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
  15415. sqliterc = zBuf;
  15416. }
  15417. p->in = fopen(sqliterc,"rb");
  15418. if( p->in ){
  15419. if( stdin_is_interactive ){
  15420. utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
  15421. }
  15422. process_input(p);
  15423. fclose(p->in);
  15424. }
  15425. p->in = inSaved;
  15426. p->lineno = savedLineno;
  15427. sqlite3_free(zBuf);
  15428. }
  15429. /*
  15430. ** Show available command line options
  15431. */
  15432. static const char zOptions[] =
  15433. #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
  15434. " -A ARGS... run \".archive ARGS\" and exit\n"
  15435. #endif
  15436. " -append append the database to the end of the file\n"
  15437. " -ascii set output mode to 'ascii'\n"
  15438. " -bail stop after hitting an error\n"
  15439. " -batch force batch I/O\n"
  15440. " -column set output mode to 'column'\n"
  15441. " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
  15442. " -csv set output mode to 'csv'\n"
  15443. #if defined(SQLITE_ENABLE_DESERIALIZE)
  15444. " -deserialize open the database using sqlite3_deserialize()\n"
  15445. #endif
  15446. " -echo print commands before execution\n"
  15447. " -init FILENAME read/process named file\n"
  15448. " -[no]header turn headers on or off\n"
  15449. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  15450. " -heap SIZE Size of heap for memsys3 or memsys5\n"
  15451. #endif
  15452. " -help show this message\n"
  15453. " -html set output mode to HTML\n"
  15454. " -interactive force interactive I/O\n"
  15455. " -line set output mode to 'line'\n"
  15456. " -list set output mode to 'list'\n"
  15457. " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
  15458. #if defined(SQLITE_ENABLE_DESERIALIZE)
  15459. " -maxsize N maximum size for a --deserialize database\n"
  15460. #endif
  15461. " -memtrace trace all memory allocations and deallocations\n"
  15462. " -mmap N default mmap size set to N\n"
  15463. #ifdef SQLITE_ENABLE_MULTIPLEX
  15464. " -multiplex enable the multiplexor VFS\n"
  15465. #endif
  15466. " -newline SEP set output row separator. Default: '\\n'\n"
  15467. " -nullvalue TEXT set text string for NULL values. Default ''\n"
  15468. " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
  15469. " -quote set output mode to 'quote'\n"
  15470. " -readonly open the database read-only\n"
  15471. " -separator SEP set output column separator. Default: '|'\n"
  15472. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  15473. " -sorterref SIZE sorter references threshold size\n"
  15474. #endif
  15475. " -stats print memory stats before each finalize\n"
  15476. " -version show SQLite version\n"
  15477. " -vfs NAME use NAME as the default VFS\n"
  15478. #ifdef SQLITE_ENABLE_VFSTRACE
  15479. " -vfstrace enable tracing of all VFS calls\n"
  15480. #endif
  15481. #ifdef SQLITE_HAVE_ZLIB
  15482. " -zip open the file as a ZIP Archive\n"
  15483. #endif
  15484. ;
  15485. static void usage(int showDetail){
  15486. utf8_printf(stderr,
  15487. "Usage: %s [OPTIONS] FILENAME [SQL]\n"
  15488. "FILENAME is the name of an SQLite database. A new database is created\n"
  15489. "if the file does not previously exist.\n", Argv0);
  15490. if( showDetail ){
  15491. utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
  15492. }else{
  15493. raw_printf(stderr, "Use the -help option for additional information\n");
  15494. }
  15495. exit(1);
  15496. }
  15497. /*
  15498. ** Internal check: Verify that the SQLite is uninitialized. Print a
  15499. ** error message if it is initialized.
  15500. */
  15501. static void verify_uninitialized(void){
  15502. if( sqlite3_config(-1)==SQLITE_MISUSE ){
  15503. utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
  15504. " initialization.\n");
  15505. }
  15506. }
  15507. /*
  15508. ** Initialize the state information in data
  15509. */
  15510. static void main_init(ShellState *data) {
  15511. memset(data, 0, sizeof(*data));
  15512. data->normalMode = data->cMode = data->mode = MODE_List;
  15513. data->autoExplain = 1;
  15514. memcpy(data->colSeparator,SEP_Column, 2);
  15515. memcpy(data->rowSeparator,SEP_Row, 2);
  15516. data->showHeader = 0;
  15517. data->shellFlgs = SHFLG_Lookaside;
  15518. verify_uninitialized();
  15519. sqlite3_config(SQLITE_CONFIG_URI, 1);
  15520. sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
  15521. sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
  15522. sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  15523. sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
  15524. }
  15525. /*
  15526. ** Output text to the console in a font that attracts extra attention.
  15527. */
  15528. #ifdef _WIN32
  15529. static void printBold(const char *zText){
  15530. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  15531. CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
  15532. GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
  15533. SetConsoleTextAttribute(out,
  15534. FOREGROUND_RED|FOREGROUND_INTENSITY
  15535. );
  15536. printf("%s", zText);
  15537. SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
  15538. }
  15539. #else
  15540. static void printBold(const char *zText){
  15541. printf("\033[1m%s\033[0m", zText);
  15542. }
  15543. #endif
  15544. /*
  15545. ** Get the argument to an --option. Throw an error and die if no argument
  15546. ** is available.
  15547. */
  15548. static char *cmdline_option_value(int argc, char **argv, int i){
  15549. if( i==argc ){
  15550. utf8_printf(stderr, "%s: Error: missing argument to %s\n",
  15551. argv[0], argv[argc-1]);
  15552. exit(1);
  15553. }
  15554. return argv[i];
  15555. }
  15556. #ifndef SQLITE_SHELL_IS_UTF8
  15557. # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
  15558. # define SQLITE_SHELL_IS_UTF8 (0)
  15559. # else
  15560. # define SQLITE_SHELL_IS_UTF8 (1)
  15561. # endif
  15562. #endif
  15563. #if SQLITE_SHELL_IS_UTF8
  15564. int SQLITE_CDECL main(int argc, char **argv){
  15565. #else
  15566. int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
  15567. char **argv;
  15568. #endif
  15569. char *zErrMsg = 0;
  15570. ShellState data;
  15571. const char *zInitFile = 0;
  15572. int i;
  15573. int rc = 0;
  15574. int warnInmemoryDb = 0;
  15575. int readStdin = 1;
  15576. int nCmd = 0;
  15577. char **azCmd = 0;
  15578. const char *zVfs = 0; /* Value of -vfs command-line option */
  15579. #if !SQLITE_SHELL_IS_UTF8
  15580. char **argvToFree = 0;
  15581. int argcToFree = 0;
  15582. #endif
  15583. setBinaryMode(stdin, 0);
  15584. setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
  15585. stdin_is_interactive = isatty(0);
  15586. stdout_is_console = isatty(1);
  15587. #if !defined(_WIN32_WCE)
  15588. if( getenv("SQLITE_DEBUG_BREAK") ){
  15589. if( isatty(0) && isatty(2) ){
  15590. fprintf(stderr,
  15591. "attach debugger to process %d and press any key to continue.\n",
  15592. GETPID());
  15593. fgetc(stdin);
  15594. }else{
  15595. #if defined(_WIN32) || defined(WIN32)
  15596. DebugBreak();
  15597. #elif defined(SIGTRAP)
  15598. raise(SIGTRAP);
  15599. #endif
  15600. }
  15601. }
  15602. #endif
  15603. #if USE_SYSTEM_SQLITE+0!=1
  15604. if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
  15605. utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
  15606. sqlite3_sourceid(), SQLITE_SOURCE_ID);
  15607. exit(1);
  15608. }
  15609. #endif
  15610. main_init(&data);
  15611. /* On Windows, we must translate command-line arguments into UTF-8.
  15612. ** The SQLite memory allocator subsystem has to be enabled in order to
  15613. ** do this. But we want to run an sqlite3_shutdown() afterwards so that
  15614. ** subsequent sqlite3_config() calls will work. So copy all results into
  15615. ** memory that does not come from the SQLite memory allocator.
  15616. */
  15617. #if !SQLITE_SHELL_IS_UTF8
  15618. sqlite3_initialize();
  15619. argvToFree = malloc(sizeof(argv[0])*argc*2);
  15620. argcToFree = argc;
  15621. argv = argvToFree + argc;
  15622. if( argv==0 ) shell_out_of_memory();
  15623. for(i=0; i<argc; i++){
  15624. char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
  15625. int n;
  15626. if( z==0 ) shell_out_of_memory();
  15627. n = (int)strlen(z);
  15628. argv[i] = malloc( n+1 );
  15629. if( argv[i]==0 ) shell_out_of_memory();
  15630. memcpy(argv[i], z, n+1);
  15631. argvToFree[i] = argv[i];
  15632. sqlite3_free(z);
  15633. }
  15634. sqlite3_shutdown();
  15635. #endif
  15636. assert( argc>=1 && argv && argv[0] );
  15637. Argv0 = argv[0];
  15638. /* Make sure we have a valid signal handler early, before anything
  15639. ** else is done.
  15640. */
  15641. #ifdef SIGINT
  15642. signal(SIGINT, interrupt_handler);
  15643. #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
  15644. SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
  15645. #endif
  15646. #ifdef SQLITE_SHELL_DBNAME_PROC
  15647. {
  15648. /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
  15649. ** of a C-function that will provide the name of the database file. Use
  15650. ** this compile-time option to embed this shell program in larger
  15651. ** applications. */
  15652. extern void SQLITE_SHELL_DBNAME_PROC(const char**);
  15653. SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
  15654. warnInmemoryDb = 0;
  15655. }
  15656. #endif
  15657. /* Do an initial pass through the command-line argument to locate
  15658. ** the name of the database file, the name of the initialization file,
  15659. ** the size of the alternative malloc heap,
  15660. ** and the first command to execute.
  15661. */
  15662. verify_uninitialized();
  15663. for(i=1; i<argc; i++){
  15664. char *z;
  15665. z = argv[i];
  15666. if( z[0]!='-' ){
  15667. if( data.zDbFilename==0 ){
  15668. data.zDbFilename = z;
  15669. }else{
  15670. /* Excesss arguments are interpreted as SQL (or dot-commands) and
  15671. ** mean that nothing is read from stdin */
  15672. readStdin = 0;
  15673. nCmd++;
  15674. azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
  15675. if( azCmd==0 ) shell_out_of_memory();
  15676. azCmd[nCmd-1] = z;
  15677. }
  15678. }
  15679. if( z[1]=='-' ) z++;
  15680. if( strcmp(z,"-separator")==0
  15681. || strcmp(z,"-nullvalue")==0
  15682. || strcmp(z,"-newline")==0
  15683. || strcmp(z,"-cmd")==0
  15684. ){
  15685. (void)cmdline_option_value(argc, argv, ++i);
  15686. }else if( strcmp(z,"-init")==0 ){
  15687. zInitFile = cmdline_option_value(argc, argv, ++i);
  15688. }else if( strcmp(z,"-batch")==0 ){
  15689. /* Need to check for batch mode here to so we can avoid printing
  15690. ** informational messages (like from process_sqliterc) before
  15691. ** we do the actual processing of arguments later in a second pass.
  15692. */
  15693. stdin_is_interactive = 0;
  15694. }else if( strcmp(z,"-heap")==0 ){
  15695. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  15696. const char *zSize;
  15697. sqlite3_int64 szHeap;
  15698. zSize = cmdline_option_value(argc, argv, ++i);
  15699. szHeap = integerValue(zSize);
  15700. if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
  15701. sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
  15702. #else
  15703. (void)cmdline_option_value(argc, argv, ++i);
  15704. #endif
  15705. }else if( strcmp(z,"-pagecache")==0 ){
  15706. int n, sz;
  15707. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  15708. if( sz>70000 ) sz = 70000;
  15709. if( sz<0 ) sz = 0;
  15710. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  15711. sqlite3_config(SQLITE_CONFIG_PAGECACHE,
  15712. (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
  15713. data.shellFlgs |= SHFLG_Pagecache;
  15714. }else if( strcmp(z,"-lookaside")==0 ){
  15715. int n, sz;
  15716. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  15717. if( sz<0 ) sz = 0;
  15718. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  15719. if( n<0 ) n = 0;
  15720. sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
  15721. if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
  15722. #ifdef SQLITE_ENABLE_VFSTRACE
  15723. }else if( strcmp(z,"-vfstrace")==0 ){
  15724. extern int vfstrace_register(
  15725. const char *zTraceName,
  15726. const char *zOldVfsName,
  15727. int (*xOut)(const char*,void*),
  15728. void *pOutArg,
  15729. int makeDefault
  15730. );
  15731. vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
  15732. #endif
  15733. #ifdef SQLITE_ENABLE_MULTIPLEX
  15734. }else if( strcmp(z,"-multiplex")==0 ){
  15735. extern int sqlite3_multiple_initialize(const char*,int);
  15736. sqlite3_multiplex_initialize(0, 1);
  15737. #endif
  15738. }else if( strcmp(z,"-mmap")==0 ){
  15739. sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  15740. sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
  15741. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  15742. }else if( strcmp(z,"-sorterref")==0 ){
  15743. sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  15744. sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
  15745. #endif
  15746. }else if( strcmp(z,"-vfs")==0 ){
  15747. zVfs = cmdline_option_value(argc, argv, ++i);
  15748. #ifdef SQLITE_HAVE_ZLIB
  15749. }else if( strcmp(z,"-zip")==0 ){
  15750. data.openMode = SHELL_OPEN_ZIPFILE;
  15751. #endif
  15752. }else if( strcmp(z,"-append")==0 ){
  15753. data.openMode = SHELL_OPEN_APPENDVFS;
  15754. #ifdef SQLITE_ENABLE_DESERIALIZE
  15755. }else if( strcmp(z,"-deserialize")==0 ){
  15756. data.openMode = SHELL_OPEN_DESERIALIZE;
  15757. }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
  15758. data.szMax = integerValue(argv[++i]);
  15759. #endif
  15760. }else if( strcmp(z,"-readonly")==0 ){
  15761. data.openMode = SHELL_OPEN_READONLY;
  15762. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  15763. }else if( strncmp(z, "-A",2)==0 ){
  15764. /* All remaining command-line arguments are passed to the ".archive"
  15765. ** command, so ignore them */
  15766. break;
  15767. #endif
  15768. }else if( strcmp(z, "-memtrace")==0 ){
  15769. sqlite3MemTraceActivate(stderr);
  15770. }
  15771. }
  15772. verify_uninitialized();
  15773. #ifdef SQLITE_SHELL_INIT_PROC
  15774. {
  15775. /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
  15776. ** of a C-function that will perform initialization actions on SQLite that
  15777. ** occur just before or after sqlite3_initialize(). Use this compile-time
  15778. ** option to embed this shell program in larger applications. */
  15779. extern void SQLITE_SHELL_INIT_PROC(void);
  15780. SQLITE_SHELL_INIT_PROC();
  15781. }
  15782. #else
  15783. /* All the sqlite3_config() calls have now been made. So it is safe
  15784. ** to call sqlite3_initialize() and process any command line -vfs option. */
  15785. sqlite3_initialize();
  15786. #endif
  15787. if( zVfs ){
  15788. sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
  15789. if( pVfs ){
  15790. sqlite3_vfs_register(pVfs, 1);
  15791. }else{
  15792. utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
  15793. exit(1);
  15794. }
  15795. }
  15796. if( data.zDbFilename==0 ){
  15797. #ifndef SQLITE_OMIT_MEMORYDB
  15798. data.zDbFilename = ":memory:";
  15799. warnInmemoryDb = argc==1;
  15800. #else
  15801. utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
  15802. return 1;
  15803. #endif
  15804. }
  15805. data.out = stdout;
  15806. sqlite3_appendvfs_init(0,0,0);
  15807. /* Go ahead and open the database file if it already exists. If the
  15808. ** file does not exist, delay opening it. This prevents empty database
  15809. ** files from being created if a user mistypes the database name argument
  15810. ** to the sqlite command-line tool.
  15811. */
  15812. if( access(data.zDbFilename, 0)==0 ){
  15813. open_db(&data, 0);
  15814. }
  15815. /* Process the initialization file if there is one. If no -init option
  15816. ** is given on the command line, look for a file named ~/.sqliterc and
  15817. ** try to process it.
  15818. */
  15819. process_sqliterc(&data,zInitFile);
  15820. /* Make a second pass through the command-line argument and set
  15821. ** options. This second pass is delayed until after the initialization
  15822. ** file is processed so that the command-line arguments will override
  15823. ** settings in the initialization file.
  15824. */
  15825. for(i=1; i<argc; i++){
  15826. char *z = argv[i];
  15827. if( z[0]!='-' ) continue;
  15828. if( z[1]=='-' ){ z++; }
  15829. if( strcmp(z,"-init")==0 ){
  15830. i++;
  15831. }else if( strcmp(z,"-html")==0 ){
  15832. data.mode = MODE_Html;
  15833. }else if( strcmp(z,"-list")==0 ){
  15834. data.mode = MODE_List;
  15835. }else if( strcmp(z,"-quote")==0 ){
  15836. data.mode = MODE_Quote;
  15837. }else if( strcmp(z,"-line")==0 ){
  15838. data.mode = MODE_Line;
  15839. }else if( strcmp(z,"-column")==0 ){
  15840. data.mode = MODE_Column;
  15841. }else if( strcmp(z,"-csv")==0 ){
  15842. data.mode = MODE_Csv;
  15843. memcpy(data.colSeparator,",",2);
  15844. #ifdef SQLITE_HAVE_ZLIB
  15845. }else if( strcmp(z,"-zip")==0 ){
  15846. data.openMode = SHELL_OPEN_ZIPFILE;
  15847. #endif
  15848. }else if( strcmp(z,"-append")==0 ){
  15849. data.openMode = SHELL_OPEN_APPENDVFS;
  15850. #ifdef SQLITE_ENABLE_DESERIALIZE
  15851. }else if( strcmp(z,"-deserialize")==0 ){
  15852. data.openMode = SHELL_OPEN_DESERIALIZE;
  15853. }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
  15854. data.szMax = integerValue(argv[++i]);
  15855. #endif
  15856. }else if( strcmp(z,"-readonly")==0 ){
  15857. data.openMode = SHELL_OPEN_READONLY;
  15858. }else if( strcmp(z,"-ascii")==0 ){
  15859. data.mode = MODE_Ascii;
  15860. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  15861. SEP_Unit);
  15862. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  15863. SEP_Record);
  15864. }else if( strcmp(z,"-separator")==0 ){
  15865. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  15866. "%s",cmdline_option_value(argc,argv,++i));
  15867. }else if( strcmp(z,"-newline")==0 ){
  15868. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  15869. "%s",cmdline_option_value(argc,argv,++i));
  15870. }else if( strcmp(z,"-nullvalue")==0 ){
  15871. sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
  15872. "%s",cmdline_option_value(argc,argv,++i));
  15873. }else if( strcmp(z,"-header")==0 ){
  15874. data.showHeader = 1;
  15875. }else if( strcmp(z,"-noheader")==0 ){
  15876. data.showHeader = 0;
  15877. }else if( strcmp(z,"-echo")==0 ){
  15878. ShellSetFlag(&data, SHFLG_Echo);
  15879. }else if( strcmp(z,"-eqp")==0 ){
  15880. data.autoEQP = AUTOEQP_on;
  15881. }else if( strcmp(z,"-eqpfull")==0 ){
  15882. data.autoEQP = AUTOEQP_full;
  15883. }else if( strcmp(z,"-stats")==0 ){
  15884. data.statsOn = 1;
  15885. }else if( strcmp(z,"-scanstats")==0 ){
  15886. data.scanstatsOn = 1;
  15887. }else if( strcmp(z,"-backslash")==0 ){
  15888. /* Undocumented command-line option: -backslash
  15889. ** Causes C-style backslash escapes to be evaluated in SQL statements
  15890. ** prior to sending the SQL into SQLite. Useful for injecting
  15891. ** crazy bytes in the middle of SQL statements for testing and debugging.
  15892. */
  15893. ShellSetFlag(&data, SHFLG_Backslash);
  15894. }else if( strcmp(z,"-bail")==0 ){
  15895. bail_on_error = 1;
  15896. }else if( strcmp(z,"-version")==0 ){
  15897. printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
  15898. return 0;
  15899. }else if( strcmp(z,"-interactive")==0 ){
  15900. stdin_is_interactive = 1;
  15901. }else if( strcmp(z,"-batch")==0 ){
  15902. stdin_is_interactive = 0;
  15903. }else if( strcmp(z,"-heap")==0 ){
  15904. i++;
  15905. }else if( strcmp(z,"-pagecache")==0 ){
  15906. i+=2;
  15907. }else if( strcmp(z,"-lookaside")==0 ){
  15908. i+=2;
  15909. }else if( strcmp(z,"-mmap")==0 ){
  15910. i++;
  15911. }else if( strcmp(z,"-memtrace")==0 ){
  15912. i++;
  15913. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  15914. }else if( strcmp(z,"-sorterref")==0 ){
  15915. i++;
  15916. #endif
  15917. }else if( strcmp(z,"-vfs")==0 ){
  15918. i++;
  15919. #ifdef SQLITE_ENABLE_VFSTRACE
  15920. }else if( strcmp(z,"-vfstrace")==0 ){
  15921. i++;
  15922. #endif
  15923. #ifdef SQLITE_ENABLE_MULTIPLEX
  15924. }else if( strcmp(z,"-multiplex")==0 ){
  15925. i++;
  15926. #endif
  15927. }else if( strcmp(z,"-help")==0 ){
  15928. usage(1);
  15929. }else if( strcmp(z,"-cmd")==0 ){
  15930. /* Run commands that follow -cmd first and separately from commands
  15931. ** that simply appear on the command-line. This seems goofy. It would
  15932. ** be better if all commands ran in the order that they appear. But
  15933. ** we retain the goofy behavior for historical compatibility. */
  15934. if( i==argc-1 ) break;
  15935. z = cmdline_option_value(argc,argv,++i);
  15936. if( z[0]=='.' ){
  15937. rc = do_meta_command(z, &data);
  15938. if( rc && bail_on_error ) return rc==2 ? 0 : rc;
  15939. }else{
  15940. open_db(&data, 0);
  15941. rc = shell_exec(&data, z, &zErrMsg);
  15942. if( zErrMsg!=0 ){
  15943. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  15944. if( bail_on_error ) return rc!=0 ? rc : 1;
  15945. }else if( rc!=0 ){
  15946. utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
  15947. if( bail_on_error ) return rc;
  15948. }
  15949. }
  15950. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  15951. }else if( strncmp(z, "-A", 2)==0 ){
  15952. if( nCmd>0 ){
  15953. utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
  15954. " with \"%s\"\n", z);
  15955. return 1;
  15956. }
  15957. open_db(&data, OPEN_DB_ZIPFILE);
  15958. if( z[2] ){
  15959. argv[i] = &z[2];
  15960. arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
  15961. }else{
  15962. arDotCommand(&data, 1, argv+i, argc-i);
  15963. }
  15964. readStdin = 0;
  15965. break;
  15966. #endif
  15967. }else{
  15968. utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
  15969. raw_printf(stderr,"Use -help for a list of options.\n");
  15970. return 1;
  15971. }
  15972. data.cMode = data.mode;
  15973. }
  15974. if( !readStdin ){
  15975. /* Run all arguments that do not begin with '-' as if they were separate
  15976. ** command-line inputs, except for the argToSkip argument which contains
  15977. ** the database filename.
  15978. */
  15979. for(i=0; i<nCmd; i++){
  15980. if( azCmd[i][0]=='.' ){
  15981. rc = do_meta_command(azCmd[i], &data);
  15982. if( rc ) return rc==2 ? 0 : rc;
  15983. }else{
  15984. open_db(&data, 0);
  15985. rc = shell_exec(&data, azCmd[i], &zErrMsg);
  15986. if( zErrMsg!=0 ){
  15987. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  15988. return rc!=0 ? rc : 1;
  15989. }else if( rc!=0 ){
  15990. utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
  15991. return rc;
  15992. }
  15993. }
  15994. }
  15995. free(azCmd);
  15996. }else{
  15997. /* Run commands received from standard input
  15998. */
  15999. if( stdin_is_interactive ){
  16000. char *zHome;
  16001. char *zHistory;
  16002. int nHistory;
  16003. printf(
  16004. "SQLite version %s %.19s\n" /*extra-version-info*/
  16005. "Enter \".help\" for usage hints.\n",
  16006. sqlite3_libversion(), sqlite3_sourceid()
  16007. );
  16008. if( warnInmemoryDb ){
  16009. printf("Connected to a ");
  16010. printBold("transient in-memory database");
  16011. printf(".\nUse \".open FILENAME\" to reopen on a "
  16012. "persistent database.\n");
  16013. }
  16014. zHistory = getenv("SQLITE_HISTORY");
  16015. if( zHistory ){
  16016. zHistory = strdup(zHistory);
  16017. }else if( (zHome = find_home_dir(0))!=0 ){
  16018. nHistory = strlen30(zHome) + 20;
  16019. if( (zHistory = malloc(nHistory))!=0 ){
  16020. sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  16021. }
  16022. }
  16023. if( zHistory ){ shell_read_history(zHistory); }
  16024. #if HAVE_READLINE || HAVE_EDITLINE
  16025. rl_attempted_completion_function = readline_completion;
  16026. #elif HAVE_LINENOISE
  16027. linenoiseSetCompletionCallback(linenoise_completion);
  16028. #endif
  16029. data.in = 0;
  16030. rc = process_input(&data);
  16031. if( zHistory ){
  16032. shell_stifle_history(2000);
  16033. shell_write_history(zHistory);
  16034. free(zHistory);
  16035. }
  16036. }else{
  16037. data.in = stdin;
  16038. rc = process_input(&data);
  16039. }
  16040. }
  16041. set_table_name(&data, 0);
  16042. if( data.db ){
  16043. session_close_all(&data);
  16044. close_db(data.db);
  16045. }
  16046. sqlite3_free(data.zFreeOnClose);
  16047. find_home_dir(1);
  16048. output_reset(&data);
  16049. data.doXdgOpen = 0;
  16050. clearTempFile(&data);
  16051. #if !SQLITE_SHELL_IS_UTF8
  16052. for(i=0; i<argcToFree; i++) free(argvToFree[i]);
  16053. free(argvToFree);
  16054. #endif
  16055. /* Clear the global data structure so that valgrind will detect memory
  16056. ** leaks */
  16057. memset(&data, 0, sizeof(data));
  16058. return rc;
  16059. }