shell.c 621 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838
  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. ** Determine if we are dealing with WinRT, which provides only a subset of
  39. ** the full Win32 API.
  40. */
  41. #if !defined(SQLITE_OS_WINRT)
  42. # define SQLITE_OS_WINRT 0
  43. #endif
  44. /*
  45. ** Warning pragmas copied from msvc.h in the core.
  46. */
  47. #if defined(_MSC_VER)
  48. #pragma warning(disable : 4054)
  49. #pragma warning(disable : 4055)
  50. #pragma warning(disable : 4100)
  51. #pragma warning(disable : 4127)
  52. #pragma warning(disable : 4130)
  53. #pragma warning(disable : 4152)
  54. #pragma warning(disable : 4189)
  55. #pragma warning(disable : 4206)
  56. #pragma warning(disable : 4210)
  57. #pragma warning(disable : 4232)
  58. #pragma warning(disable : 4244)
  59. #pragma warning(disable : 4305)
  60. #pragma warning(disable : 4306)
  61. #pragma warning(disable : 4702)
  62. #pragma warning(disable : 4706)
  63. #endif /* defined(_MSC_VER) */
  64. /*
  65. ** No support for loadable extensions in VxWorks.
  66. */
  67. #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
  68. # define SQLITE_OMIT_LOAD_EXTENSION 1
  69. #endif
  70. /*
  71. ** Enable large-file support for fopen() and friends on unix.
  72. */
  73. #ifndef SQLITE_DISABLE_LFS
  74. # define _LARGE_FILE 1
  75. # ifndef _FILE_OFFSET_BITS
  76. # define _FILE_OFFSET_BITS 64
  77. # endif
  78. # define _LARGEFILE_SOURCE 1
  79. #endif
  80. #include <stdlib.h>
  81. #include <string.h>
  82. #include <stdio.h>
  83. #include <assert.h>
  84. #include "sqlite3.h"
  85. typedef sqlite3_int64 i64;
  86. typedef sqlite3_uint64 u64;
  87. typedef unsigned char u8;
  88. #if SQLITE_USER_AUTHENTICATION
  89. # include "sqlite3userauth.h"
  90. #endif
  91. #include <ctype.h>
  92. #include <stdarg.h>
  93. #if !defined(_WIN32) && !defined(WIN32)
  94. # include <signal.h>
  95. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  96. # include <pwd.h>
  97. # endif
  98. #endif
  99. #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
  100. # include <unistd.h>
  101. # include <dirent.h>
  102. # define GETPID getpid
  103. # if defined(__MINGW32__)
  104. # define DIRENT dirent
  105. # ifndef S_ISLNK
  106. # define S_ISLNK(mode) (0)
  107. # endif
  108. # endif
  109. #else
  110. # define GETPID (int)GetCurrentProcessId
  111. #endif
  112. #include <sys/types.h>
  113. #include <sys/stat.h>
  114. #if HAVE_READLINE
  115. # include <readline/readline.h>
  116. # include <readline/history.h>
  117. #endif
  118. #if HAVE_EDITLINE
  119. # include <editline/readline.h>
  120. #endif
  121. #if HAVE_EDITLINE || HAVE_READLINE
  122. # define shell_add_history(X) add_history(X)
  123. # define shell_read_history(X) read_history(X)
  124. # define shell_write_history(X) write_history(X)
  125. # define shell_stifle_history(X) stifle_history(X)
  126. # define shell_readline(X) readline(X)
  127. #elif HAVE_LINENOISE
  128. # include "linenoise.h"
  129. # define shell_add_history(X) linenoiseHistoryAdd(X)
  130. # define shell_read_history(X) linenoiseHistoryLoad(X)
  131. # define shell_write_history(X) linenoiseHistorySave(X)
  132. # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
  133. # define shell_readline(X) linenoise(X)
  134. #else
  135. # define shell_read_history(X)
  136. # define shell_write_history(X)
  137. # define shell_stifle_history(X)
  138. # define SHELL_USE_LOCAL_GETLINE 1
  139. #endif
  140. #if defined(_WIN32) || defined(WIN32)
  141. # if SQLITE_OS_WINRT
  142. # define SQLITE_OMIT_POPEN 1
  143. # else
  144. # include <io.h>
  145. # include <fcntl.h>
  146. # define isatty(h) _isatty(h)
  147. # ifndef access
  148. # define access(f,m) _access((f),(m))
  149. # endif
  150. # ifndef unlink
  151. # define unlink _unlink
  152. # endif
  153. # ifndef strdup
  154. # define strdup _strdup
  155. # endif
  156. # undef popen
  157. # define popen _popen
  158. # undef pclose
  159. # define pclose _pclose
  160. # endif
  161. #else
  162. /* Make sure isatty() has a prototype. */
  163. extern int isatty(int);
  164. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  165. /* popen and pclose are not C89 functions and so are
  166. ** sometimes omitted from the <stdio.h> header */
  167. extern FILE *popen(const char*,const char*);
  168. extern int pclose(FILE*);
  169. # else
  170. # define SQLITE_OMIT_POPEN 1
  171. # endif
  172. #endif
  173. #if defined(_WIN32_WCE)
  174. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
  175. * thus we always assume that we have a console. That can be
  176. * overridden with the -batch command line option.
  177. */
  178. #define isatty(x) 1
  179. #endif
  180. /* ctype macros that work with signed characters */
  181. #define IsSpace(X) isspace((unsigned char)X)
  182. #define IsDigit(X) isdigit((unsigned char)X)
  183. #define ToLower(X) (char)tolower((unsigned char)X)
  184. #if defined(_WIN32) || defined(WIN32)
  185. #if SQLITE_OS_WINRT
  186. #include <intrin.h>
  187. #endif
  188. #include <windows.h>
  189. /* string conversion routines only needed on Win32 */
  190. extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
  191. extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
  192. extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
  193. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
  194. #endif
  195. /* On Windows, we normally run with output mode of TEXT so that \n characters
  196. ** are automatically translated into \r\n. However, this behavior needs
  197. ** to be disabled in some cases (ex: when generating CSV output and when
  198. ** rendering quoted strings that contain \n characters). The following
  199. ** routines take care of that.
  200. */
  201. #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
  202. static void setBinaryMode(FILE *file, int isOutput){
  203. if( isOutput ) fflush(file);
  204. _setmode(_fileno(file), _O_BINARY);
  205. }
  206. static void setTextMode(FILE *file, int isOutput){
  207. if( isOutput ) fflush(file);
  208. _setmode(_fileno(file), _O_TEXT);
  209. }
  210. #else
  211. # define setBinaryMode(X,Y)
  212. # define setTextMode(X,Y)
  213. #endif
  214. /* True if the timer is enabled */
  215. static int enableTimer = 0;
  216. /* Return the current wall-clock time */
  217. static sqlite3_int64 timeOfDay(void){
  218. static sqlite3_vfs *clockVfs = 0;
  219. sqlite3_int64 t;
  220. if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
  221. if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
  222. clockVfs->xCurrentTimeInt64(clockVfs, &t);
  223. }else{
  224. double r;
  225. clockVfs->xCurrentTime(clockVfs, &r);
  226. t = (sqlite3_int64)(r*86400000.0);
  227. }
  228. return t;
  229. }
  230. #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
  231. #include <sys/time.h>
  232. #include <sys/resource.h>
  233. /* VxWorks does not support getrusage() as far as we can determine */
  234. #if defined(_WRS_KERNEL) || defined(__RTP__)
  235. struct rusage {
  236. struct timeval ru_utime; /* user CPU time used */
  237. struct timeval ru_stime; /* system CPU time used */
  238. };
  239. #define getrusage(A,B) memset(B,0,sizeof(*B))
  240. #endif
  241. /* Saved resource information for the beginning of an operation */
  242. static struct rusage sBegin; /* CPU time at start */
  243. static sqlite3_int64 iBegin; /* Wall-clock time at start */
  244. /*
  245. ** Begin timing an operation
  246. */
  247. static void beginTimer(void){
  248. if( enableTimer ){
  249. getrusage(RUSAGE_SELF, &sBegin);
  250. iBegin = timeOfDay();
  251. }
  252. }
  253. /* Return the difference of two time_structs in seconds */
  254. static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  255. return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
  256. (double)(pEnd->tv_sec - pStart->tv_sec);
  257. }
  258. /*
  259. ** Print the timing results.
  260. */
  261. static void endTimer(void){
  262. if( enableTimer ){
  263. sqlite3_int64 iEnd = timeOfDay();
  264. struct rusage sEnd;
  265. getrusage(RUSAGE_SELF, &sEnd);
  266. printf("Run Time: real %.3f user %f sys %f\n",
  267. (iEnd - iBegin)*0.001,
  268. timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
  269. timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  270. }
  271. }
  272. #define BEGIN_TIMER beginTimer()
  273. #define END_TIMER endTimer()
  274. #define HAS_TIMER 1
  275. #elif (defined(_WIN32) || defined(WIN32))
  276. /* Saved resource information for the beginning of an operation */
  277. static HANDLE hProcess;
  278. static FILETIME ftKernelBegin;
  279. static FILETIME ftUserBegin;
  280. static sqlite3_int64 ftWallBegin;
  281. typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
  282. LPFILETIME, LPFILETIME);
  283. static GETPROCTIMES getProcessTimesAddr = NULL;
  284. /*
  285. ** Check to see if we have timer support. Return 1 if necessary
  286. ** support found (or found previously).
  287. */
  288. static int hasTimer(void){
  289. if( getProcessTimesAddr ){
  290. return 1;
  291. } else {
  292. #if !SQLITE_OS_WINRT
  293. /* GetProcessTimes() isn't supported in WIN95 and some other Windows
  294. ** versions. See if the version we are running on has it, and if it
  295. ** does, save off a pointer to it and the current process handle.
  296. */
  297. hProcess = GetCurrentProcess();
  298. if( hProcess ){
  299. HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
  300. if( NULL != hinstLib ){
  301. getProcessTimesAddr =
  302. (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
  303. if( NULL != getProcessTimesAddr ){
  304. return 1;
  305. }
  306. FreeLibrary(hinstLib);
  307. }
  308. }
  309. #endif
  310. }
  311. return 0;
  312. }
  313. /*
  314. ** Begin timing an operation
  315. */
  316. static void beginTimer(void){
  317. if( enableTimer && getProcessTimesAddr ){
  318. FILETIME ftCreation, ftExit;
  319. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
  320. &ftKernelBegin,&ftUserBegin);
  321. ftWallBegin = timeOfDay();
  322. }
  323. }
  324. /* Return the difference of two FILETIME structs in seconds */
  325. static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
  326. sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
  327. sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
  328. return (double) ((i64End - i64Start) / 10000000.0);
  329. }
  330. /*
  331. ** Print the timing results.
  332. */
  333. static void endTimer(void){
  334. if( enableTimer && getProcessTimesAddr){
  335. FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
  336. sqlite3_int64 ftWallEnd = timeOfDay();
  337. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
  338. printf("Run Time: real %.3f user %f sys %f\n",
  339. (ftWallEnd - ftWallBegin)*0.001,
  340. timeDiff(&ftUserBegin, &ftUserEnd),
  341. timeDiff(&ftKernelBegin, &ftKernelEnd));
  342. }
  343. }
  344. #define BEGIN_TIMER beginTimer()
  345. #define END_TIMER endTimer()
  346. #define HAS_TIMER hasTimer()
  347. #else
  348. #define BEGIN_TIMER
  349. #define END_TIMER
  350. #define HAS_TIMER 0
  351. #endif
  352. /*
  353. ** Used to prevent warnings about unused parameters
  354. */
  355. #define UNUSED_PARAMETER(x) (void)(x)
  356. /*
  357. ** Number of elements in an array
  358. */
  359. #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
  360. /*
  361. ** If the following flag is set, then command execution stops
  362. ** at an error if we are not interactive.
  363. */
  364. static int bail_on_error = 0;
  365. /*
  366. ** Threat stdin as an interactive input if the following variable
  367. ** is true. Otherwise, assume stdin is connected to a file or pipe.
  368. */
  369. static int stdin_is_interactive = 1;
  370. /*
  371. ** On Windows systems we have to know if standard output is a console
  372. ** in order to translate UTF-8 into MBCS. The following variable is
  373. ** true if translation is required.
  374. */
  375. static int stdout_is_console = 1;
  376. /*
  377. ** The following is the open SQLite database. We make a pointer
  378. ** to this database a static variable so that it can be accessed
  379. ** by the SIGINT handler to interrupt database processing.
  380. */
  381. static sqlite3 *globalDb = 0;
  382. /*
  383. ** True if an interrupt (Control-C) has been received.
  384. */
  385. static volatile int seenInterrupt = 0;
  386. #ifdef SQLITE_DEBUG
  387. /*
  388. ** Out-of-memory simulator variables
  389. */
  390. static unsigned int oomCounter = 0; /* Simulate OOM when equals 1 */
  391. static unsigned int oomRepeat = 0; /* Number of OOMs in a row */
  392. static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
  393. #endif /* SQLITE_DEBUG */
  394. /*
  395. ** This is the name of our program. It is set in main(), used
  396. ** in a number of other places, mostly for error messages.
  397. */
  398. static char *Argv0;
  399. /*
  400. ** Prompt strings. Initialized in main. Settable with
  401. ** .prompt main continue
  402. */
  403. static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
  404. static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
  405. /*
  406. ** Render output like fprintf(). Except, if the output is going to the
  407. ** console and if this is running on a Windows machine, translate the
  408. ** output from UTF-8 into MBCS.
  409. */
  410. #if defined(_WIN32) || defined(WIN32)
  411. void utf8_printf(FILE *out, const char *zFormat, ...){
  412. va_list ap;
  413. va_start(ap, zFormat);
  414. if( stdout_is_console && (out==stdout || out==stderr) ){
  415. char *z1 = sqlite3_vmprintf(zFormat, ap);
  416. char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
  417. sqlite3_free(z1);
  418. fputs(z2, out);
  419. sqlite3_free(z2);
  420. }else{
  421. vfprintf(out, zFormat, ap);
  422. }
  423. va_end(ap);
  424. }
  425. #elif !defined(utf8_printf)
  426. # define utf8_printf fprintf
  427. #endif
  428. /*
  429. ** Render output like fprintf(). This should not be used on anything that
  430. ** includes string formatting (e.g. "%s").
  431. */
  432. #if !defined(raw_printf)
  433. # define raw_printf fprintf
  434. #endif
  435. /* Indicate out-of-memory and exit. */
  436. static void shell_out_of_memory(void){
  437. raw_printf(stderr,"Error: out of memory\n");
  438. exit(1);
  439. }
  440. #ifdef SQLITE_DEBUG
  441. /* This routine is called when a simulated OOM occurs. It is broken
  442. ** out as a separate routine to make it easy to set a breakpoint on
  443. ** the OOM
  444. */
  445. void shellOomFault(void){
  446. if( oomRepeat>0 ){
  447. oomRepeat--;
  448. }else{
  449. oomCounter--;
  450. }
  451. }
  452. #endif /* SQLITE_DEBUG */
  453. #ifdef SQLITE_DEBUG
  454. /* This routine is a replacement malloc() that is used to simulate
  455. ** Out-Of-Memory (OOM) errors for testing purposes.
  456. */
  457. static void *oomMalloc(int nByte){
  458. if( oomCounter ){
  459. if( oomCounter==1 ){
  460. shellOomFault();
  461. return 0;
  462. }else{
  463. oomCounter--;
  464. }
  465. }
  466. return defaultMalloc(nByte);
  467. }
  468. #endif /* SQLITE_DEBUG */
  469. #ifdef SQLITE_DEBUG
  470. /* Register the OOM simulator. This must occur before any memory
  471. ** allocations */
  472. static void registerOomSimulator(void){
  473. sqlite3_mem_methods mem;
  474. sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
  475. defaultMalloc = mem.xMalloc;
  476. mem.xMalloc = oomMalloc;
  477. sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
  478. }
  479. #endif
  480. /*
  481. ** Write I/O traces to the following stream.
  482. */
  483. #ifdef SQLITE_ENABLE_IOTRACE
  484. static FILE *iotrace = 0;
  485. #endif
  486. /*
  487. ** This routine works like printf in that its first argument is a
  488. ** format string and subsequent arguments are values to be substituted
  489. ** in place of % fields. The result of formatting this string
  490. ** is written to iotrace.
  491. */
  492. #ifdef SQLITE_ENABLE_IOTRACE
  493. static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
  494. va_list ap;
  495. char *z;
  496. if( iotrace==0 ) return;
  497. va_start(ap, zFormat);
  498. z = sqlite3_vmprintf(zFormat, ap);
  499. va_end(ap);
  500. utf8_printf(iotrace, "%s", z);
  501. sqlite3_free(z);
  502. }
  503. #endif
  504. /*
  505. ** Output string zUtf to stream pOut as w characters. If w is negative,
  506. ** then right-justify the text. W is the width in UTF-8 characters, not
  507. ** in bytes. This is different from the %*.*s specification in printf
  508. ** since with %*.*s the width is measured in bytes, not characters.
  509. */
  510. static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
  511. int i;
  512. int n;
  513. int aw = w<0 ? -w : w;
  514. char zBuf[1000];
  515. if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
  516. for(i=n=0; zUtf[i]; i++){
  517. if( (zUtf[i]&0xc0)!=0x80 ){
  518. n++;
  519. if( n==aw ){
  520. do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
  521. break;
  522. }
  523. }
  524. }
  525. if( n>=aw ){
  526. utf8_printf(pOut, "%.*s", i, zUtf);
  527. }else if( w<0 ){
  528. utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
  529. }else{
  530. utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
  531. }
  532. }
  533. /*
  534. ** Determines if a string is a number of not.
  535. */
  536. static int isNumber(const char *z, int *realnum){
  537. if( *z=='-' || *z=='+' ) z++;
  538. if( !IsDigit(*z) ){
  539. return 0;
  540. }
  541. z++;
  542. if( realnum ) *realnum = 0;
  543. while( IsDigit(*z) ){ z++; }
  544. if( *z=='.' ){
  545. z++;
  546. if( !IsDigit(*z) ) return 0;
  547. while( IsDigit(*z) ){ z++; }
  548. if( realnum ) *realnum = 1;
  549. }
  550. if( *z=='e' || *z=='E' ){
  551. z++;
  552. if( *z=='+' || *z=='-' ) z++;
  553. if( !IsDigit(*z) ) return 0;
  554. while( IsDigit(*z) ){ z++; }
  555. if( realnum ) *realnum = 1;
  556. }
  557. return *z==0;
  558. }
  559. /*
  560. ** Compute a string length that is limited to what can be stored in
  561. ** lower 30 bits of a 32-bit signed integer.
  562. */
  563. static int strlen30(const char *z){
  564. const char *z2 = z;
  565. while( *z2 ){ z2++; }
  566. return 0x3fffffff & (int)(z2 - z);
  567. }
  568. /*
  569. ** Return the length of a string in characters. Multibyte UTF8 characters
  570. ** count as a single character.
  571. */
  572. static int strlenChar(const char *z){
  573. int n = 0;
  574. while( *z ){
  575. if( (0xc0&*(z++))!=0x80 ) n++;
  576. }
  577. return n;
  578. }
  579. /*
  580. ** Return true if zFile does not exist or if it is not an ordinary file.
  581. */
  582. #ifdef _WIN32
  583. # define notNormalFile(X) 0
  584. #else
  585. static int notNormalFile(const char *zFile){
  586. struct stat x;
  587. int rc;
  588. memset(&x, 0, sizeof(x));
  589. rc = stat(zFile, &x);
  590. return rc || !S_ISREG(x.st_mode);
  591. }
  592. #endif
  593. /*
  594. ** This routine reads a line of text from FILE in, stores
  595. ** the text in memory obtained from malloc() and returns a pointer
  596. ** to the text. NULL is returned at end of file, or if malloc()
  597. ** fails.
  598. **
  599. ** If zLine is not NULL then it is a malloced buffer returned from
  600. ** a previous call to this routine that may be reused.
  601. */
  602. static char *local_getline(char *zLine, FILE *in){
  603. int nLine = zLine==0 ? 0 : 100;
  604. int n = 0;
  605. while( 1 ){
  606. if( n+100>nLine ){
  607. nLine = nLine*2 + 100;
  608. zLine = realloc(zLine, nLine);
  609. if( zLine==0 ) shell_out_of_memory();
  610. }
  611. if( fgets(&zLine[n], nLine - n, in)==0 ){
  612. if( n==0 ){
  613. free(zLine);
  614. return 0;
  615. }
  616. zLine[n] = 0;
  617. break;
  618. }
  619. while( zLine[n] ) n++;
  620. if( n>0 && zLine[n-1]=='\n' ){
  621. n--;
  622. if( n>0 && zLine[n-1]=='\r' ) n--;
  623. zLine[n] = 0;
  624. break;
  625. }
  626. }
  627. #if defined(_WIN32) || defined(WIN32)
  628. /* For interactive input on Windows systems, translate the
  629. ** multi-byte characterset characters into UTF-8. */
  630. if( stdin_is_interactive && in==stdin ){
  631. char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
  632. if( zTrans ){
  633. int nTrans = strlen30(zTrans)+1;
  634. if( nTrans>nLine ){
  635. zLine = realloc(zLine, nTrans);
  636. if( zLine==0 ) shell_out_of_memory();
  637. }
  638. memcpy(zLine, zTrans, nTrans);
  639. sqlite3_free(zTrans);
  640. }
  641. }
  642. #endif /* defined(_WIN32) || defined(WIN32) */
  643. return zLine;
  644. }
  645. /*
  646. ** Retrieve a single line of input text.
  647. **
  648. ** If in==0 then read from standard input and prompt before each line.
  649. ** If isContinuation is true, then a continuation prompt is appropriate.
  650. ** If isContinuation is zero, then the main prompt should be used.
  651. **
  652. ** If zPrior is not NULL then it is a buffer from a prior call to this
  653. ** routine that can be reused.
  654. **
  655. ** The result is stored in space obtained from malloc() and must either
  656. ** be freed by the caller or else passed back into this routine via the
  657. ** zPrior argument for reuse.
  658. */
  659. static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
  660. char *zPrompt;
  661. char *zResult;
  662. if( in!=0 ){
  663. zResult = local_getline(zPrior, in);
  664. }else{
  665. zPrompt = isContinuation ? continuePrompt : mainPrompt;
  666. #if SHELL_USE_LOCAL_GETLINE
  667. printf("%s", zPrompt);
  668. fflush(stdout);
  669. zResult = local_getline(zPrior, stdin);
  670. #else
  671. free(zPrior);
  672. zResult = shell_readline(zPrompt);
  673. if( zResult && *zResult ) shell_add_history(zResult);
  674. #endif
  675. }
  676. return zResult;
  677. }
  678. /*
  679. ** Return the value of a hexadecimal digit. Return -1 if the input
  680. ** is not a hex digit.
  681. */
  682. static int hexDigitValue(char c){
  683. if( c>='0' && c<='9' ) return c - '0';
  684. if( c>='a' && c<='f' ) return c - 'a' + 10;
  685. if( c>='A' && c<='F' ) return c - 'A' + 10;
  686. return -1;
  687. }
  688. /*
  689. ** Interpret zArg as an integer value, possibly with suffixes.
  690. */
  691. static sqlite3_int64 integerValue(const char *zArg){
  692. sqlite3_int64 v = 0;
  693. static const struct { char *zSuffix; int iMult; } aMult[] = {
  694. { "KiB", 1024 },
  695. { "MiB", 1024*1024 },
  696. { "GiB", 1024*1024*1024 },
  697. { "KB", 1000 },
  698. { "MB", 1000000 },
  699. { "GB", 1000000000 },
  700. { "K", 1000 },
  701. { "M", 1000000 },
  702. { "G", 1000000000 },
  703. };
  704. int i;
  705. int isNeg = 0;
  706. if( zArg[0]=='-' ){
  707. isNeg = 1;
  708. zArg++;
  709. }else if( zArg[0]=='+' ){
  710. zArg++;
  711. }
  712. if( zArg[0]=='0' && zArg[1]=='x' ){
  713. int x;
  714. zArg += 2;
  715. while( (x = hexDigitValue(zArg[0]))>=0 ){
  716. v = (v<<4) + x;
  717. zArg++;
  718. }
  719. }else{
  720. while( IsDigit(zArg[0]) ){
  721. v = v*10 + zArg[0] - '0';
  722. zArg++;
  723. }
  724. }
  725. for(i=0; i<ArraySize(aMult); i++){
  726. if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
  727. v *= aMult[i].iMult;
  728. break;
  729. }
  730. }
  731. return isNeg? -v : v;
  732. }
  733. /*
  734. ** A variable length string to which one can append text.
  735. */
  736. typedef struct ShellText ShellText;
  737. struct ShellText {
  738. char *z;
  739. int n;
  740. int nAlloc;
  741. };
  742. /*
  743. ** Initialize and destroy a ShellText object
  744. */
  745. static void initText(ShellText *p){
  746. memset(p, 0, sizeof(*p));
  747. }
  748. static void freeText(ShellText *p){
  749. free(p->z);
  750. initText(p);
  751. }
  752. /* zIn is either a pointer to a NULL-terminated string in memory obtained
  753. ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  754. ** added to zIn, and the result returned in memory obtained from malloc().
  755. ** zIn, if it was not NULL, is freed.
  756. **
  757. ** If the third argument, quote, is not '\0', then it is used as a
  758. ** quote character for zAppend.
  759. */
  760. static void appendText(ShellText *p, char const *zAppend, char quote){
  761. int len;
  762. int i;
  763. int nAppend = strlen30(zAppend);
  764. len = nAppend+p->n+1;
  765. if( quote ){
  766. len += 2;
  767. for(i=0; i<nAppend; i++){
  768. if( zAppend[i]==quote ) len++;
  769. }
  770. }
  771. if( p->n+len>=p->nAlloc ){
  772. p->nAlloc = p->nAlloc*2 + len + 20;
  773. p->z = realloc(p->z, p->nAlloc);
  774. if( p->z==0 ) shell_out_of_memory();
  775. }
  776. if( quote ){
  777. char *zCsr = p->z+p->n;
  778. *zCsr++ = quote;
  779. for(i=0; i<nAppend; i++){
  780. *zCsr++ = zAppend[i];
  781. if( zAppend[i]==quote ) *zCsr++ = quote;
  782. }
  783. *zCsr++ = quote;
  784. p->n = (int)(zCsr - p->z);
  785. *zCsr = '\0';
  786. }else{
  787. memcpy(p->z+p->n, zAppend, nAppend);
  788. p->n += nAppend;
  789. p->z[p->n] = '\0';
  790. }
  791. }
  792. /*
  793. ** Attempt to determine if identifier zName needs to be quoted, either
  794. ** because it contains non-alphanumeric characters, or because it is an
  795. ** SQLite keyword. Be conservative in this estimate: When in doubt assume
  796. ** that quoting is required.
  797. **
  798. ** Return '"' if quoting is required. Return 0 if no quoting is required.
  799. */
  800. static char quoteChar(const char *zName){
  801. int i;
  802. if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
  803. for(i=0; zName[i]; i++){
  804. if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
  805. }
  806. return sqlite3_keyword_check(zName, i) ? '"' : 0;
  807. }
  808. /*
  809. ** Construct a fake object name and column list to describe the structure
  810. ** of the view, virtual table, or table valued function zSchema.zName.
  811. */
  812. static char *shellFakeSchema(
  813. sqlite3 *db, /* The database connection containing the vtab */
  814. const char *zSchema, /* Schema of the database holding the vtab */
  815. const char *zName /* The name of the virtual table */
  816. ){
  817. sqlite3_stmt *pStmt = 0;
  818. char *zSql;
  819. ShellText s;
  820. char cQuote;
  821. char *zDiv = "(";
  822. int nRow = 0;
  823. zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
  824. zSchema ? zSchema : "main", zName);
  825. sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  826. sqlite3_free(zSql);
  827. initText(&s);
  828. if( zSchema ){
  829. cQuote = quoteChar(zSchema);
  830. if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
  831. appendText(&s, zSchema, cQuote);
  832. appendText(&s, ".", 0);
  833. }
  834. cQuote = quoteChar(zName);
  835. appendText(&s, zName, cQuote);
  836. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  837. const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
  838. nRow++;
  839. appendText(&s, zDiv, 0);
  840. zDiv = ",";
  841. cQuote = quoteChar(zCol);
  842. appendText(&s, zCol, cQuote);
  843. }
  844. appendText(&s, ")", 0);
  845. sqlite3_finalize(pStmt);
  846. if( nRow==0 ){
  847. freeText(&s);
  848. s.z = 0;
  849. }
  850. return s.z;
  851. }
  852. /*
  853. ** SQL function: shell_module_schema(X)
  854. **
  855. ** Return a fake schema for the table-valued function or eponymous virtual
  856. ** table X.
  857. */
  858. static void shellModuleSchema(
  859. sqlite3_context *pCtx,
  860. int nVal,
  861. sqlite3_value **apVal
  862. ){
  863. const char *zName = (const char*)sqlite3_value_text(apVal[0]);
  864. char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
  865. UNUSED_PARAMETER(nVal);
  866. if( zFake ){
  867. sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
  868. -1, sqlite3_free);
  869. free(zFake);
  870. }
  871. }
  872. /*
  873. ** SQL function: shell_add_schema(S,X)
  874. **
  875. ** Add the schema name X to the CREATE statement in S and return the result.
  876. ** Examples:
  877. **
  878. ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
  879. **
  880. ** Also works on
  881. **
  882. ** CREATE INDEX
  883. ** CREATE UNIQUE INDEX
  884. ** CREATE VIEW
  885. ** CREATE TRIGGER
  886. ** CREATE VIRTUAL TABLE
  887. **
  888. ** This UDF is used by the .schema command to insert the schema name of
  889. ** attached databases into the middle of the sqlite_schema.sql field.
  890. */
  891. static void shellAddSchemaName(
  892. sqlite3_context *pCtx,
  893. int nVal,
  894. sqlite3_value **apVal
  895. ){
  896. static const char *aPrefix[] = {
  897. "TABLE",
  898. "INDEX",
  899. "UNIQUE INDEX",
  900. "VIEW",
  901. "TRIGGER",
  902. "VIRTUAL TABLE"
  903. };
  904. int i = 0;
  905. const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
  906. const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
  907. const char *zName = (const char*)sqlite3_value_text(apVal[2]);
  908. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  909. UNUSED_PARAMETER(nVal);
  910. if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
  911. for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
  912. int n = strlen30(aPrefix[i]);
  913. if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
  914. char *z = 0;
  915. char *zFake = 0;
  916. if( zSchema ){
  917. char cQuote = quoteChar(zSchema);
  918. if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
  919. z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
  920. }else{
  921. z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
  922. }
  923. }
  924. if( zName
  925. && aPrefix[i][0]=='V'
  926. && (zFake = shellFakeSchema(db, zSchema, zName))!=0
  927. ){
  928. if( z==0 ){
  929. z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
  930. }else{
  931. z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
  932. }
  933. free(zFake);
  934. }
  935. if( z ){
  936. sqlite3_result_text(pCtx, z, -1, sqlite3_free);
  937. return;
  938. }
  939. }
  940. }
  941. }
  942. sqlite3_result_value(pCtx, apVal[0]);
  943. }
  944. /*
  945. ** The source code for several run-time loadable extensions is inserted
  946. ** below by the ../tool/mkshellc.tcl script. Before processing that included
  947. ** code, we need to override some macros to make the included program code
  948. ** work here in the middle of this regular program.
  949. */
  950. #define SQLITE_EXTENSION_INIT1
  951. #define SQLITE_EXTENSION_INIT2(X) (void)(X)
  952. #if defined(_WIN32) && defined(_MSC_VER)
  953. /************************* Begin test_windirent.h ******************/
  954. /*
  955. ** 2015 November 30
  956. **
  957. ** The author disclaims copyright to this source code. In place of
  958. ** a legal notice, here is a blessing:
  959. **
  960. ** May you do good and not evil.
  961. ** May you find forgiveness for yourself and forgive others.
  962. ** May you share freely, never taking more than you give.
  963. **
  964. *************************************************************************
  965. ** This file contains declarations for most of the opendir() family of
  966. ** POSIX functions on Win32 using the MSVCRT.
  967. */
  968. #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
  969. #define SQLITE_WINDIRENT_H
  970. /*
  971. ** We need several data types from the Windows SDK header.
  972. */
  973. #ifndef WIN32_LEAN_AND_MEAN
  974. #define WIN32_LEAN_AND_MEAN
  975. #endif
  976. #include "windows.h"
  977. /*
  978. ** We need several support functions from the SQLite core.
  979. */
  980. /* #include "sqlite3.h" */
  981. /*
  982. ** We need several things from the ANSI and MSVCRT headers.
  983. */
  984. #include <stdio.h>
  985. #include <stdlib.h>
  986. #include <errno.h>
  987. #include <io.h>
  988. #include <limits.h>
  989. #include <sys/types.h>
  990. #include <sys/stat.h>
  991. /*
  992. ** We may need several defines that should have been in "sys/stat.h".
  993. */
  994. #ifndef S_ISREG
  995. #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
  996. #endif
  997. #ifndef S_ISDIR
  998. #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
  999. #endif
  1000. #ifndef S_ISLNK
  1001. #define S_ISLNK(mode) (0)
  1002. #endif
  1003. /*
  1004. ** We may need to provide the "mode_t" type.
  1005. */
  1006. #ifndef MODE_T_DEFINED
  1007. #define MODE_T_DEFINED
  1008. typedef unsigned short mode_t;
  1009. #endif
  1010. /*
  1011. ** We may need to provide the "ino_t" type.
  1012. */
  1013. #ifndef INO_T_DEFINED
  1014. #define INO_T_DEFINED
  1015. typedef unsigned short ino_t;
  1016. #endif
  1017. /*
  1018. ** We need to define "NAME_MAX" if it was not present in "limits.h".
  1019. */
  1020. #ifndef NAME_MAX
  1021. # ifdef FILENAME_MAX
  1022. # define NAME_MAX (FILENAME_MAX)
  1023. # else
  1024. # define NAME_MAX (260)
  1025. # endif
  1026. #endif
  1027. /*
  1028. ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
  1029. */
  1030. #ifndef NULL_INTPTR_T
  1031. # define NULL_INTPTR_T ((intptr_t)(0))
  1032. #endif
  1033. #ifndef BAD_INTPTR_T
  1034. # define BAD_INTPTR_T ((intptr_t)(-1))
  1035. #endif
  1036. /*
  1037. ** We need to provide the necessary structures and related types.
  1038. */
  1039. #ifndef DIRENT_DEFINED
  1040. #define DIRENT_DEFINED
  1041. typedef struct DIRENT DIRENT;
  1042. typedef DIRENT *LPDIRENT;
  1043. struct DIRENT {
  1044. ino_t d_ino; /* Sequence number, do not use. */
  1045. unsigned d_attributes; /* Win32 file attributes. */
  1046. char d_name[NAME_MAX + 1]; /* Name within the directory. */
  1047. };
  1048. #endif
  1049. #ifndef DIR_DEFINED
  1050. #define DIR_DEFINED
  1051. typedef struct DIR DIR;
  1052. typedef DIR *LPDIR;
  1053. struct DIR {
  1054. intptr_t d_handle; /* Value returned by "_findfirst". */
  1055. DIRENT d_first; /* DIRENT constructed based on "_findfirst". */
  1056. DIRENT d_next; /* DIRENT constructed based on "_findnext". */
  1057. };
  1058. #endif
  1059. /*
  1060. ** Provide a macro, for use by the implementation, to determine if a
  1061. ** particular directory entry should be skipped over when searching for
  1062. ** the next directory entry that should be returned by the readdir() or
  1063. ** readdir_r() functions.
  1064. */
  1065. #ifndef is_filtered
  1066. # define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
  1067. #endif
  1068. /*
  1069. ** Provide the function prototype for the POSIX compatiable getenv()
  1070. ** function. This function is not thread-safe.
  1071. */
  1072. extern const char *windirent_getenv(const char *name);
  1073. /*
  1074. ** Finally, we can provide the function prototypes for the opendir(),
  1075. ** readdir(), readdir_r(), and closedir() POSIX functions.
  1076. */
  1077. extern LPDIR opendir(const char *dirname);
  1078. extern LPDIRENT readdir(LPDIR dirp);
  1079. extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
  1080. extern INT closedir(LPDIR dirp);
  1081. #endif /* defined(WIN32) && defined(_MSC_VER) */
  1082. /************************* End test_windirent.h ********************/
  1083. /************************* Begin test_windirent.c ******************/
  1084. /*
  1085. ** 2015 November 30
  1086. **
  1087. ** The author disclaims copyright to this source code. In place of
  1088. ** a legal notice, here is a blessing:
  1089. **
  1090. ** May you do good and not evil.
  1091. ** May you find forgiveness for yourself and forgive others.
  1092. ** May you share freely, never taking more than you give.
  1093. **
  1094. *************************************************************************
  1095. ** This file contains code to implement most of the opendir() family of
  1096. ** POSIX functions on Win32 using the MSVCRT.
  1097. */
  1098. #if defined(_WIN32) && defined(_MSC_VER)
  1099. /* #include "test_windirent.h" */
  1100. /*
  1101. ** Implementation of the POSIX getenv() function using the Win32 API.
  1102. ** This function is not thread-safe.
  1103. */
  1104. const char *windirent_getenv(
  1105. const char *name
  1106. ){
  1107. static char value[32768]; /* Maximum length, per MSDN */
  1108. DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
  1109. DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
  1110. memset(value, 0, sizeof(value));
  1111. dwRet = GetEnvironmentVariableA(name, value, dwSize);
  1112. if( dwRet==0 || dwRet>dwSize ){
  1113. /*
  1114. ** The function call to GetEnvironmentVariableA() failed -OR-
  1115. ** the buffer is not large enough. Either way, return NULL.
  1116. */
  1117. return 0;
  1118. }else{
  1119. /*
  1120. ** The function call to GetEnvironmentVariableA() succeeded
  1121. ** -AND- the buffer contains the entire value.
  1122. */
  1123. return value;
  1124. }
  1125. }
  1126. /*
  1127. ** Implementation of the POSIX opendir() function using the MSVCRT.
  1128. */
  1129. LPDIR opendir(
  1130. const char *dirname
  1131. ){
  1132. struct _finddata_t data;
  1133. LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
  1134. SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
  1135. if( dirp==NULL ) return NULL;
  1136. memset(dirp, 0, sizeof(DIR));
  1137. /* TODO: Remove this if Unix-style root paths are not used. */
  1138. if( sqlite3_stricmp(dirname, "/")==0 ){
  1139. dirname = windirent_getenv("SystemDrive");
  1140. }
  1141. memset(&data, 0, sizeof(struct _finddata_t));
  1142. _snprintf(data.name, namesize, "%s\\*", dirname);
  1143. dirp->d_handle = _findfirst(data.name, &data);
  1144. if( dirp->d_handle==BAD_INTPTR_T ){
  1145. closedir(dirp);
  1146. return NULL;
  1147. }
  1148. /* TODO: Remove this block to allow hidden and/or system files. */
  1149. if( is_filtered(data) ){
  1150. next:
  1151. memset(&data, 0, sizeof(struct _finddata_t));
  1152. if( _findnext(dirp->d_handle, &data)==-1 ){
  1153. closedir(dirp);
  1154. return NULL;
  1155. }
  1156. /* TODO: Remove this block to allow hidden and/or system files. */
  1157. if( is_filtered(data) ) goto next;
  1158. }
  1159. dirp->d_first.d_attributes = data.attrib;
  1160. strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
  1161. dirp->d_first.d_name[NAME_MAX] = '\0';
  1162. return dirp;
  1163. }
  1164. /*
  1165. ** Implementation of the POSIX readdir() function using the MSVCRT.
  1166. */
  1167. LPDIRENT readdir(
  1168. LPDIR dirp
  1169. ){
  1170. struct _finddata_t data;
  1171. if( dirp==NULL ) return NULL;
  1172. if( dirp->d_first.d_ino==0 ){
  1173. dirp->d_first.d_ino++;
  1174. dirp->d_next.d_ino++;
  1175. return &dirp->d_first;
  1176. }
  1177. next:
  1178. memset(&data, 0, sizeof(struct _finddata_t));
  1179. if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
  1180. /* TODO: Remove this block to allow hidden and/or system files. */
  1181. if( is_filtered(data) ) goto next;
  1182. dirp->d_next.d_ino++;
  1183. dirp->d_next.d_attributes = data.attrib;
  1184. strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
  1185. dirp->d_next.d_name[NAME_MAX] = '\0';
  1186. return &dirp->d_next;
  1187. }
  1188. /*
  1189. ** Implementation of the POSIX readdir_r() function using the MSVCRT.
  1190. */
  1191. INT readdir_r(
  1192. LPDIR dirp,
  1193. LPDIRENT entry,
  1194. LPDIRENT *result
  1195. ){
  1196. struct _finddata_t data;
  1197. if( dirp==NULL ) return EBADF;
  1198. if( dirp->d_first.d_ino==0 ){
  1199. dirp->d_first.d_ino++;
  1200. dirp->d_next.d_ino++;
  1201. entry->d_ino = dirp->d_first.d_ino;
  1202. entry->d_attributes = dirp->d_first.d_attributes;
  1203. strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
  1204. entry->d_name[NAME_MAX] = '\0';
  1205. *result = entry;
  1206. return 0;
  1207. }
  1208. next:
  1209. memset(&data, 0, sizeof(struct _finddata_t));
  1210. if( _findnext(dirp->d_handle, &data)==-1 ){
  1211. *result = NULL;
  1212. return ENOENT;
  1213. }
  1214. /* TODO: Remove this block to allow hidden and/or system files. */
  1215. if( is_filtered(data) ) goto next;
  1216. entry->d_ino = (ino_t)-1; /* not available */
  1217. entry->d_attributes = data.attrib;
  1218. strncpy(entry->d_name, data.name, NAME_MAX);
  1219. entry->d_name[NAME_MAX] = '\0';
  1220. *result = entry;
  1221. return 0;
  1222. }
  1223. /*
  1224. ** Implementation of the POSIX closedir() function using the MSVCRT.
  1225. */
  1226. INT closedir(
  1227. LPDIR dirp
  1228. ){
  1229. INT result = 0;
  1230. if( dirp==NULL ) return EINVAL;
  1231. if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
  1232. result = _findclose(dirp->d_handle);
  1233. }
  1234. sqlite3_free(dirp);
  1235. return result;
  1236. }
  1237. #endif /* defined(WIN32) && defined(_MSC_VER) */
  1238. /************************* End test_windirent.c ********************/
  1239. #define dirent DIRENT
  1240. #endif
  1241. /************************* Begin ../ext/misc/shathree.c ******************/
  1242. /*
  1243. ** 2017-03-08
  1244. **
  1245. ** The author disclaims copyright to this source code. In place of
  1246. ** a legal notice, here is a blessing:
  1247. **
  1248. ** May you do good and not evil.
  1249. ** May you find forgiveness for yourself and forgive others.
  1250. ** May you share freely, never taking more than you give.
  1251. **
  1252. ******************************************************************************
  1253. **
  1254. ** This SQLite extension implements functions that compute SHA3 hashes.
  1255. ** Two SQL functions are implemented:
  1256. **
  1257. ** sha3(X,SIZE)
  1258. ** sha3_query(Y,SIZE)
  1259. **
  1260. ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
  1261. ** X is NULL.
  1262. **
  1263. ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
  1264. ** and returns a hash of their results.
  1265. **
  1266. ** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm
  1267. ** is used. If SIZE is included it must be one of the integers 224, 256,
  1268. ** 384, or 512, to determine SHA3 hash variant that is computed.
  1269. */
  1270. /* #include "sqlite3ext.h" */
  1271. SQLITE_EXTENSION_INIT1
  1272. #include <assert.h>
  1273. #include <string.h>
  1274. #include <stdarg.h>
  1275. /* typedef sqlite3_uint64 u64; */
  1276. /******************************************************************************
  1277. ** The Hash Engine
  1278. */
  1279. /*
  1280. ** Macros to determine whether the machine is big or little endian,
  1281. ** and whether or not that determination is run-time or compile-time.
  1282. **
  1283. ** For best performance, an attempt is made to guess at the byte-order
  1284. ** using C-preprocessor macros. If that is unsuccessful, or if
  1285. ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
  1286. ** at run-time.
  1287. */
  1288. #ifndef SHA3_BYTEORDER
  1289. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  1290. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  1291. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  1292. defined(__arm__)
  1293. # define SHA3_BYTEORDER 1234
  1294. # elif defined(sparc) || defined(__ppc__)
  1295. # define SHA3_BYTEORDER 4321
  1296. # else
  1297. # define SHA3_BYTEORDER 0
  1298. # endif
  1299. #endif
  1300. /*
  1301. ** State structure for a SHA3 hash in progress
  1302. */
  1303. typedef struct SHA3Context SHA3Context;
  1304. struct SHA3Context {
  1305. union {
  1306. u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
  1307. unsigned char x[1600]; /* ... or 1600 bytes */
  1308. } u;
  1309. unsigned nRate; /* Bytes of input accepted per Keccak iteration */
  1310. unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
  1311. unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
  1312. };
  1313. /*
  1314. ** A single step of the Keccak mixing function for a 1600-bit state
  1315. */
  1316. static void KeccakF1600Step(SHA3Context *p){
  1317. int i;
  1318. u64 b0, b1, b2, b3, b4;
  1319. u64 c0, c1, c2, c3, c4;
  1320. u64 d0, d1, d2, d3, d4;
  1321. static const u64 RC[] = {
  1322. 0x0000000000000001ULL, 0x0000000000008082ULL,
  1323. 0x800000000000808aULL, 0x8000000080008000ULL,
  1324. 0x000000000000808bULL, 0x0000000080000001ULL,
  1325. 0x8000000080008081ULL, 0x8000000000008009ULL,
  1326. 0x000000000000008aULL, 0x0000000000000088ULL,
  1327. 0x0000000080008009ULL, 0x000000008000000aULL,
  1328. 0x000000008000808bULL, 0x800000000000008bULL,
  1329. 0x8000000000008089ULL, 0x8000000000008003ULL,
  1330. 0x8000000000008002ULL, 0x8000000000000080ULL,
  1331. 0x000000000000800aULL, 0x800000008000000aULL,
  1332. 0x8000000080008081ULL, 0x8000000000008080ULL,
  1333. 0x0000000080000001ULL, 0x8000000080008008ULL
  1334. };
  1335. # define a00 (p->u.s[0])
  1336. # define a01 (p->u.s[1])
  1337. # define a02 (p->u.s[2])
  1338. # define a03 (p->u.s[3])
  1339. # define a04 (p->u.s[4])
  1340. # define a10 (p->u.s[5])
  1341. # define a11 (p->u.s[6])
  1342. # define a12 (p->u.s[7])
  1343. # define a13 (p->u.s[8])
  1344. # define a14 (p->u.s[9])
  1345. # define a20 (p->u.s[10])
  1346. # define a21 (p->u.s[11])
  1347. # define a22 (p->u.s[12])
  1348. # define a23 (p->u.s[13])
  1349. # define a24 (p->u.s[14])
  1350. # define a30 (p->u.s[15])
  1351. # define a31 (p->u.s[16])
  1352. # define a32 (p->u.s[17])
  1353. # define a33 (p->u.s[18])
  1354. # define a34 (p->u.s[19])
  1355. # define a40 (p->u.s[20])
  1356. # define a41 (p->u.s[21])
  1357. # define a42 (p->u.s[22])
  1358. # define a43 (p->u.s[23])
  1359. # define a44 (p->u.s[24])
  1360. # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
  1361. for(i=0; i<24; i+=4){
  1362. c0 = a00^a10^a20^a30^a40;
  1363. c1 = a01^a11^a21^a31^a41;
  1364. c2 = a02^a12^a22^a32^a42;
  1365. c3 = a03^a13^a23^a33^a43;
  1366. c4 = a04^a14^a24^a34^a44;
  1367. d0 = c4^ROL64(c1, 1);
  1368. d1 = c0^ROL64(c2, 1);
  1369. d2 = c1^ROL64(c3, 1);
  1370. d3 = c2^ROL64(c4, 1);
  1371. d4 = c3^ROL64(c0, 1);
  1372. b0 = (a00^d0);
  1373. b1 = ROL64((a11^d1), 44);
  1374. b2 = ROL64((a22^d2), 43);
  1375. b3 = ROL64((a33^d3), 21);
  1376. b4 = ROL64((a44^d4), 14);
  1377. a00 = b0 ^((~b1)& b2 );
  1378. a00 ^= RC[i];
  1379. a11 = b1 ^((~b2)& b3 );
  1380. a22 = b2 ^((~b3)& b4 );
  1381. a33 = b3 ^((~b4)& b0 );
  1382. a44 = b4 ^((~b0)& b1 );
  1383. b2 = ROL64((a20^d0), 3);
  1384. b3 = ROL64((a31^d1), 45);
  1385. b4 = ROL64((a42^d2), 61);
  1386. b0 = ROL64((a03^d3), 28);
  1387. b1 = ROL64((a14^d4), 20);
  1388. a20 = b0 ^((~b1)& b2 );
  1389. a31 = b1 ^((~b2)& b3 );
  1390. a42 = b2 ^((~b3)& b4 );
  1391. a03 = b3 ^((~b4)& b0 );
  1392. a14 = b4 ^((~b0)& b1 );
  1393. b4 = ROL64((a40^d0), 18);
  1394. b0 = ROL64((a01^d1), 1);
  1395. b1 = ROL64((a12^d2), 6);
  1396. b2 = ROL64((a23^d3), 25);
  1397. b3 = ROL64((a34^d4), 8);
  1398. a40 = b0 ^((~b1)& b2 );
  1399. a01 = b1 ^((~b2)& b3 );
  1400. a12 = b2 ^((~b3)& b4 );
  1401. a23 = b3 ^((~b4)& b0 );
  1402. a34 = b4 ^((~b0)& b1 );
  1403. b1 = ROL64((a10^d0), 36);
  1404. b2 = ROL64((a21^d1), 10);
  1405. b3 = ROL64((a32^d2), 15);
  1406. b4 = ROL64((a43^d3), 56);
  1407. b0 = ROL64((a04^d4), 27);
  1408. a10 = b0 ^((~b1)& b2 );
  1409. a21 = b1 ^((~b2)& b3 );
  1410. a32 = b2 ^((~b3)& b4 );
  1411. a43 = b3 ^((~b4)& b0 );
  1412. a04 = b4 ^((~b0)& b1 );
  1413. b3 = ROL64((a30^d0), 41);
  1414. b4 = ROL64((a41^d1), 2);
  1415. b0 = ROL64((a02^d2), 62);
  1416. b1 = ROL64((a13^d3), 55);
  1417. b2 = ROL64((a24^d4), 39);
  1418. a30 = b0 ^((~b1)& b2 );
  1419. a41 = b1 ^((~b2)& b3 );
  1420. a02 = b2 ^((~b3)& b4 );
  1421. a13 = b3 ^((~b4)& b0 );
  1422. a24 = b4 ^((~b0)& b1 );
  1423. c0 = a00^a20^a40^a10^a30;
  1424. c1 = a11^a31^a01^a21^a41;
  1425. c2 = a22^a42^a12^a32^a02;
  1426. c3 = a33^a03^a23^a43^a13;
  1427. c4 = a44^a14^a34^a04^a24;
  1428. d0 = c4^ROL64(c1, 1);
  1429. d1 = c0^ROL64(c2, 1);
  1430. d2 = c1^ROL64(c3, 1);
  1431. d3 = c2^ROL64(c4, 1);
  1432. d4 = c3^ROL64(c0, 1);
  1433. b0 = (a00^d0);
  1434. b1 = ROL64((a31^d1), 44);
  1435. b2 = ROL64((a12^d2), 43);
  1436. b3 = ROL64((a43^d3), 21);
  1437. b4 = ROL64((a24^d4), 14);
  1438. a00 = b0 ^((~b1)& b2 );
  1439. a00 ^= RC[i+1];
  1440. a31 = b1 ^((~b2)& b3 );
  1441. a12 = b2 ^((~b3)& b4 );
  1442. a43 = b3 ^((~b4)& b0 );
  1443. a24 = b4 ^((~b0)& b1 );
  1444. b2 = ROL64((a40^d0), 3);
  1445. b3 = ROL64((a21^d1), 45);
  1446. b4 = ROL64((a02^d2), 61);
  1447. b0 = ROL64((a33^d3), 28);
  1448. b1 = ROL64((a14^d4), 20);
  1449. a40 = b0 ^((~b1)& b2 );
  1450. a21 = b1 ^((~b2)& b3 );
  1451. a02 = b2 ^((~b3)& b4 );
  1452. a33 = b3 ^((~b4)& b0 );
  1453. a14 = b4 ^((~b0)& b1 );
  1454. b4 = ROL64((a30^d0), 18);
  1455. b0 = ROL64((a11^d1), 1);
  1456. b1 = ROL64((a42^d2), 6);
  1457. b2 = ROL64((a23^d3), 25);
  1458. b3 = ROL64((a04^d4), 8);
  1459. a30 = b0 ^((~b1)& b2 );
  1460. a11 = b1 ^((~b2)& b3 );
  1461. a42 = b2 ^((~b3)& b4 );
  1462. a23 = b3 ^((~b4)& b0 );
  1463. a04 = b4 ^((~b0)& b1 );
  1464. b1 = ROL64((a20^d0), 36);
  1465. b2 = ROL64((a01^d1), 10);
  1466. b3 = ROL64((a32^d2), 15);
  1467. b4 = ROL64((a13^d3), 56);
  1468. b0 = ROL64((a44^d4), 27);
  1469. a20 = b0 ^((~b1)& b2 );
  1470. a01 = b1 ^((~b2)& b3 );
  1471. a32 = b2 ^((~b3)& b4 );
  1472. a13 = b3 ^((~b4)& b0 );
  1473. a44 = b4 ^((~b0)& b1 );
  1474. b3 = ROL64((a10^d0), 41);
  1475. b4 = ROL64((a41^d1), 2);
  1476. b0 = ROL64((a22^d2), 62);
  1477. b1 = ROL64((a03^d3), 55);
  1478. b2 = ROL64((a34^d4), 39);
  1479. a10 = b0 ^((~b1)& b2 );
  1480. a41 = b1 ^((~b2)& b3 );
  1481. a22 = b2 ^((~b3)& b4 );
  1482. a03 = b3 ^((~b4)& b0 );
  1483. a34 = b4 ^((~b0)& b1 );
  1484. c0 = a00^a40^a30^a20^a10;
  1485. c1 = a31^a21^a11^a01^a41;
  1486. c2 = a12^a02^a42^a32^a22;
  1487. c3 = a43^a33^a23^a13^a03;
  1488. c4 = a24^a14^a04^a44^a34;
  1489. d0 = c4^ROL64(c1, 1);
  1490. d1 = c0^ROL64(c2, 1);
  1491. d2 = c1^ROL64(c3, 1);
  1492. d3 = c2^ROL64(c4, 1);
  1493. d4 = c3^ROL64(c0, 1);
  1494. b0 = (a00^d0);
  1495. b1 = ROL64((a21^d1), 44);
  1496. b2 = ROL64((a42^d2), 43);
  1497. b3 = ROL64((a13^d3), 21);
  1498. b4 = ROL64((a34^d4), 14);
  1499. a00 = b0 ^((~b1)& b2 );
  1500. a00 ^= RC[i+2];
  1501. a21 = b1 ^((~b2)& b3 );
  1502. a42 = b2 ^((~b3)& b4 );
  1503. a13 = b3 ^((~b4)& b0 );
  1504. a34 = b4 ^((~b0)& b1 );
  1505. b2 = ROL64((a30^d0), 3);
  1506. b3 = ROL64((a01^d1), 45);
  1507. b4 = ROL64((a22^d2), 61);
  1508. b0 = ROL64((a43^d3), 28);
  1509. b1 = ROL64((a14^d4), 20);
  1510. a30 = b0 ^((~b1)& b2 );
  1511. a01 = b1 ^((~b2)& b3 );
  1512. a22 = b2 ^((~b3)& b4 );
  1513. a43 = b3 ^((~b4)& b0 );
  1514. a14 = b4 ^((~b0)& b1 );
  1515. b4 = ROL64((a10^d0), 18);
  1516. b0 = ROL64((a31^d1), 1);
  1517. b1 = ROL64((a02^d2), 6);
  1518. b2 = ROL64((a23^d3), 25);
  1519. b3 = ROL64((a44^d4), 8);
  1520. a10 = b0 ^((~b1)& b2 );
  1521. a31 = b1 ^((~b2)& b3 );
  1522. a02 = b2 ^((~b3)& b4 );
  1523. a23 = b3 ^((~b4)& b0 );
  1524. a44 = b4 ^((~b0)& b1 );
  1525. b1 = ROL64((a40^d0), 36);
  1526. b2 = ROL64((a11^d1), 10);
  1527. b3 = ROL64((a32^d2), 15);
  1528. b4 = ROL64((a03^d3), 56);
  1529. b0 = ROL64((a24^d4), 27);
  1530. a40 = b0 ^((~b1)& b2 );
  1531. a11 = b1 ^((~b2)& b3 );
  1532. a32 = b2 ^((~b3)& b4 );
  1533. a03 = b3 ^((~b4)& b0 );
  1534. a24 = b4 ^((~b0)& b1 );
  1535. b3 = ROL64((a20^d0), 41);
  1536. b4 = ROL64((a41^d1), 2);
  1537. b0 = ROL64((a12^d2), 62);
  1538. b1 = ROL64((a33^d3), 55);
  1539. b2 = ROL64((a04^d4), 39);
  1540. a20 = b0 ^((~b1)& b2 );
  1541. a41 = b1 ^((~b2)& b3 );
  1542. a12 = b2 ^((~b3)& b4 );
  1543. a33 = b3 ^((~b4)& b0 );
  1544. a04 = b4 ^((~b0)& b1 );
  1545. c0 = a00^a30^a10^a40^a20;
  1546. c1 = a21^a01^a31^a11^a41;
  1547. c2 = a42^a22^a02^a32^a12;
  1548. c3 = a13^a43^a23^a03^a33;
  1549. c4 = a34^a14^a44^a24^a04;
  1550. d0 = c4^ROL64(c1, 1);
  1551. d1 = c0^ROL64(c2, 1);
  1552. d2 = c1^ROL64(c3, 1);
  1553. d3 = c2^ROL64(c4, 1);
  1554. d4 = c3^ROL64(c0, 1);
  1555. b0 = (a00^d0);
  1556. b1 = ROL64((a01^d1), 44);
  1557. b2 = ROL64((a02^d2), 43);
  1558. b3 = ROL64((a03^d3), 21);
  1559. b4 = ROL64((a04^d4), 14);
  1560. a00 = b0 ^((~b1)& b2 );
  1561. a00 ^= RC[i+3];
  1562. a01 = b1 ^((~b2)& b3 );
  1563. a02 = b2 ^((~b3)& b4 );
  1564. a03 = b3 ^((~b4)& b0 );
  1565. a04 = b4 ^((~b0)& b1 );
  1566. b2 = ROL64((a10^d0), 3);
  1567. b3 = ROL64((a11^d1), 45);
  1568. b4 = ROL64((a12^d2), 61);
  1569. b0 = ROL64((a13^d3), 28);
  1570. b1 = ROL64((a14^d4), 20);
  1571. a10 = b0 ^((~b1)& b2 );
  1572. a11 = b1 ^((~b2)& b3 );
  1573. a12 = b2 ^((~b3)& b4 );
  1574. a13 = b3 ^((~b4)& b0 );
  1575. a14 = b4 ^((~b0)& b1 );
  1576. b4 = ROL64((a20^d0), 18);
  1577. b0 = ROL64((a21^d1), 1);
  1578. b1 = ROL64((a22^d2), 6);
  1579. b2 = ROL64((a23^d3), 25);
  1580. b3 = ROL64((a24^d4), 8);
  1581. a20 = b0 ^((~b1)& b2 );
  1582. a21 = b1 ^((~b2)& b3 );
  1583. a22 = b2 ^((~b3)& b4 );
  1584. a23 = b3 ^((~b4)& b0 );
  1585. a24 = b4 ^((~b0)& b1 );
  1586. b1 = ROL64((a30^d0), 36);
  1587. b2 = ROL64((a31^d1), 10);
  1588. b3 = ROL64((a32^d2), 15);
  1589. b4 = ROL64((a33^d3), 56);
  1590. b0 = ROL64((a34^d4), 27);
  1591. a30 = b0 ^((~b1)& b2 );
  1592. a31 = b1 ^((~b2)& b3 );
  1593. a32 = b2 ^((~b3)& b4 );
  1594. a33 = b3 ^((~b4)& b0 );
  1595. a34 = b4 ^((~b0)& b1 );
  1596. b3 = ROL64((a40^d0), 41);
  1597. b4 = ROL64((a41^d1), 2);
  1598. b0 = ROL64((a42^d2), 62);
  1599. b1 = ROL64((a43^d3), 55);
  1600. b2 = ROL64((a44^d4), 39);
  1601. a40 = b0 ^((~b1)& b2 );
  1602. a41 = b1 ^((~b2)& b3 );
  1603. a42 = b2 ^((~b3)& b4 );
  1604. a43 = b3 ^((~b4)& b0 );
  1605. a44 = b4 ^((~b0)& b1 );
  1606. }
  1607. }
  1608. /*
  1609. ** Initialize a new hash. iSize determines the size of the hash
  1610. ** in bits and should be one of 224, 256, 384, or 512. Or iSize
  1611. ** can be zero to use the default hash size of 256 bits.
  1612. */
  1613. static void SHA3Init(SHA3Context *p, int iSize){
  1614. memset(p, 0, sizeof(*p));
  1615. if( iSize>=128 && iSize<=512 ){
  1616. p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
  1617. }else{
  1618. p->nRate = (1600 - 2*256)/8;
  1619. }
  1620. #if SHA3_BYTEORDER==1234
  1621. /* Known to be little-endian at compile-time. No-op */
  1622. #elif SHA3_BYTEORDER==4321
  1623. p->ixMask = 7; /* Big-endian */
  1624. #else
  1625. {
  1626. static unsigned int one = 1;
  1627. if( 1==*(unsigned char*)&one ){
  1628. /* Little endian. No byte swapping. */
  1629. p->ixMask = 0;
  1630. }else{
  1631. /* Big endian. Byte swap. */
  1632. p->ixMask = 7;
  1633. }
  1634. }
  1635. #endif
  1636. }
  1637. /*
  1638. ** Make consecutive calls to the SHA3Update function to add new content
  1639. ** to the hash
  1640. */
  1641. static void SHA3Update(
  1642. SHA3Context *p,
  1643. const unsigned char *aData,
  1644. unsigned int nData
  1645. ){
  1646. unsigned int i = 0;
  1647. #if SHA3_BYTEORDER==1234
  1648. if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
  1649. for(; i+7<nData; i+=8){
  1650. p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
  1651. p->nLoaded += 8;
  1652. if( p->nLoaded>=p->nRate ){
  1653. KeccakF1600Step(p);
  1654. p->nLoaded = 0;
  1655. }
  1656. }
  1657. }
  1658. #endif
  1659. for(; i<nData; i++){
  1660. #if SHA3_BYTEORDER==1234
  1661. p->u.x[p->nLoaded] ^= aData[i];
  1662. #elif SHA3_BYTEORDER==4321
  1663. p->u.x[p->nLoaded^0x07] ^= aData[i];
  1664. #else
  1665. p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
  1666. #endif
  1667. p->nLoaded++;
  1668. if( p->nLoaded==p->nRate ){
  1669. KeccakF1600Step(p);
  1670. p->nLoaded = 0;
  1671. }
  1672. }
  1673. }
  1674. /*
  1675. ** After all content has been added, invoke SHA3Final() to compute
  1676. ** the final hash. The function returns a pointer to the binary
  1677. ** hash value.
  1678. */
  1679. static unsigned char *SHA3Final(SHA3Context *p){
  1680. unsigned int i;
  1681. if( p->nLoaded==p->nRate-1 ){
  1682. const unsigned char c1 = 0x86;
  1683. SHA3Update(p, &c1, 1);
  1684. }else{
  1685. const unsigned char c2 = 0x06;
  1686. const unsigned char c3 = 0x80;
  1687. SHA3Update(p, &c2, 1);
  1688. p->nLoaded = p->nRate - 1;
  1689. SHA3Update(p, &c3, 1);
  1690. }
  1691. for(i=0; i<p->nRate; i++){
  1692. p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
  1693. }
  1694. return &p->u.x[p->nRate];
  1695. }
  1696. /* End of the hashing logic
  1697. *****************************************************************************/
  1698. /*
  1699. ** Implementation of the sha3(X,SIZE) function.
  1700. **
  1701. ** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
  1702. ** size is 256. If X is a BLOB, it is hashed as is.
  1703. ** For all other non-NULL types of input, X is converted into a UTF-8 string
  1704. ** and the string is hashed without the trailing 0x00 terminator. The hash
  1705. ** of a NULL value is NULL.
  1706. */
  1707. static void sha3Func(
  1708. sqlite3_context *context,
  1709. int argc,
  1710. sqlite3_value **argv
  1711. ){
  1712. SHA3Context cx;
  1713. int eType = sqlite3_value_type(argv[0]);
  1714. int nByte = sqlite3_value_bytes(argv[0]);
  1715. int iSize;
  1716. if( argc==1 ){
  1717. iSize = 256;
  1718. }else{
  1719. iSize = sqlite3_value_int(argv[1]);
  1720. if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
  1721. sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
  1722. "384 512", -1);
  1723. return;
  1724. }
  1725. }
  1726. if( eType==SQLITE_NULL ) return;
  1727. SHA3Init(&cx, iSize);
  1728. if( eType==SQLITE_BLOB ){
  1729. SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
  1730. }else{
  1731. SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
  1732. }
  1733. sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
  1734. }
  1735. /* Compute a string using sqlite3_vsnprintf() with a maximum length
  1736. ** of 50 bytes and add it to the hash.
  1737. */
  1738. static void hash_step_vformat(
  1739. SHA3Context *p, /* Add content to this context */
  1740. const char *zFormat,
  1741. ...
  1742. ){
  1743. va_list ap;
  1744. int n;
  1745. char zBuf[50];
  1746. va_start(ap, zFormat);
  1747. sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
  1748. va_end(ap);
  1749. n = (int)strlen(zBuf);
  1750. SHA3Update(p, (unsigned char*)zBuf, n);
  1751. }
  1752. /*
  1753. ** Implementation of the sha3_query(SQL,SIZE) function.
  1754. **
  1755. ** This function compiles and runs the SQL statement(s) given in the
  1756. ** argument. The results are hashed using a SIZE-bit SHA3. The default
  1757. ** size is 256.
  1758. **
  1759. ** The format of the byte stream that is hashed is summarized as follows:
  1760. **
  1761. ** S<n>:<sql>
  1762. ** R
  1763. ** N
  1764. ** I<int>
  1765. ** F<ieee-float>
  1766. ** B<size>:<bytes>
  1767. ** T<size>:<text>
  1768. **
  1769. ** <sql> is the original SQL text for each statement run and <n> is
  1770. ** the size of that text. The SQL text is UTF-8. A single R character
  1771. ** occurs before the start of each row. N means a NULL value.
  1772. ** I mean an 8-byte little-endian integer <int>. F is a floating point
  1773. ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
  1774. ** B means blobs of <size> bytes. T means text rendered as <size>
  1775. ** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
  1776. ** text integers.
  1777. **
  1778. ** For each SQL statement in the X input, there is one S segment. Each
  1779. ** S segment is followed by zero or more R segments, one for each row in the
  1780. ** result set. After each R, there are one or more N, I, F, B, or T segments,
  1781. ** one for each column in the result set. Segments are concatentated directly
  1782. ** with no delimiters of any kind.
  1783. */
  1784. static void sha3QueryFunc(
  1785. sqlite3_context *context,
  1786. int argc,
  1787. sqlite3_value **argv
  1788. ){
  1789. sqlite3 *db = sqlite3_context_db_handle(context);
  1790. const char *zSql = (const char*)sqlite3_value_text(argv[0]);
  1791. sqlite3_stmt *pStmt = 0;
  1792. int nCol; /* Number of columns in the result set */
  1793. int i; /* Loop counter */
  1794. int rc;
  1795. int n;
  1796. const char *z;
  1797. SHA3Context cx;
  1798. int iSize;
  1799. if( argc==1 ){
  1800. iSize = 256;
  1801. }else{
  1802. iSize = sqlite3_value_int(argv[1]);
  1803. if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
  1804. sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
  1805. "384 512", -1);
  1806. return;
  1807. }
  1808. }
  1809. if( zSql==0 ) return;
  1810. SHA3Init(&cx, iSize);
  1811. while( zSql[0] ){
  1812. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
  1813. if( rc ){
  1814. char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
  1815. zSql, sqlite3_errmsg(db));
  1816. sqlite3_finalize(pStmt);
  1817. sqlite3_result_error(context, zMsg, -1);
  1818. sqlite3_free(zMsg);
  1819. return;
  1820. }
  1821. if( !sqlite3_stmt_readonly(pStmt) ){
  1822. char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
  1823. sqlite3_finalize(pStmt);
  1824. sqlite3_result_error(context, zMsg, -1);
  1825. sqlite3_free(zMsg);
  1826. return;
  1827. }
  1828. nCol = sqlite3_column_count(pStmt);
  1829. z = sqlite3_sql(pStmt);
  1830. n = (int)strlen(z);
  1831. hash_step_vformat(&cx,"S%d:",n);
  1832. SHA3Update(&cx,(unsigned char*)z,n);
  1833. /* Compute a hash over the result of the query */
  1834. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  1835. SHA3Update(&cx,(const unsigned char*)"R",1);
  1836. for(i=0; i<nCol; i++){
  1837. switch( sqlite3_column_type(pStmt,i) ){
  1838. case SQLITE_NULL: {
  1839. SHA3Update(&cx, (const unsigned char*)"N",1);
  1840. break;
  1841. }
  1842. case SQLITE_INTEGER: {
  1843. sqlite3_uint64 u;
  1844. int j;
  1845. unsigned char x[9];
  1846. sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
  1847. memcpy(&u, &v, 8);
  1848. for(j=8; j>=1; j--){
  1849. x[j] = u & 0xff;
  1850. u >>= 8;
  1851. }
  1852. x[0] = 'I';
  1853. SHA3Update(&cx, x, 9);
  1854. break;
  1855. }
  1856. case SQLITE_FLOAT: {
  1857. sqlite3_uint64 u;
  1858. int j;
  1859. unsigned char x[9];
  1860. double r = sqlite3_column_double(pStmt,i);
  1861. memcpy(&u, &r, 8);
  1862. for(j=8; j>=1; j--){
  1863. x[j] = u & 0xff;
  1864. u >>= 8;
  1865. }
  1866. x[0] = 'F';
  1867. SHA3Update(&cx,x,9);
  1868. break;
  1869. }
  1870. case SQLITE_TEXT: {
  1871. int n2 = sqlite3_column_bytes(pStmt, i);
  1872. const unsigned char *z2 = sqlite3_column_text(pStmt, i);
  1873. hash_step_vformat(&cx,"T%d:",n2);
  1874. SHA3Update(&cx, z2, n2);
  1875. break;
  1876. }
  1877. case SQLITE_BLOB: {
  1878. int n2 = sqlite3_column_bytes(pStmt, i);
  1879. const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
  1880. hash_step_vformat(&cx,"B%d:",n2);
  1881. SHA3Update(&cx, z2, n2);
  1882. break;
  1883. }
  1884. }
  1885. }
  1886. }
  1887. sqlite3_finalize(pStmt);
  1888. }
  1889. sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
  1890. }
  1891. #ifdef _WIN32
  1892. #endif
  1893. int sqlite3_shathree_init(
  1894. sqlite3 *db,
  1895. char **pzErrMsg,
  1896. const sqlite3_api_routines *pApi
  1897. ){
  1898. int rc = SQLITE_OK;
  1899. SQLITE_EXTENSION_INIT2(pApi);
  1900. (void)pzErrMsg; /* Unused parameter */
  1901. rc = sqlite3_create_function(db, "sha3", 1,
  1902. SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
  1903. 0, sha3Func, 0, 0);
  1904. if( rc==SQLITE_OK ){
  1905. rc = sqlite3_create_function(db, "sha3", 2,
  1906. SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
  1907. 0, sha3Func, 0, 0);
  1908. }
  1909. if( rc==SQLITE_OK ){
  1910. rc = sqlite3_create_function(db, "sha3_query", 1,
  1911. SQLITE_UTF8 | SQLITE_DIRECTONLY,
  1912. 0, sha3QueryFunc, 0, 0);
  1913. }
  1914. if( rc==SQLITE_OK ){
  1915. rc = sqlite3_create_function(db, "sha3_query", 2,
  1916. SQLITE_UTF8 | SQLITE_DIRECTONLY,
  1917. 0, sha3QueryFunc, 0, 0);
  1918. }
  1919. return rc;
  1920. }
  1921. /************************* End ../ext/misc/shathree.c ********************/
  1922. /************************* Begin ../ext/misc/fileio.c ******************/
  1923. /*
  1924. ** 2014-06-13
  1925. **
  1926. ** The author disclaims copyright to this source code. In place of
  1927. ** a legal notice, here is a blessing:
  1928. **
  1929. ** May you do good and not evil.
  1930. ** May you find forgiveness for yourself and forgive others.
  1931. ** May you share freely, never taking more than you give.
  1932. **
  1933. ******************************************************************************
  1934. **
  1935. ** This SQLite extension implements SQL functions readfile() and
  1936. ** writefile(), and eponymous virtual type "fsdir".
  1937. **
  1938. ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
  1939. **
  1940. ** If neither of the optional arguments is present, then this UDF
  1941. ** function writes blob DATA to file FILE. If successful, the number
  1942. ** of bytes written is returned. If an error occurs, NULL is returned.
  1943. **
  1944. ** If the first option argument - MODE - is present, then it must
  1945. ** be passed an integer value that corresponds to a POSIX mode
  1946. ** value (file type + permissions, as returned in the stat.st_mode
  1947. ** field by the stat() system call). Three types of files may
  1948. ** be written/created:
  1949. **
  1950. ** regular files: (mode & 0170000)==0100000
  1951. ** symbolic links: (mode & 0170000)==0120000
  1952. ** directories: (mode & 0170000)==0040000
  1953. **
  1954. ** For a directory, the DATA is ignored. For a symbolic link, it is
  1955. ** interpreted as text and used as the target of the link. For a
  1956. ** regular file, it is interpreted as a blob and written into the
  1957. ** named file. Regardless of the type of file, its permissions are
  1958. ** set to (mode & 0777) before returning.
  1959. **
  1960. ** If the optional MTIME argument is present, then it is interpreted
  1961. ** as an integer - the number of seconds since the unix epoch. The
  1962. ** modification-time of the target file is set to this value before
  1963. ** returning.
  1964. **
  1965. ** If three or more arguments are passed to this function and an
  1966. ** error is encountered, an exception is raised.
  1967. **
  1968. ** READFILE(FILE):
  1969. **
  1970. ** Read and return the contents of file FILE (type blob) from disk.
  1971. **
  1972. ** FSDIR:
  1973. **
  1974. ** Used as follows:
  1975. **
  1976. ** SELECT * FROM fsdir($path [, $dir]);
  1977. **
  1978. ** Parameter $path is an absolute or relative pathname. If the file that it
  1979. ** refers to does not exist, it is an error. If the path refers to a regular
  1980. ** file or symbolic link, it returns a single row. Or, if the path refers
  1981. ** to a directory, it returns one row for the directory, and one row for each
  1982. ** file within the hierarchy rooted at $path.
  1983. **
  1984. ** Each row has the following columns:
  1985. **
  1986. ** name: Path to file or directory (text value).
  1987. ** mode: Value of stat.st_mode for directory entry (an integer).
  1988. ** mtime: Value of stat.st_mtime for directory entry (an integer).
  1989. ** data: For a regular file, a blob containing the file data. For a
  1990. ** symlink, a text value containing the text of the link. For a
  1991. ** directory, NULL.
  1992. **
  1993. ** If a non-NULL value is specified for the optional $dir parameter and
  1994. ** $path is a relative path, then $path is interpreted relative to $dir.
  1995. ** And the paths returned in the "name" column of the table are also
  1996. ** relative to directory $dir.
  1997. */
  1998. /* #include "sqlite3ext.h" */
  1999. SQLITE_EXTENSION_INIT1
  2000. #include <stdio.h>
  2001. #include <string.h>
  2002. #include <assert.h>
  2003. #include <sys/types.h>
  2004. #include <sys/stat.h>
  2005. #include <fcntl.h>
  2006. #if !defined(_WIN32) && !defined(WIN32)
  2007. # include <unistd.h>
  2008. # include <dirent.h>
  2009. # include <utime.h>
  2010. # include <sys/time.h>
  2011. #else
  2012. # include "windows.h"
  2013. # include <io.h>
  2014. # include <direct.h>
  2015. /* # include "test_windirent.h" */
  2016. # define dirent DIRENT
  2017. # ifndef chmod
  2018. # define chmod _chmod
  2019. # endif
  2020. # ifndef stat
  2021. # define stat _stat
  2022. # endif
  2023. # define mkdir(path,mode) _mkdir(path)
  2024. # define lstat(path,buf) stat(path,buf)
  2025. #endif
  2026. #include <time.h>
  2027. #include <errno.h>
  2028. /*
  2029. ** Structure of the fsdir() table-valued function
  2030. */
  2031. /* 0 1 2 3 4 5 */
  2032. #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
  2033. #define FSDIR_COLUMN_NAME 0 /* Name of the file */
  2034. #define FSDIR_COLUMN_MODE 1 /* Access mode */
  2035. #define FSDIR_COLUMN_MTIME 2 /* Last modification time */
  2036. #define FSDIR_COLUMN_DATA 3 /* File content */
  2037. #define FSDIR_COLUMN_PATH 4 /* Path to top of search */
  2038. #define FSDIR_COLUMN_DIR 5 /* Path is relative to this directory */
  2039. /*
  2040. ** Set the result stored by context ctx to a blob containing the
  2041. ** contents of file zName. Or, leave the result unchanged (NULL)
  2042. ** if the file does not exist or is unreadable.
  2043. **
  2044. ** If the file exceeds the SQLite blob size limit, through an
  2045. ** SQLITE_TOOBIG error.
  2046. **
  2047. ** Throw an SQLITE_IOERR if there are difficulties pulling the file
  2048. ** off of disk.
  2049. */
  2050. static void readFileContents(sqlite3_context *ctx, const char *zName){
  2051. FILE *in;
  2052. sqlite3_int64 nIn;
  2053. void *pBuf;
  2054. sqlite3 *db;
  2055. int mxBlob;
  2056. in = fopen(zName, "rb");
  2057. if( in==0 ){
  2058. /* File does not exist or is unreadable. Leave the result set to NULL. */
  2059. return;
  2060. }
  2061. fseek(in, 0, SEEK_END);
  2062. nIn = ftell(in);
  2063. rewind(in);
  2064. db = sqlite3_context_db_handle(ctx);
  2065. mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
  2066. if( nIn>mxBlob ){
  2067. sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
  2068. fclose(in);
  2069. return;
  2070. }
  2071. pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
  2072. if( pBuf==0 ){
  2073. sqlite3_result_error_nomem(ctx);
  2074. fclose(in);
  2075. return;
  2076. }
  2077. if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
  2078. sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
  2079. }else{
  2080. sqlite3_result_error_code(ctx, SQLITE_IOERR);
  2081. sqlite3_free(pBuf);
  2082. }
  2083. fclose(in);
  2084. }
  2085. /*
  2086. ** Implementation of the "readfile(X)" SQL function. The entire content
  2087. ** of the file named X is read and returned as a BLOB. NULL is returned
  2088. ** if the file does not exist or is unreadable.
  2089. */
  2090. static void readfileFunc(
  2091. sqlite3_context *context,
  2092. int argc,
  2093. sqlite3_value **argv
  2094. ){
  2095. const char *zName;
  2096. (void)(argc); /* Unused parameter */
  2097. zName = (const char*)sqlite3_value_text(argv[0]);
  2098. if( zName==0 ) return;
  2099. readFileContents(context, zName);
  2100. }
  2101. /*
  2102. ** Set the error message contained in context ctx to the results of
  2103. ** vprintf(zFmt, ...).
  2104. */
  2105. static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
  2106. char *zMsg = 0;
  2107. va_list ap;
  2108. va_start(ap, zFmt);
  2109. zMsg = sqlite3_vmprintf(zFmt, ap);
  2110. sqlite3_result_error(ctx, zMsg, -1);
  2111. sqlite3_free(zMsg);
  2112. va_end(ap);
  2113. }
  2114. #if defined(_WIN32)
  2115. /*
  2116. ** This function is designed to convert a Win32 FILETIME structure into the
  2117. ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
  2118. */
  2119. static sqlite3_uint64 fileTimeToUnixTime(
  2120. LPFILETIME pFileTime
  2121. ){
  2122. SYSTEMTIME epochSystemTime;
  2123. ULARGE_INTEGER epochIntervals;
  2124. FILETIME epochFileTime;
  2125. ULARGE_INTEGER fileIntervals;
  2126. memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
  2127. epochSystemTime.wYear = 1970;
  2128. epochSystemTime.wMonth = 1;
  2129. epochSystemTime.wDay = 1;
  2130. SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
  2131. epochIntervals.LowPart = epochFileTime.dwLowDateTime;
  2132. epochIntervals.HighPart = epochFileTime.dwHighDateTime;
  2133. fileIntervals.LowPart = pFileTime->dwLowDateTime;
  2134. fileIntervals.HighPart = pFileTime->dwHighDateTime;
  2135. return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
  2136. }
  2137. /*
  2138. ** This function attempts to normalize the time values found in the stat()
  2139. ** buffer to UTC. This is necessary on Win32, where the runtime library
  2140. ** appears to return these values as local times.
  2141. */
  2142. static void statTimesToUtc(
  2143. const char *zPath,
  2144. struct stat *pStatBuf
  2145. ){
  2146. HANDLE hFindFile;
  2147. WIN32_FIND_DATAW fd;
  2148. LPWSTR zUnicodeName;
  2149. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
  2150. zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
  2151. if( zUnicodeName ){
  2152. memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
  2153. hFindFile = FindFirstFileW(zUnicodeName, &fd);
  2154. if( hFindFile!=NULL ){
  2155. pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
  2156. pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
  2157. pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
  2158. FindClose(hFindFile);
  2159. }
  2160. sqlite3_free(zUnicodeName);
  2161. }
  2162. }
  2163. #endif
  2164. /*
  2165. ** This function is used in place of stat(). On Windows, special handling
  2166. ** is required in order for the included time to be returned as UTC. On all
  2167. ** other systems, this function simply calls stat().
  2168. */
  2169. static int fileStat(
  2170. const char *zPath,
  2171. struct stat *pStatBuf
  2172. ){
  2173. #if defined(_WIN32)
  2174. int rc = stat(zPath, pStatBuf);
  2175. if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
  2176. return rc;
  2177. #else
  2178. return stat(zPath, pStatBuf);
  2179. #endif
  2180. }
  2181. /*
  2182. ** This function is used in place of lstat(). On Windows, special handling
  2183. ** is required in order for the included time to be returned as UTC. On all
  2184. ** other systems, this function simply calls lstat().
  2185. */
  2186. static int fileLinkStat(
  2187. const char *zPath,
  2188. struct stat *pStatBuf
  2189. ){
  2190. #if defined(_WIN32)
  2191. int rc = lstat(zPath, pStatBuf);
  2192. if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
  2193. return rc;
  2194. #else
  2195. return lstat(zPath, pStatBuf);
  2196. #endif
  2197. }
  2198. /*
  2199. ** Argument zFile is the name of a file that will be created and/or written
  2200. ** by SQL function writefile(). This function ensures that the directory
  2201. ** zFile will be written to exists, creating it if required. The permissions
  2202. ** for any path components created by this function are set in accordance
  2203. ** with the current umask.
  2204. **
  2205. ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
  2206. ** SQLITE_OK is returned if the directory is successfully created, or
  2207. ** SQLITE_ERROR otherwise.
  2208. */
  2209. static int makeDirectory(
  2210. const char *zFile
  2211. ){
  2212. char *zCopy = sqlite3_mprintf("%s", zFile);
  2213. int rc = SQLITE_OK;
  2214. if( zCopy==0 ){
  2215. rc = SQLITE_NOMEM;
  2216. }else{
  2217. int nCopy = (int)strlen(zCopy);
  2218. int i = 1;
  2219. while( rc==SQLITE_OK ){
  2220. struct stat sStat;
  2221. int rc2;
  2222. for(; zCopy[i]!='/' && i<nCopy; i++);
  2223. if( i==nCopy ) break;
  2224. zCopy[i] = '\0';
  2225. rc2 = fileStat(zCopy, &sStat);
  2226. if( rc2!=0 ){
  2227. if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
  2228. }else{
  2229. if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
  2230. }
  2231. zCopy[i] = '/';
  2232. i++;
  2233. }
  2234. sqlite3_free(zCopy);
  2235. }
  2236. return rc;
  2237. }
  2238. /*
  2239. ** This function does the work for the writefile() UDF. Refer to
  2240. ** header comments at the top of this file for details.
  2241. */
  2242. static int writeFile(
  2243. sqlite3_context *pCtx, /* Context to return bytes written in */
  2244. const char *zFile, /* File to write */
  2245. sqlite3_value *pData, /* Data to write */
  2246. mode_t mode, /* MODE parameter passed to writefile() */
  2247. sqlite3_int64 mtime /* MTIME parameter (or -1 to not set time) */
  2248. ){
  2249. #if !defined(_WIN32) && !defined(WIN32)
  2250. if( S_ISLNK(mode) ){
  2251. const char *zTo = (const char*)sqlite3_value_text(pData);
  2252. if( symlink(zTo, zFile)<0 ) return 1;
  2253. }else
  2254. #endif
  2255. {
  2256. if( S_ISDIR(mode) ){
  2257. if( mkdir(zFile, mode) ){
  2258. /* The mkdir() call to create the directory failed. This might not
  2259. ** be an error though - if there is already a directory at the same
  2260. ** path and either the permissions already match or can be changed
  2261. ** to do so using chmod(), it is not an error. */
  2262. struct stat sStat;
  2263. if( errno!=EEXIST
  2264. || 0!=fileStat(zFile, &sStat)
  2265. || !S_ISDIR(sStat.st_mode)
  2266. || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
  2267. ){
  2268. return 1;
  2269. }
  2270. }
  2271. }else{
  2272. sqlite3_int64 nWrite = 0;
  2273. const char *z;
  2274. int rc = 0;
  2275. FILE *out = fopen(zFile, "wb");
  2276. if( out==0 ) return 1;
  2277. z = (const char*)sqlite3_value_blob(pData);
  2278. if( z ){
  2279. sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
  2280. nWrite = sqlite3_value_bytes(pData);
  2281. if( nWrite!=n ){
  2282. rc = 1;
  2283. }
  2284. }
  2285. fclose(out);
  2286. if( rc==0 && mode && chmod(zFile, mode & 0777) ){
  2287. rc = 1;
  2288. }
  2289. if( rc ) return 2;
  2290. sqlite3_result_int64(pCtx, nWrite);
  2291. }
  2292. }
  2293. if( mtime>=0 ){
  2294. #if defined(_WIN32)
  2295. #if !SQLITE_OS_WINRT
  2296. /* Windows */
  2297. FILETIME lastAccess;
  2298. FILETIME lastWrite;
  2299. SYSTEMTIME currentTime;
  2300. LONGLONG intervals;
  2301. HANDLE hFile;
  2302. LPWSTR zUnicodeName;
  2303. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
  2304. GetSystemTime(&currentTime);
  2305. SystemTimeToFileTime(&currentTime, &lastAccess);
  2306. intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
  2307. lastWrite.dwLowDateTime = (DWORD)intervals;
  2308. lastWrite.dwHighDateTime = intervals >> 32;
  2309. zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
  2310. if( zUnicodeName==0 ){
  2311. return 1;
  2312. }
  2313. hFile = CreateFileW(
  2314. zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
  2315. FILE_FLAG_BACKUP_SEMANTICS, NULL
  2316. );
  2317. sqlite3_free(zUnicodeName);
  2318. if( hFile!=INVALID_HANDLE_VALUE ){
  2319. BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
  2320. CloseHandle(hFile);
  2321. return !bResult;
  2322. }else{
  2323. return 1;
  2324. }
  2325. #endif
  2326. #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
  2327. /* Recent unix */
  2328. struct timespec times[2];
  2329. times[0].tv_nsec = times[1].tv_nsec = 0;
  2330. times[0].tv_sec = time(0);
  2331. times[1].tv_sec = mtime;
  2332. if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
  2333. return 1;
  2334. }
  2335. #else
  2336. /* Legacy unix */
  2337. struct timeval times[2];
  2338. times[0].tv_usec = times[1].tv_usec = 0;
  2339. times[0].tv_sec = time(0);
  2340. times[1].tv_sec = mtime;
  2341. if( utimes(zFile, times) ){
  2342. return 1;
  2343. }
  2344. #endif
  2345. }
  2346. return 0;
  2347. }
  2348. /*
  2349. ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
  2350. ** Refer to header comments at the top of this file for details.
  2351. */
  2352. static void writefileFunc(
  2353. sqlite3_context *context,
  2354. int argc,
  2355. sqlite3_value **argv
  2356. ){
  2357. const char *zFile;
  2358. mode_t mode = 0;
  2359. int res;
  2360. sqlite3_int64 mtime = -1;
  2361. if( argc<2 || argc>4 ){
  2362. sqlite3_result_error(context,
  2363. "wrong number of arguments to function writefile()", -1
  2364. );
  2365. return;
  2366. }
  2367. zFile = (const char*)sqlite3_value_text(argv[0]);
  2368. if( zFile==0 ) return;
  2369. if( argc>=3 ){
  2370. mode = (mode_t)sqlite3_value_int(argv[2]);
  2371. }
  2372. if( argc==4 ){
  2373. mtime = sqlite3_value_int64(argv[3]);
  2374. }
  2375. res = writeFile(context, zFile, argv[1], mode, mtime);
  2376. if( res==1 && errno==ENOENT ){
  2377. if( makeDirectory(zFile)==SQLITE_OK ){
  2378. res = writeFile(context, zFile, argv[1], mode, mtime);
  2379. }
  2380. }
  2381. if( argc>2 && res!=0 ){
  2382. if( S_ISLNK(mode) ){
  2383. ctxErrorMsg(context, "failed to create symlink: %s", zFile);
  2384. }else if( S_ISDIR(mode) ){
  2385. ctxErrorMsg(context, "failed to create directory: %s", zFile);
  2386. }else{
  2387. ctxErrorMsg(context, "failed to write file: %s", zFile);
  2388. }
  2389. }
  2390. }
  2391. /*
  2392. ** SQL function: lsmode(MODE)
  2393. **
  2394. ** Given a numberic st_mode from stat(), convert it into a human-readable
  2395. ** text string in the style of "ls -l".
  2396. */
  2397. static void lsModeFunc(
  2398. sqlite3_context *context,
  2399. int argc,
  2400. sqlite3_value **argv
  2401. ){
  2402. int i;
  2403. int iMode = sqlite3_value_int(argv[0]);
  2404. char z[16];
  2405. (void)argc;
  2406. if( S_ISLNK(iMode) ){
  2407. z[0] = 'l';
  2408. }else if( S_ISREG(iMode) ){
  2409. z[0] = '-';
  2410. }else if( S_ISDIR(iMode) ){
  2411. z[0] = 'd';
  2412. }else{
  2413. z[0] = '?';
  2414. }
  2415. for(i=0; i<3; i++){
  2416. int m = (iMode >> ((2-i)*3));
  2417. char *a = &z[1 + i*3];
  2418. a[0] = (m & 0x4) ? 'r' : '-';
  2419. a[1] = (m & 0x2) ? 'w' : '-';
  2420. a[2] = (m & 0x1) ? 'x' : '-';
  2421. }
  2422. z[10] = '\0';
  2423. sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
  2424. }
  2425. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2426. /*
  2427. ** Cursor type for recursively iterating through a directory structure.
  2428. */
  2429. typedef struct fsdir_cursor fsdir_cursor;
  2430. typedef struct FsdirLevel FsdirLevel;
  2431. struct FsdirLevel {
  2432. DIR *pDir; /* From opendir() */
  2433. char *zDir; /* Name of directory (nul-terminated) */
  2434. };
  2435. struct fsdir_cursor {
  2436. sqlite3_vtab_cursor base; /* Base class - must be first */
  2437. int nLvl; /* Number of entries in aLvl[] array */
  2438. int iLvl; /* Index of current entry */
  2439. FsdirLevel *aLvl; /* Hierarchy of directories being traversed */
  2440. const char *zBase;
  2441. int nBase;
  2442. struct stat sStat; /* Current lstat() results */
  2443. char *zPath; /* Path to current entry */
  2444. sqlite3_int64 iRowid; /* Current rowid */
  2445. };
  2446. typedef struct fsdir_tab fsdir_tab;
  2447. struct fsdir_tab {
  2448. sqlite3_vtab base; /* Base class - must be first */
  2449. };
  2450. /*
  2451. ** Construct a new fsdir virtual table object.
  2452. */
  2453. static int fsdirConnect(
  2454. sqlite3 *db,
  2455. void *pAux,
  2456. int argc, const char *const*argv,
  2457. sqlite3_vtab **ppVtab,
  2458. char **pzErr
  2459. ){
  2460. fsdir_tab *pNew = 0;
  2461. int rc;
  2462. (void)pAux;
  2463. (void)argc;
  2464. (void)argv;
  2465. (void)pzErr;
  2466. rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
  2467. if( rc==SQLITE_OK ){
  2468. pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
  2469. if( pNew==0 ) return SQLITE_NOMEM;
  2470. memset(pNew, 0, sizeof(*pNew));
  2471. sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
  2472. }
  2473. *ppVtab = (sqlite3_vtab*)pNew;
  2474. return rc;
  2475. }
  2476. /*
  2477. ** This method is the destructor for fsdir vtab objects.
  2478. */
  2479. static int fsdirDisconnect(sqlite3_vtab *pVtab){
  2480. sqlite3_free(pVtab);
  2481. return SQLITE_OK;
  2482. }
  2483. /*
  2484. ** Constructor for a new fsdir_cursor object.
  2485. */
  2486. static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  2487. fsdir_cursor *pCur;
  2488. (void)p;
  2489. pCur = sqlite3_malloc( sizeof(*pCur) );
  2490. if( pCur==0 ) return SQLITE_NOMEM;
  2491. memset(pCur, 0, sizeof(*pCur));
  2492. pCur->iLvl = -1;
  2493. *ppCursor = &pCur->base;
  2494. return SQLITE_OK;
  2495. }
  2496. /*
  2497. ** Reset a cursor back to the state it was in when first returned
  2498. ** by fsdirOpen().
  2499. */
  2500. static void fsdirResetCursor(fsdir_cursor *pCur){
  2501. int i;
  2502. for(i=0; i<=pCur->iLvl; i++){
  2503. FsdirLevel *pLvl = &pCur->aLvl[i];
  2504. if( pLvl->pDir ) closedir(pLvl->pDir);
  2505. sqlite3_free(pLvl->zDir);
  2506. }
  2507. sqlite3_free(pCur->zPath);
  2508. sqlite3_free(pCur->aLvl);
  2509. pCur->aLvl = 0;
  2510. pCur->zPath = 0;
  2511. pCur->zBase = 0;
  2512. pCur->nBase = 0;
  2513. pCur->nLvl = 0;
  2514. pCur->iLvl = -1;
  2515. pCur->iRowid = 1;
  2516. }
  2517. /*
  2518. ** Destructor for an fsdir_cursor.
  2519. */
  2520. static int fsdirClose(sqlite3_vtab_cursor *cur){
  2521. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2522. fsdirResetCursor(pCur);
  2523. sqlite3_free(pCur);
  2524. return SQLITE_OK;
  2525. }
  2526. /*
  2527. ** Set the error message for the virtual table associated with cursor
  2528. ** pCur to the results of vprintf(zFmt, ...).
  2529. */
  2530. static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
  2531. va_list ap;
  2532. va_start(ap, zFmt);
  2533. pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
  2534. va_end(ap);
  2535. }
  2536. /*
  2537. ** Advance an fsdir_cursor to its next row of output.
  2538. */
  2539. static int fsdirNext(sqlite3_vtab_cursor *cur){
  2540. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2541. mode_t m = pCur->sStat.st_mode;
  2542. pCur->iRowid++;
  2543. if( S_ISDIR(m) ){
  2544. /* Descend into this directory */
  2545. int iNew = pCur->iLvl + 1;
  2546. FsdirLevel *pLvl;
  2547. if( iNew>=pCur->nLvl ){
  2548. int nNew = iNew+1;
  2549. sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
  2550. FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
  2551. if( aNew==0 ) return SQLITE_NOMEM;
  2552. memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
  2553. pCur->aLvl = aNew;
  2554. pCur->nLvl = nNew;
  2555. }
  2556. pCur->iLvl = iNew;
  2557. pLvl = &pCur->aLvl[iNew];
  2558. pLvl->zDir = pCur->zPath;
  2559. pCur->zPath = 0;
  2560. pLvl->pDir = opendir(pLvl->zDir);
  2561. if( pLvl->pDir==0 ){
  2562. fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
  2563. return SQLITE_ERROR;
  2564. }
  2565. }
  2566. while( pCur->iLvl>=0 ){
  2567. FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
  2568. struct dirent *pEntry = readdir(pLvl->pDir);
  2569. if( pEntry ){
  2570. if( pEntry->d_name[0]=='.' ){
  2571. if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
  2572. if( pEntry->d_name[1]=='\0' ) continue;
  2573. }
  2574. sqlite3_free(pCur->zPath);
  2575. pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
  2576. if( pCur->zPath==0 ) return SQLITE_NOMEM;
  2577. if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
  2578. fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
  2579. return SQLITE_ERROR;
  2580. }
  2581. return SQLITE_OK;
  2582. }
  2583. closedir(pLvl->pDir);
  2584. sqlite3_free(pLvl->zDir);
  2585. pLvl->pDir = 0;
  2586. pLvl->zDir = 0;
  2587. pCur->iLvl--;
  2588. }
  2589. /* EOF */
  2590. sqlite3_free(pCur->zPath);
  2591. pCur->zPath = 0;
  2592. return SQLITE_OK;
  2593. }
  2594. /*
  2595. ** Return values of columns for the row at which the series_cursor
  2596. ** is currently pointing.
  2597. */
  2598. static int fsdirColumn(
  2599. sqlite3_vtab_cursor *cur, /* The cursor */
  2600. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  2601. int i /* Which column to return */
  2602. ){
  2603. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2604. switch( i ){
  2605. case FSDIR_COLUMN_NAME: {
  2606. sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
  2607. break;
  2608. }
  2609. case FSDIR_COLUMN_MODE:
  2610. sqlite3_result_int64(ctx, pCur->sStat.st_mode);
  2611. break;
  2612. case FSDIR_COLUMN_MTIME:
  2613. sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
  2614. break;
  2615. case FSDIR_COLUMN_DATA: {
  2616. mode_t m = pCur->sStat.st_mode;
  2617. if( S_ISDIR(m) ){
  2618. sqlite3_result_null(ctx);
  2619. #if !defined(_WIN32) && !defined(WIN32)
  2620. }else if( S_ISLNK(m) ){
  2621. char aStatic[64];
  2622. char *aBuf = aStatic;
  2623. sqlite3_int64 nBuf = 64;
  2624. int n;
  2625. while( 1 ){
  2626. n = readlink(pCur->zPath, aBuf, nBuf);
  2627. if( n<nBuf ) break;
  2628. if( aBuf!=aStatic ) sqlite3_free(aBuf);
  2629. nBuf = nBuf*2;
  2630. aBuf = sqlite3_malloc64(nBuf);
  2631. if( aBuf==0 ){
  2632. sqlite3_result_error_nomem(ctx);
  2633. return SQLITE_NOMEM;
  2634. }
  2635. }
  2636. sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
  2637. if( aBuf!=aStatic ) sqlite3_free(aBuf);
  2638. #endif
  2639. }else{
  2640. readFileContents(ctx, pCur->zPath);
  2641. }
  2642. }
  2643. case FSDIR_COLUMN_PATH:
  2644. default: {
  2645. /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
  2646. ** always return their values as NULL */
  2647. break;
  2648. }
  2649. }
  2650. return SQLITE_OK;
  2651. }
  2652. /*
  2653. ** Return the rowid for the current row. In this implementation, the
  2654. ** first row returned is assigned rowid value 1, and each subsequent
  2655. ** row a value 1 more than that of the previous.
  2656. */
  2657. static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  2658. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2659. *pRowid = pCur->iRowid;
  2660. return SQLITE_OK;
  2661. }
  2662. /*
  2663. ** Return TRUE if the cursor has been moved off of the last
  2664. ** row of output.
  2665. */
  2666. static int fsdirEof(sqlite3_vtab_cursor *cur){
  2667. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2668. return (pCur->zPath==0);
  2669. }
  2670. /*
  2671. ** xFilter callback.
  2672. **
  2673. ** idxNum==1 PATH parameter only
  2674. ** idxNum==2 Both PATH and DIR supplied
  2675. */
  2676. static int fsdirFilter(
  2677. sqlite3_vtab_cursor *cur,
  2678. int idxNum, const char *idxStr,
  2679. int argc, sqlite3_value **argv
  2680. ){
  2681. const char *zDir = 0;
  2682. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2683. (void)idxStr;
  2684. fsdirResetCursor(pCur);
  2685. if( idxNum==0 ){
  2686. fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
  2687. return SQLITE_ERROR;
  2688. }
  2689. assert( argc==idxNum && (argc==1 || argc==2) );
  2690. zDir = (const char*)sqlite3_value_text(argv[0]);
  2691. if( zDir==0 ){
  2692. fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
  2693. return SQLITE_ERROR;
  2694. }
  2695. if( argc==2 ){
  2696. pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
  2697. }
  2698. if( pCur->zBase ){
  2699. pCur->nBase = (int)strlen(pCur->zBase)+1;
  2700. pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
  2701. }else{
  2702. pCur->zPath = sqlite3_mprintf("%s", zDir);
  2703. }
  2704. if( pCur->zPath==0 ){
  2705. return SQLITE_NOMEM;
  2706. }
  2707. if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
  2708. fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
  2709. return SQLITE_ERROR;
  2710. }
  2711. return SQLITE_OK;
  2712. }
  2713. /*
  2714. ** SQLite will invoke this method one or more times while planning a query
  2715. ** that uses the generate_series virtual table. This routine needs to create
  2716. ** a query plan for each invocation and compute an estimated cost for that
  2717. ** plan.
  2718. **
  2719. ** In this implementation idxNum is used to represent the
  2720. ** query plan. idxStr is unused.
  2721. **
  2722. ** The query plan is represented by values of idxNum:
  2723. **
  2724. ** (1) The path value is supplied by argv[0]
  2725. ** (2) Path is in argv[0] and dir is in argv[1]
  2726. */
  2727. static int fsdirBestIndex(
  2728. sqlite3_vtab *tab,
  2729. sqlite3_index_info *pIdxInfo
  2730. ){
  2731. int i; /* Loop over constraints */
  2732. int idxPath = -1; /* Index in pIdxInfo->aConstraint of PATH= */
  2733. int idxDir = -1; /* Index in pIdxInfo->aConstraint of DIR= */
  2734. int seenPath = 0; /* True if an unusable PATH= constraint is seen */
  2735. int seenDir = 0; /* True if an unusable DIR= constraint is seen */
  2736. const struct sqlite3_index_constraint *pConstraint;
  2737. (void)tab;
  2738. pConstraint = pIdxInfo->aConstraint;
  2739. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  2740. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  2741. switch( pConstraint->iColumn ){
  2742. case FSDIR_COLUMN_PATH: {
  2743. if( pConstraint->usable ){
  2744. idxPath = i;
  2745. seenPath = 0;
  2746. }else if( idxPath<0 ){
  2747. seenPath = 1;
  2748. }
  2749. break;
  2750. }
  2751. case FSDIR_COLUMN_DIR: {
  2752. if( pConstraint->usable ){
  2753. idxDir = i;
  2754. seenDir = 0;
  2755. }else if( idxDir<0 ){
  2756. seenDir = 1;
  2757. }
  2758. break;
  2759. }
  2760. }
  2761. }
  2762. if( seenPath || seenDir ){
  2763. /* If input parameters are unusable, disallow this plan */
  2764. return SQLITE_CONSTRAINT;
  2765. }
  2766. if( idxPath<0 ){
  2767. pIdxInfo->idxNum = 0;
  2768. /* The pIdxInfo->estimatedCost should have been initialized to a huge
  2769. ** number. Leave it unchanged. */
  2770. pIdxInfo->estimatedRows = 0x7fffffff;
  2771. }else{
  2772. pIdxInfo->aConstraintUsage[idxPath].omit = 1;
  2773. pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
  2774. if( idxDir>=0 ){
  2775. pIdxInfo->aConstraintUsage[idxDir].omit = 1;
  2776. pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
  2777. pIdxInfo->idxNum = 2;
  2778. pIdxInfo->estimatedCost = 10.0;
  2779. }else{
  2780. pIdxInfo->idxNum = 1;
  2781. pIdxInfo->estimatedCost = 100.0;
  2782. }
  2783. }
  2784. return SQLITE_OK;
  2785. }
  2786. /*
  2787. ** Register the "fsdir" virtual table.
  2788. */
  2789. static int fsdirRegister(sqlite3 *db){
  2790. static sqlite3_module fsdirModule = {
  2791. 0, /* iVersion */
  2792. 0, /* xCreate */
  2793. fsdirConnect, /* xConnect */
  2794. fsdirBestIndex, /* xBestIndex */
  2795. fsdirDisconnect, /* xDisconnect */
  2796. 0, /* xDestroy */
  2797. fsdirOpen, /* xOpen - open a cursor */
  2798. fsdirClose, /* xClose - close a cursor */
  2799. fsdirFilter, /* xFilter - configure scan constraints */
  2800. fsdirNext, /* xNext - advance a cursor */
  2801. fsdirEof, /* xEof - check for end of scan */
  2802. fsdirColumn, /* xColumn - read data */
  2803. fsdirRowid, /* xRowid - read data */
  2804. 0, /* xUpdate */
  2805. 0, /* xBegin */
  2806. 0, /* xSync */
  2807. 0, /* xCommit */
  2808. 0, /* xRollback */
  2809. 0, /* xFindMethod */
  2810. 0, /* xRename */
  2811. 0, /* xSavepoint */
  2812. 0, /* xRelease */
  2813. 0, /* xRollbackTo */
  2814. 0, /* xShadowName */
  2815. };
  2816. int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
  2817. return rc;
  2818. }
  2819. #else /* SQLITE_OMIT_VIRTUALTABLE */
  2820. # define fsdirRegister(x) SQLITE_OK
  2821. #endif
  2822. #ifdef _WIN32
  2823. #endif
  2824. int sqlite3_fileio_init(
  2825. sqlite3 *db,
  2826. char **pzErrMsg,
  2827. const sqlite3_api_routines *pApi
  2828. ){
  2829. int rc = SQLITE_OK;
  2830. SQLITE_EXTENSION_INIT2(pApi);
  2831. (void)pzErrMsg; /* Unused parameter */
  2832. rc = sqlite3_create_function(db, "readfile", 1,
  2833. SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
  2834. readfileFunc, 0, 0);
  2835. if( rc==SQLITE_OK ){
  2836. rc = sqlite3_create_function(db, "writefile", -1,
  2837. SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
  2838. writefileFunc, 0, 0);
  2839. }
  2840. if( rc==SQLITE_OK ){
  2841. rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
  2842. lsModeFunc, 0, 0);
  2843. }
  2844. if( rc==SQLITE_OK ){
  2845. rc = fsdirRegister(db);
  2846. }
  2847. return rc;
  2848. }
  2849. /************************* End ../ext/misc/fileio.c ********************/
  2850. /************************* Begin ../ext/misc/completion.c ******************/
  2851. /*
  2852. ** 2017-07-10
  2853. **
  2854. ** The author disclaims copyright to this source code. In place of
  2855. ** a legal notice, here is a blessing:
  2856. **
  2857. ** May you do good and not evil.
  2858. ** May you find forgiveness for yourself and forgive others.
  2859. ** May you share freely, never taking more than you give.
  2860. **
  2861. *************************************************************************
  2862. **
  2863. ** This file implements an eponymous virtual table that returns suggested
  2864. ** completions for a partial SQL input.
  2865. **
  2866. ** Suggested usage:
  2867. **
  2868. ** SELECT DISTINCT candidate COLLATE nocase
  2869. ** FROM completion($prefix,$wholeline)
  2870. ** ORDER BY 1;
  2871. **
  2872. ** The two query parameters are optional. $prefix is the text of the
  2873. ** current word being typed and that is to be completed. $wholeline is
  2874. ** the complete input line, used for context.
  2875. **
  2876. ** The raw completion() table might return the same candidate multiple
  2877. ** times, for example if the same column name is used to two or more
  2878. ** tables. And the candidates are returned in an arbitrary order. Hence,
  2879. ** the DISTINCT and ORDER BY are recommended.
  2880. **
  2881. ** This virtual table operates at the speed of human typing, and so there
  2882. ** is no attempt to make it fast. Even a slow implementation will be much
  2883. ** faster than any human can type.
  2884. **
  2885. */
  2886. /* #include "sqlite3ext.h" */
  2887. SQLITE_EXTENSION_INIT1
  2888. #include <assert.h>
  2889. #include <string.h>
  2890. #include <ctype.h>
  2891. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2892. /* completion_vtab is a subclass of sqlite3_vtab which will
  2893. ** serve as the underlying representation of a completion virtual table
  2894. */
  2895. typedef struct completion_vtab completion_vtab;
  2896. struct completion_vtab {
  2897. sqlite3_vtab base; /* Base class - must be first */
  2898. sqlite3 *db; /* Database connection for this completion vtab */
  2899. };
  2900. /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
  2901. ** serve as the underlying representation of a cursor that scans
  2902. ** over rows of the result
  2903. */
  2904. typedef struct completion_cursor completion_cursor;
  2905. struct completion_cursor {
  2906. sqlite3_vtab_cursor base; /* Base class - must be first */
  2907. sqlite3 *db; /* Database connection for this cursor */
  2908. int nPrefix, nLine; /* Number of bytes in zPrefix and zLine */
  2909. char *zPrefix; /* The prefix for the word we want to complete */
  2910. char *zLine; /* The whole that we want to complete */
  2911. const char *zCurrentRow; /* Current output row */
  2912. int szRow; /* Length of the zCurrentRow string */
  2913. sqlite3_stmt *pStmt; /* Current statement */
  2914. sqlite3_int64 iRowid; /* The rowid */
  2915. int ePhase; /* Current phase */
  2916. int j; /* inter-phase counter */
  2917. };
  2918. /* Values for ePhase:
  2919. */
  2920. #define COMPLETION_FIRST_PHASE 1
  2921. #define COMPLETION_KEYWORDS 1
  2922. #define COMPLETION_PRAGMAS 2
  2923. #define COMPLETION_FUNCTIONS 3
  2924. #define COMPLETION_COLLATIONS 4
  2925. #define COMPLETION_INDEXES 5
  2926. #define COMPLETION_TRIGGERS 6
  2927. #define COMPLETION_DATABASES 7
  2928. #define COMPLETION_TABLES 8 /* Also VIEWs and TRIGGERs */
  2929. #define COMPLETION_COLUMNS 9
  2930. #define COMPLETION_MODULES 10
  2931. #define COMPLETION_EOF 11
  2932. /*
  2933. ** The completionConnect() method is invoked to create a new
  2934. ** completion_vtab that describes the completion virtual table.
  2935. **
  2936. ** Think of this routine as the constructor for completion_vtab objects.
  2937. **
  2938. ** All this routine needs to do is:
  2939. **
  2940. ** (1) Allocate the completion_vtab object and initialize all fields.
  2941. **
  2942. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  2943. ** result set of queries against completion will look like.
  2944. */
  2945. static int completionConnect(
  2946. sqlite3 *db,
  2947. void *pAux,
  2948. int argc, const char *const*argv,
  2949. sqlite3_vtab **ppVtab,
  2950. char **pzErr
  2951. ){
  2952. completion_vtab *pNew;
  2953. int rc;
  2954. (void)(pAux); /* Unused parameter */
  2955. (void)(argc); /* Unused parameter */
  2956. (void)(argv); /* Unused parameter */
  2957. (void)(pzErr); /* Unused parameter */
  2958. /* Column numbers */
  2959. #define COMPLETION_COLUMN_CANDIDATE 0 /* Suggested completion of the input */
  2960. #define COMPLETION_COLUMN_PREFIX 1 /* Prefix of the word to be completed */
  2961. #define COMPLETION_COLUMN_WHOLELINE 2 /* Entire line seen so far */
  2962. #define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */
  2963. sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
  2964. rc = sqlite3_declare_vtab(db,
  2965. "CREATE TABLE x("
  2966. " candidate TEXT,"
  2967. " prefix TEXT HIDDEN,"
  2968. " wholeline TEXT HIDDEN,"
  2969. " phase INT HIDDEN" /* Used for debugging only */
  2970. ")");
  2971. if( rc==SQLITE_OK ){
  2972. pNew = sqlite3_malloc( sizeof(*pNew) );
  2973. *ppVtab = (sqlite3_vtab*)pNew;
  2974. if( pNew==0 ) return SQLITE_NOMEM;
  2975. memset(pNew, 0, sizeof(*pNew));
  2976. pNew->db = db;
  2977. }
  2978. return rc;
  2979. }
  2980. /*
  2981. ** This method is the destructor for completion_cursor objects.
  2982. */
  2983. static int completionDisconnect(sqlite3_vtab *pVtab){
  2984. sqlite3_free(pVtab);
  2985. return SQLITE_OK;
  2986. }
  2987. /*
  2988. ** Constructor for a new completion_cursor object.
  2989. */
  2990. static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  2991. completion_cursor *pCur;
  2992. pCur = sqlite3_malloc( sizeof(*pCur) );
  2993. if( pCur==0 ) return SQLITE_NOMEM;
  2994. memset(pCur, 0, sizeof(*pCur));
  2995. pCur->db = ((completion_vtab*)p)->db;
  2996. *ppCursor = &pCur->base;
  2997. return SQLITE_OK;
  2998. }
  2999. /*
  3000. ** Reset the completion_cursor.
  3001. */
  3002. static void completionCursorReset(completion_cursor *pCur){
  3003. sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0;
  3004. sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0;
  3005. sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
  3006. pCur->j = 0;
  3007. }
  3008. /*
  3009. ** Destructor for a completion_cursor.
  3010. */
  3011. static int completionClose(sqlite3_vtab_cursor *cur){
  3012. completionCursorReset((completion_cursor*)cur);
  3013. sqlite3_free(cur);
  3014. return SQLITE_OK;
  3015. }
  3016. /*
  3017. ** Advance a completion_cursor to its next row of output.
  3018. **
  3019. ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
  3020. ** record the current state of the scan. This routine sets ->zCurrentRow
  3021. ** to the current row of output and then returns. If no more rows remain,
  3022. ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
  3023. ** table that has reached the end of its scan.
  3024. **
  3025. ** The current implementation just lists potential identifiers and
  3026. ** keywords and filters them by zPrefix. Future enhancements should
  3027. ** take zLine into account to try to restrict the set of identifiers and
  3028. ** keywords based on what would be legal at the current point of input.
  3029. */
  3030. static int completionNext(sqlite3_vtab_cursor *cur){
  3031. completion_cursor *pCur = (completion_cursor*)cur;
  3032. int eNextPhase = 0; /* Next phase to try if current phase reaches end */
  3033. int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */
  3034. pCur->iRowid++;
  3035. while( pCur->ePhase!=COMPLETION_EOF ){
  3036. switch( pCur->ePhase ){
  3037. case COMPLETION_KEYWORDS: {
  3038. if( pCur->j >= sqlite3_keyword_count() ){
  3039. pCur->zCurrentRow = 0;
  3040. pCur->ePhase = COMPLETION_DATABASES;
  3041. }else{
  3042. sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
  3043. }
  3044. iCol = -1;
  3045. break;
  3046. }
  3047. case COMPLETION_DATABASES: {
  3048. if( pCur->pStmt==0 ){
  3049. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
  3050. &pCur->pStmt, 0);
  3051. }
  3052. iCol = 1;
  3053. eNextPhase = COMPLETION_TABLES;
  3054. break;
  3055. }
  3056. case COMPLETION_TABLES: {
  3057. if( pCur->pStmt==0 ){
  3058. sqlite3_stmt *pS2;
  3059. char *zSql = 0;
  3060. const char *zSep = "";
  3061. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
  3062. while( sqlite3_step(pS2)==SQLITE_ROW ){
  3063. const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
  3064. zSql = sqlite3_mprintf(
  3065. "%z%s"
  3066. "SELECT name FROM \"%w\".sqlite_schema",
  3067. zSql, zSep, zDb
  3068. );
  3069. if( zSql==0 ) return SQLITE_NOMEM;
  3070. zSep = " UNION ";
  3071. }
  3072. sqlite3_finalize(pS2);
  3073. sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
  3074. sqlite3_free(zSql);
  3075. }
  3076. iCol = 0;
  3077. eNextPhase = COMPLETION_COLUMNS;
  3078. break;
  3079. }
  3080. case COMPLETION_COLUMNS: {
  3081. if( pCur->pStmt==0 ){
  3082. sqlite3_stmt *pS2;
  3083. char *zSql = 0;
  3084. const char *zSep = "";
  3085. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
  3086. while( sqlite3_step(pS2)==SQLITE_ROW ){
  3087. const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
  3088. zSql = sqlite3_mprintf(
  3089. "%z%s"
  3090. "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
  3091. " JOIN pragma_table_info(sm.name,%Q) AS pti"
  3092. " WHERE sm.type='table'",
  3093. zSql, zSep, zDb, zDb
  3094. );
  3095. if( zSql==0 ) return SQLITE_NOMEM;
  3096. zSep = " UNION ";
  3097. }
  3098. sqlite3_finalize(pS2);
  3099. sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
  3100. sqlite3_free(zSql);
  3101. }
  3102. iCol = 0;
  3103. eNextPhase = COMPLETION_EOF;
  3104. break;
  3105. }
  3106. }
  3107. if( iCol<0 ){
  3108. /* This case is when the phase presets zCurrentRow */
  3109. if( pCur->zCurrentRow==0 ) continue;
  3110. }else{
  3111. if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
  3112. /* Extract the next row of content */
  3113. pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
  3114. pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
  3115. }else{
  3116. /* When all rows are finished, advance to the next phase */
  3117. sqlite3_finalize(pCur->pStmt);
  3118. pCur->pStmt = 0;
  3119. pCur->ePhase = eNextPhase;
  3120. continue;
  3121. }
  3122. }
  3123. if( pCur->nPrefix==0 ) break;
  3124. if( pCur->nPrefix<=pCur->szRow
  3125. && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
  3126. ){
  3127. break;
  3128. }
  3129. }
  3130. return SQLITE_OK;
  3131. }
  3132. /*
  3133. ** Return values of columns for the row at which the completion_cursor
  3134. ** is currently pointing.
  3135. */
  3136. static int completionColumn(
  3137. sqlite3_vtab_cursor *cur, /* The cursor */
  3138. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  3139. int i /* Which column to return */
  3140. ){
  3141. completion_cursor *pCur = (completion_cursor*)cur;
  3142. switch( i ){
  3143. case COMPLETION_COLUMN_CANDIDATE: {
  3144. sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
  3145. break;
  3146. }
  3147. case COMPLETION_COLUMN_PREFIX: {
  3148. sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
  3149. break;
  3150. }
  3151. case COMPLETION_COLUMN_WHOLELINE: {
  3152. sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
  3153. break;
  3154. }
  3155. case COMPLETION_COLUMN_PHASE: {
  3156. sqlite3_result_int(ctx, pCur->ePhase);
  3157. break;
  3158. }
  3159. }
  3160. return SQLITE_OK;
  3161. }
  3162. /*
  3163. ** Return the rowid for the current row. In this implementation, the
  3164. ** rowid is the same as the output value.
  3165. */
  3166. static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  3167. completion_cursor *pCur = (completion_cursor*)cur;
  3168. *pRowid = pCur->iRowid;
  3169. return SQLITE_OK;
  3170. }
  3171. /*
  3172. ** Return TRUE if the cursor has been moved off of the last
  3173. ** row of output.
  3174. */
  3175. static int completionEof(sqlite3_vtab_cursor *cur){
  3176. completion_cursor *pCur = (completion_cursor*)cur;
  3177. return pCur->ePhase >= COMPLETION_EOF;
  3178. }
  3179. /*
  3180. ** This method is called to "rewind" the completion_cursor object back
  3181. ** to the first row of output. This method is always called at least
  3182. ** once prior to any call to completionColumn() or completionRowid() or
  3183. ** completionEof().
  3184. */
  3185. static int completionFilter(
  3186. sqlite3_vtab_cursor *pVtabCursor,
  3187. int idxNum, const char *idxStr,
  3188. int argc, sqlite3_value **argv
  3189. ){
  3190. completion_cursor *pCur = (completion_cursor *)pVtabCursor;
  3191. int iArg = 0;
  3192. (void)(idxStr); /* Unused parameter */
  3193. (void)(argc); /* Unused parameter */
  3194. completionCursorReset(pCur);
  3195. if( idxNum & 1 ){
  3196. pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
  3197. if( pCur->nPrefix>0 ){
  3198. pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
  3199. if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
  3200. }
  3201. iArg = 1;
  3202. }
  3203. if( idxNum & 2 ){
  3204. pCur->nLine = sqlite3_value_bytes(argv[iArg]);
  3205. if( pCur->nLine>0 ){
  3206. pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
  3207. if( pCur->zLine==0 ) return SQLITE_NOMEM;
  3208. }
  3209. }
  3210. if( pCur->zLine!=0 && pCur->zPrefix==0 ){
  3211. int i = pCur->nLine;
  3212. while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
  3213. i--;
  3214. }
  3215. pCur->nPrefix = pCur->nLine - i;
  3216. if( pCur->nPrefix>0 ){
  3217. pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
  3218. if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
  3219. }
  3220. }
  3221. pCur->iRowid = 0;
  3222. pCur->ePhase = COMPLETION_FIRST_PHASE;
  3223. return completionNext(pVtabCursor);
  3224. }
  3225. /*
  3226. ** SQLite will invoke this method one or more times while planning a query
  3227. ** that uses the completion virtual table. This routine needs to create
  3228. ** a query plan for each invocation and compute an estimated cost for that
  3229. ** plan.
  3230. **
  3231. ** There are two hidden parameters that act as arguments to the table-valued
  3232. ** function: "prefix" and "wholeline". Bit 0 of idxNum is set if "prefix"
  3233. ** is available and bit 1 is set if "wholeline" is available.
  3234. */
  3235. static int completionBestIndex(
  3236. sqlite3_vtab *tab,
  3237. sqlite3_index_info *pIdxInfo
  3238. ){
  3239. int i; /* Loop over constraints */
  3240. int idxNum = 0; /* The query plan bitmask */
  3241. int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */
  3242. int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
  3243. int nArg = 0; /* Number of arguments that completeFilter() expects */
  3244. const struct sqlite3_index_constraint *pConstraint;
  3245. (void)(tab); /* Unused parameter */
  3246. pConstraint = pIdxInfo->aConstraint;
  3247. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  3248. if( pConstraint->usable==0 ) continue;
  3249. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  3250. switch( pConstraint->iColumn ){
  3251. case COMPLETION_COLUMN_PREFIX:
  3252. prefixIdx = i;
  3253. idxNum |= 1;
  3254. break;
  3255. case COMPLETION_COLUMN_WHOLELINE:
  3256. wholelineIdx = i;
  3257. idxNum |= 2;
  3258. break;
  3259. }
  3260. }
  3261. if( prefixIdx>=0 ){
  3262. pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
  3263. pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
  3264. }
  3265. if( wholelineIdx>=0 ){
  3266. pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
  3267. pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
  3268. }
  3269. pIdxInfo->idxNum = idxNum;
  3270. pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
  3271. pIdxInfo->estimatedRows = 500 - 100*nArg;
  3272. return SQLITE_OK;
  3273. }
  3274. /*
  3275. ** This following structure defines all the methods for the
  3276. ** completion virtual table.
  3277. */
  3278. static sqlite3_module completionModule = {
  3279. 0, /* iVersion */
  3280. 0, /* xCreate */
  3281. completionConnect, /* xConnect */
  3282. completionBestIndex, /* xBestIndex */
  3283. completionDisconnect, /* xDisconnect */
  3284. 0, /* xDestroy */
  3285. completionOpen, /* xOpen - open a cursor */
  3286. completionClose, /* xClose - close a cursor */
  3287. completionFilter, /* xFilter - configure scan constraints */
  3288. completionNext, /* xNext - advance a cursor */
  3289. completionEof, /* xEof - check for end of scan */
  3290. completionColumn, /* xColumn - read data */
  3291. completionRowid, /* xRowid - read data */
  3292. 0, /* xUpdate */
  3293. 0, /* xBegin */
  3294. 0, /* xSync */
  3295. 0, /* xCommit */
  3296. 0, /* xRollback */
  3297. 0, /* xFindMethod */
  3298. 0, /* xRename */
  3299. 0, /* xSavepoint */
  3300. 0, /* xRelease */
  3301. 0, /* xRollbackTo */
  3302. 0 /* xShadowName */
  3303. };
  3304. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  3305. int sqlite3CompletionVtabInit(sqlite3 *db){
  3306. int rc = SQLITE_OK;
  3307. #ifndef SQLITE_OMIT_VIRTUALTABLE
  3308. rc = sqlite3_create_module(db, "completion", &completionModule, 0);
  3309. #endif
  3310. return rc;
  3311. }
  3312. #ifdef _WIN32
  3313. #endif
  3314. int sqlite3_completion_init(
  3315. sqlite3 *db,
  3316. char **pzErrMsg,
  3317. const sqlite3_api_routines *pApi
  3318. ){
  3319. int rc = SQLITE_OK;
  3320. SQLITE_EXTENSION_INIT2(pApi);
  3321. (void)(pzErrMsg); /* Unused parameter */
  3322. #ifndef SQLITE_OMIT_VIRTUALTABLE
  3323. rc = sqlite3CompletionVtabInit(db);
  3324. #endif
  3325. return rc;
  3326. }
  3327. /************************* End ../ext/misc/completion.c ********************/
  3328. /************************* Begin ../ext/misc/appendvfs.c ******************/
  3329. /*
  3330. ** 2017-10-20
  3331. **
  3332. ** The author disclaims copyright to this source code. In place of
  3333. ** a legal notice, here is a blessing:
  3334. **
  3335. ** May you do good and not evil.
  3336. ** May you find forgiveness for yourself and forgive others.
  3337. ** May you share freely, never taking more than you give.
  3338. **
  3339. ******************************************************************************
  3340. **
  3341. ** This file implements a VFS shim that allows an SQLite database to be
  3342. ** appended onto the end of some other file, such as an executable.
  3343. **
  3344. ** A special record must appear at the end of the file that identifies the
  3345. ** file as an appended database and provides an offset to page 1. For
  3346. ** best performance page 1 should be located at a disk page boundary, though
  3347. ** that is not required.
  3348. **
  3349. ** When opening a database using this VFS, the connection might treat
  3350. ** the file as an ordinary SQLite database, or it might treat is as a
  3351. ** database appended onto some other file. Here are the rules:
  3352. **
  3353. ** (1) When opening a new empty file, that file is treated as an ordinary
  3354. ** database.
  3355. **
  3356. ** (2) When opening a file that begins with the standard SQLite prefix
  3357. ** string "SQLite format 3", that file is treated as an ordinary
  3358. ** database.
  3359. **
  3360. ** (3) When opening a file that ends with the appendvfs trailer string
  3361. ** "Start-Of-SQLite3-NNNNNNNN" that file is treated as an appended
  3362. ** database.
  3363. **
  3364. ** (4) If none of the above apply and the SQLITE_OPEN_CREATE flag is
  3365. ** set, then a new database is appended to the already existing file.
  3366. **
  3367. ** (5) Otherwise, SQLITE_CANTOPEN is returned.
  3368. **
  3369. ** To avoid unnecessary complications with the PENDING_BYTE, the size of
  3370. ** the file containing the database is limited to 1GB. This VFS will refuse
  3371. ** to read or write past the 1GB mark. This restriction might be lifted in
  3372. ** future versions. For now, if you need a large database, then keep the
  3373. ** database in a separate file.
  3374. **
  3375. ** If the file being opened is not an appended database, then this shim is
  3376. ** a pass-through into the default underlying VFS.
  3377. **/
  3378. /* #include "sqlite3ext.h" */
  3379. SQLITE_EXTENSION_INIT1
  3380. #include <string.h>
  3381. #include <assert.h>
  3382. /* The append mark at the end of the database is:
  3383. **
  3384. ** Start-Of-SQLite3-NNNNNNNN
  3385. ** 123456789 123456789 12345
  3386. **
  3387. ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
  3388. ** the offset to page 1.
  3389. */
  3390. #define APND_MARK_PREFIX "Start-Of-SQLite3-"
  3391. #define APND_MARK_PREFIX_SZ 17
  3392. #define APND_MARK_SIZE 25
  3393. /*
  3394. ** Maximum size of the combined prefix + database + append-mark. This
  3395. ** must be less than 0x40000000 to avoid locking issues on Windows.
  3396. */
  3397. #define APND_MAX_SIZE (65536*15259)
  3398. /*
  3399. ** Forward declaration of objects used by this utility
  3400. */
  3401. typedef struct sqlite3_vfs ApndVfs;
  3402. typedef struct ApndFile ApndFile;
  3403. /* Access to a lower-level VFS that (might) implement dynamic loading,
  3404. ** access to randomness, etc.
  3405. */
  3406. #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
  3407. #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
  3408. /* An open file */
  3409. struct ApndFile {
  3410. sqlite3_file base; /* IO methods */
  3411. sqlite3_int64 iPgOne; /* File offset to page 1 */
  3412. sqlite3_int64 iMark; /* Start of the append-mark */
  3413. };
  3414. /*
  3415. ** Methods for ApndFile
  3416. */
  3417. static int apndClose(sqlite3_file*);
  3418. static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  3419. static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
  3420. static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
  3421. static int apndSync(sqlite3_file*, int flags);
  3422. static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
  3423. static int apndLock(sqlite3_file*, int);
  3424. static int apndUnlock(sqlite3_file*, int);
  3425. static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
  3426. static int apndFileControl(sqlite3_file*, int op, void *pArg);
  3427. static int apndSectorSize(sqlite3_file*);
  3428. static int apndDeviceCharacteristics(sqlite3_file*);
  3429. static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  3430. static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
  3431. static void apndShmBarrier(sqlite3_file*);
  3432. static int apndShmUnmap(sqlite3_file*, int deleteFlag);
  3433. static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  3434. static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  3435. /*
  3436. ** Methods for ApndVfs
  3437. */
  3438. static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
  3439. static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
  3440. static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
  3441. static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
  3442. static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
  3443. static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
  3444. static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
  3445. static void apndDlClose(sqlite3_vfs*, void*);
  3446. static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
  3447. static int apndSleep(sqlite3_vfs*, int microseconds);
  3448. static int apndCurrentTime(sqlite3_vfs*, double*);
  3449. static int apndGetLastError(sqlite3_vfs*, int, char *);
  3450. static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
  3451. static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
  3452. static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
  3453. static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
  3454. static sqlite3_vfs apnd_vfs = {
  3455. 3, /* iVersion (set when registered) */
  3456. 0, /* szOsFile (set when registered) */
  3457. 1024, /* mxPathname */
  3458. 0, /* pNext */
  3459. "apndvfs", /* zName */
  3460. 0, /* pAppData (set when registered) */
  3461. apndOpen, /* xOpen */
  3462. apndDelete, /* xDelete */
  3463. apndAccess, /* xAccess */
  3464. apndFullPathname, /* xFullPathname */
  3465. apndDlOpen, /* xDlOpen */
  3466. apndDlError, /* xDlError */
  3467. apndDlSym, /* xDlSym */
  3468. apndDlClose, /* xDlClose */
  3469. apndRandomness, /* xRandomness */
  3470. apndSleep, /* xSleep */
  3471. apndCurrentTime, /* xCurrentTime */
  3472. apndGetLastError, /* xGetLastError */
  3473. apndCurrentTimeInt64, /* xCurrentTimeInt64 */
  3474. apndSetSystemCall, /* xSetSystemCall */
  3475. apndGetSystemCall, /* xGetSystemCall */
  3476. apndNextSystemCall /* xNextSystemCall */
  3477. };
  3478. static const sqlite3_io_methods apnd_io_methods = {
  3479. 3, /* iVersion */
  3480. apndClose, /* xClose */
  3481. apndRead, /* xRead */
  3482. apndWrite, /* xWrite */
  3483. apndTruncate, /* xTruncate */
  3484. apndSync, /* xSync */
  3485. apndFileSize, /* xFileSize */
  3486. apndLock, /* xLock */
  3487. apndUnlock, /* xUnlock */
  3488. apndCheckReservedLock, /* xCheckReservedLock */
  3489. apndFileControl, /* xFileControl */
  3490. apndSectorSize, /* xSectorSize */
  3491. apndDeviceCharacteristics, /* xDeviceCharacteristics */
  3492. apndShmMap, /* xShmMap */
  3493. apndShmLock, /* xShmLock */
  3494. apndShmBarrier, /* xShmBarrier */
  3495. apndShmUnmap, /* xShmUnmap */
  3496. apndFetch, /* xFetch */
  3497. apndUnfetch /* xUnfetch */
  3498. };
  3499. /*
  3500. ** Close an apnd-file.
  3501. */
  3502. static int apndClose(sqlite3_file *pFile){
  3503. pFile = ORIGFILE(pFile);
  3504. return pFile->pMethods->xClose(pFile);
  3505. }
  3506. /*
  3507. ** Read data from an apnd-file.
  3508. */
  3509. static int apndRead(
  3510. sqlite3_file *pFile,
  3511. void *zBuf,
  3512. int iAmt,
  3513. sqlite_int64 iOfst
  3514. ){
  3515. ApndFile *p = (ApndFile *)pFile;
  3516. pFile = ORIGFILE(pFile);
  3517. return pFile->pMethods->xRead(pFile, zBuf, iAmt, iOfst+p->iPgOne);
  3518. }
  3519. /*
  3520. ** Add the append-mark onto the end of the file.
  3521. */
  3522. static int apndWriteMark(ApndFile *p, sqlite3_file *pFile){
  3523. int i;
  3524. unsigned char a[APND_MARK_SIZE];
  3525. memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
  3526. for(i=0; i<8; i++){
  3527. a[APND_MARK_PREFIX_SZ+i] = (p->iPgOne >> (56 - i*8)) & 0xff;
  3528. }
  3529. return pFile->pMethods->xWrite(pFile, a, APND_MARK_SIZE, p->iMark);
  3530. }
  3531. /*
  3532. ** Write data to an apnd-file.
  3533. */
  3534. static int apndWrite(
  3535. sqlite3_file *pFile,
  3536. const void *zBuf,
  3537. int iAmt,
  3538. sqlite_int64 iOfst
  3539. ){
  3540. int rc;
  3541. ApndFile *p = (ApndFile *)pFile;
  3542. pFile = ORIGFILE(pFile);
  3543. if( iOfst+iAmt>=APND_MAX_SIZE ) return SQLITE_FULL;
  3544. rc = pFile->pMethods->xWrite(pFile, zBuf, iAmt, iOfst+p->iPgOne);
  3545. if( rc==SQLITE_OK && iOfst + iAmt + p->iPgOne > p->iMark ){
  3546. sqlite3_int64 sz = 0;
  3547. rc = pFile->pMethods->xFileSize(pFile, &sz);
  3548. if( rc==SQLITE_OK ){
  3549. p->iMark = sz - APND_MARK_SIZE;
  3550. if( iOfst + iAmt + p->iPgOne > p->iMark ){
  3551. p->iMark = p->iPgOne + iOfst + iAmt;
  3552. rc = apndWriteMark(p, pFile);
  3553. }
  3554. }
  3555. }
  3556. return rc;
  3557. }
  3558. /*
  3559. ** Truncate an apnd-file.
  3560. */
  3561. static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
  3562. int rc;
  3563. ApndFile *p = (ApndFile *)pFile;
  3564. pFile = ORIGFILE(pFile);
  3565. rc = pFile->pMethods->xTruncate(pFile, size+p->iPgOne+APND_MARK_SIZE);
  3566. if( rc==SQLITE_OK ){
  3567. p->iMark = p->iPgOne+size;
  3568. rc = apndWriteMark(p, pFile);
  3569. }
  3570. return rc;
  3571. }
  3572. /*
  3573. ** Sync an apnd-file.
  3574. */
  3575. static int apndSync(sqlite3_file *pFile, int flags){
  3576. pFile = ORIGFILE(pFile);
  3577. return pFile->pMethods->xSync(pFile, flags);
  3578. }
  3579. /*
  3580. ** Return the current file-size of an apnd-file.
  3581. */
  3582. static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  3583. ApndFile *p = (ApndFile *)pFile;
  3584. int rc;
  3585. pFile = ORIGFILE(p);
  3586. rc = pFile->pMethods->xFileSize(pFile, pSize);
  3587. if( rc==SQLITE_OK && p->iPgOne ){
  3588. *pSize -= p->iPgOne + APND_MARK_SIZE;
  3589. }
  3590. return rc;
  3591. }
  3592. /*
  3593. ** Lock an apnd-file.
  3594. */
  3595. static int apndLock(sqlite3_file *pFile, int eLock){
  3596. pFile = ORIGFILE(pFile);
  3597. return pFile->pMethods->xLock(pFile, eLock);
  3598. }
  3599. /*
  3600. ** Unlock an apnd-file.
  3601. */
  3602. static int apndUnlock(sqlite3_file *pFile, int eLock){
  3603. pFile = ORIGFILE(pFile);
  3604. return pFile->pMethods->xUnlock(pFile, eLock);
  3605. }
  3606. /*
  3607. ** Check if another file-handle holds a RESERVED lock on an apnd-file.
  3608. */
  3609. static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  3610. pFile = ORIGFILE(pFile);
  3611. return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
  3612. }
  3613. /*
  3614. ** File control method. For custom operations on an apnd-file.
  3615. */
  3616. static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
  3617. ApndFile *p = (ApndFile *)pFile;
  3618. int rc;
  3619. pFile = ORIGFILE(pFile);
  3620. rc = pFile->pMethods->xFileControl(pFile, op, pArg);
  3621. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  3622. *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", p->iPgOne, *(char**)pArg);
  3623. }
  3624. return rc;
  3625. }
  3626. /*
  3627. ** Return the sector-size in bytes for an apnd-file.
  3628. */
  3629. static int apndSectorSize(sqlite3_file *pFile){
  3630. pFile = ORIGFILE(pFile);
  3631. return pFile->pMethods->xSectorSize(pFile);
  3632. }
  3633. /*
  3634. ** Return the device characteristic flags supported by an apnd-file.
  3635. */
  3636. static int apndDeviceCharacteristics(sqlite3_file *pFile){
  3637. pFile = ORIGFILE(pFile);
  3638. return pFile->pMethods->xDeviceCharacteristics(pFile);
  3639. }
  3640. /* Create a shared memory file mapping */
  3641. static int apndShmMap(
  3642. sqlite3_file *pFile,
  3643. int iPg,
  3644. int pgsz,
  3645. int bExtend,
  3646. void volatile **pp
  3647. ){
  3648. pFile = ORIGFILE(pFile);
  3649. return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
  3650. }
  3651. /* Perform locking on a shared-memory segment */
  3652. static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
  3653. pFile = ORIGFILE(pFile);
  3654. return pFile->pMethods->xShmLock(pFile,offset,n,flags);
  3655. }
  3656. /* Memory barrier operation on shared memory */
  3657. static void apndShmBarrier(sqlite3_file *pFile){
  3658. pFile = ORIGFILE(pFile);
  3659. pFile->pMethods->xShmBarrier(pFile);
  3660. }
  3661. /* Unmap a shared memory segment */
  3662. static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
  3663. pFile = ORIGFILE(pFile);
  3664. return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
  3665. }
  3666. /* Fetch a page of a memory-mapped file */
  3667. static int apndFetch(
  3668. sqlite3_file *pFile,
  3669. sqlite3_int64 iOfst,
  3670. int iAmt,
  3671. void **pp
  3672. ){
  3673. ApndFile *p = (ApndFile *)pFile;
  3674. pFile = ORIGFILE(pFile);
  3675. return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
  3676. }
  3677. /* Release a memory-mapped page */
  3678. static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
  3679. ApndFile *p = (ApndFile *)pFile;
  3680. pFile = ORIGFILE(pFile);
  3681. return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
  3682. }
  3683. /*
  3684. ** Check to see if the file is an ordinary SQLite database file.
  3685. */
  3686. static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
  3687. int rc;
  3688. char zHdr[16];
  3689. static const char aSqliteHdr[] = "SQLite format 3";
  3690. if( sz<512 ) return 0;
  3691. rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0);
  3692. if( rc ) return 0;
  3693. return memcmp(zHdr, aSqliteHdr, sizeof(zHdr))==0;
  3694. }
  3695. /*
  3696. ** Try to read the append-mark off the end of a file. Return the
  3697. ** start of the appended database if the append-mark is present. If
  3698. ** there is no append-mark, return -1;
  3699. */
  3700. static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
  3701. int rc, i;
  3702. sqlite3_int64 iMark;
  3703. unsigned char a[APND_MARK_SIZE];
  3704. if( sz<=APND_MARK_SIZE ) return -1;
  3705. rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
  3706. if( rc ) return -1;
  3707. if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
  3708. iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ]&0x7f))<<56;
  3709. for(i=1; i<8; i++){
  3710. iMark += (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<(56-8*i);
  3711. }
  3712. return iMark;
  3713. }
  3714. /*
  3715. ** Open an apnd file handle.
  3716. */
  3717. static int apndOpen(
  3718. sqlite3_vfs *pVfs,
  3719. const char *zName,
  3720. sqlite3_file *pFile,
  3721. int flags,
  3722. int *pOutFlags
  3723. ){
  3724. ApndFile *p;
  3725. sqlite3_file *pSubFile;
  3726. sqlite3_vfs *pSubVfs;
  3727. int rc;
  3728. sqlite3_int64 sz;
  3729. pSubVfs = ORIGVFS(pVfs);
  3730. if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
  3731. return pSubVfs->xOpen(pSubVfs, zName, pFile, flags, pOutFlags);
  3732. }
  3733. p = (ApndFile*)pFile;
  3734. memset(p, 0, sizeof(*p));
  3735. pSubFile = ORIGFILE(pFile);
  3736. pFile->pMethods = &apnd_io_methods;
  3737. rc = pSubVfs->xOpen(pSubVfs, zName, pSubFile, flags, pOutFlags);
  3738. if( rc ) goto apnd_open_done;
  3739. rc = pSubFile->pMethods->xFileSize(pSubFile, &sz);
  3740. if( rc ){
  3741. pSubFile->pMethods->xClose(pSubFile);
  3742. goto apnd_open_done;
  3743. }
  3744. if( apndIsOrdinaryDatabaseFile(sz, pSubFile) ){
  3745. memmove(pFile, pSubFile, pSubVfs->szOsFile);
  3746. return SQLITE_OK;
  3747. }
  3748. p->iMark = 0;
  3749. p->iPgOne = apndReadMark(sz, pFile);
  3750. if( p->iPgOne>0 ){
  3751. return SQLITE_OK;
  3752. }
  3753. if( (flags & SQLITE_OPEN_CREATE)==0 ){
  3754. pSubFile->pMethods->xClose(pSubFile);
  3755. rc = SQLITE_CANTOPEN;
  3756. }
  3757. p->iPgOne = (sz+0xfff) & ~(sqlite3_int64)0xfff;
  3758. apnd_open_done:
  3759. if( rc ) pFile->pMethods = 0;
  3760. return rc;
  3761. }
  3762. /*
  3763. ** All other VFS methods are pass-thrus.
  3764. */
  3765. static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  3766. return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
  3767. }
  3768. static int apndAccess(
  3769. sqlite3_vfs *pVfs,
  3770. const char *zPath,
  3771. int flags,
  3772. int *pResOut
  3773. ){
  3774. return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
  3775. }
  3776. static int apndFullPathname(
  3777. sqlite3_vfs *pVfs,
  3778. const char *zPath,
  3779. int nOut,
  3780. char *zOut
  3781. ){
  3782. return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
  3783. }
  3784. static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  3785. return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
  3786. }
  3787. static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  3788. ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
  3789. }
  3790. static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
  3791. return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
  3792. }
  3793. static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
  3794. ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
  3795. }
  3796. static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  3797. return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
  3798. }
  3799. static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
  3800. return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
  3801. }
  3802. static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  3803. return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
  3804. }
  3805. static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  3806. return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
  3807. }
  3808. static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
  3809. return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
  3810. }
  3811. static int apndSetSystemCall(
  3812. sqlite3_vfs *pVfs,
  3813. const char *zName,
  3814. sqlite3_syscall_ptr pCall
  3815. ){
  3816. return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
  3817. }
  3818. static sqlite3_syscall_ptr apndGetSystemCall(
  3819. sqlite3_vfs *pVfs,
  3820. const char *zName
  3821. ){
  3822. return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
  3823. }
  3824. static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
  3825. return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
  3826. }
  3827. #ifdef _WIN32
  3828. #endif
  3829. /*
  3830. ** This routine is called when the extension is loaded.
  3831. ** Register the new VFS.
  3832. */
  3833. int sqlite3_appendvfs_init(
  3834. sqlite3 *db,
  3835. char **pzErrMsg,
  3836. const sqlite3_api_routines *pApi
  3837. ){
  3838. int rc = SQLITE_OK;
  3839. sqlite3_vfs *pOrig;
  3840. SQLITE_EXTENSION_INIT2(pApi);
  3841. (void)pzErrMsg;
  3842. (void)db;
  3843. pOrig = sqlite3_vfs_find(0);
  3844. apnd_vfs.iVersion = pOrig->iVersion;
  3845. apnd_vfs.pAppData = pOrig;
  3846. apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
  3847. rc = sqlite3_vfs_register(&apnd_vfs, 0);
  3848. #ifdef APPENDVFS_TEST
  3849. if( rc==SQLITE_OK ){
  3850. rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
  3851. }
  3852. #endif
  3853. if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
  3854. return rc;
  3855. }
  3856. /************************* End ../ext/misc/appendvfs.c ********************/
  3857. /************************* Begin ../ext/misc/memtrace.c ******************/
  3858. /*
  3859. ** 2019-01-21
  3860. **
  3861. ** The author disclaims copyright to this source code. In place of
  3862. ** a legal notice, here is a blessing:
  3863. **
  3864. ** May you do good and not evil.
  3865. ** May you find forgiveness for yourself and forgive others.
  3866. ** May you share freely, never taking more than you give.
  3867. **
  3868. *************************************************************************
  3869. **
  3870. ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
  3871. ** mechanism to add a tracing layer on top of SQLite. If this extension
  3872. ** is registered prior to sqlite3_initialize(), it will cause all memory
  3873. ** allocation activities to be logged on standard output, or to some other
  3874. ** FILE specified by the initializer.
  3875. **
  3876. ** This file needs to be compiled into the application that uses it.
  3877. **
  3878. ** This extension is used to implement the --memtrace option of the
  3879. ** command-line shell.
  3880. */
  3881. #include <assert.h>
  3882. #include <string.h>
  3883. #include <stdio.h>
  3884. /* The original memory allocation routines */
  3885. static sqlite3_mem_methods memtraceBase;
  3886. static FILE *memtraceOut;
  3887. /* Methods that trace memory allocations */
  3888. static void *memtraceMalloc(int n){
  3889. if( memtraceOut ){
  3890. fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
  3891. memtraceBase.xRoundup(n));
  3892. }
  3893. return memtraceBase.xMalloc(n);
  3894. }
  3895. static void memtraceFree(void *p){
  3896. if( p==0 ) return;
  3897. if( memtraceOut ){
  3898. fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
  3899. }
  3900. memtraceBase.xFree(p);
  3901. }
  3902. static void *memtraceRealloc(void *p, int n){
  3903. if( p==0 ) return memtraceMalloc(n);
  3904. if( n==0 ){
  3905. memtraceFree(p);
  3906. return 0;
  3907. }
  3908. if( memtraceOut ){
  3909. fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
  3910. memtraceBase.xSize(p), memtraceBase.xRoundup(n));
  3911. }
  3912. return memtraceBase.xRealloc(p, n);
  3913. }
  3914. static int memtraceSize(void *p){
  3915. return memtraceBase.xSize(p);
  3916. }
  3917. static int memtraceRoundup(int n){
  3918. return memtraceBase.xRoundup(n);
  3919. }
  3920. static int memtraceInit(void *p){
  3921. return memtraceBase.xInit(p);
  3922. }
  3923. static void memtraceShutdown(void *p){
  3924. memtraceBase.xShutdown(p);
  3925. }
  3926. /* The substitute memory allocator */
  3927. static sqlite3_mem_methods ersaztMethods = {
  3928. memtraceMalloc,
  3929. memtraceFree,
  3930. memtraceRealloc,
  3931. memtraceSize,
  3932. memtraceRoundup,
  3933. memtraceInit,
  3934. memtraceShutdown,
  3935. 0
  3936. };
  3937. /* Begin tracing memory allocations to out. */
  3938. int sqlite3MemTraceActivate(FILE *out){
  3939. int rc = SQLITE_OK;
  3940. if( memtraceBase.xMalloc==0 ){
  3941. rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
  3942. if( rc==SQLITE_OK ){
  3943. rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
  3944. }
  3945. }
  3946. memtraceOut = out;
  3947. return rc;
  3948. }
  3949. /* Deactivate memory tracing */
  3950. int sqlite3MemTraceDeactivate(void){
  3951. int rc = SQLITE_OK;
  3952. if( memtraceBase.xMalloc!=0 ){
  3953. rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
  3954. if( rc==SQLITE_OK ){
  3955. memset(&memtraceBase, 0, sizeof(memtraceBase));
  3956. }
  3957. }
  3958. memtraceOut = 0;
  3959. return rc;
  3960. }
  3961. /************************* End ../ext/misc/memtrace.c ********************/
  3962. /************************* Begin ../ext/misc/uint.c ******************/
  3963. /*
  3964. ** 2020-04-14
  3965. **
  3966. ** The author disclaims copyright to this source code. In place of
  3967. ** a legal notice, here is a blessing:
  3968. **
  3969. ** May you do good and not evil.
  3970. ** May you find forgiveness for yourself and forgive others.
  3971. ** May you share freely, never taking more than you give.
  3972. **
  3973. ******************************************************************************
  3974. **
  3975. ** This SQLite extension implements the UINT collating sequence.
  3976. **
  3977. ** UINT works like BINARY for text, except that embedded strings
  3978. ** of digits compare in numeric order.
  3979. **
  3980. ** * Leading zeros are handled properly, in the sense that
  3981. ** they do not mess of the maginitude comparison of embedded
  3982. ** strings of digits. "x00123y" is equal to "x123y".
  3983. **
  3984. ** * Only unsigned integers are recognized. Plus and minus
  3985. ** signs are ignored. Decimal points and exponential notation
  3986. ** are ignored.
  3987. **
  3988. ** * Embedded integers can be of arbitrary length. Comparison
  3989. ** is *not* limited integers that can be expressed as a
  3990. ** 64-bit machine integer.
  3991. */
  3992. /* #include "sqlite3ext.h" */
  3993. SQLITE_EXTENSION_INIT1
  3994. #include <assert.h>
  3995. #include <string.h>
  3996. #include <ctype.h>
  3997. /*
  3998. ** Compare text in lexicographic order, except strings of digits
  3999. ** compare in numeric order.
  4000. */
  4001. static int uintCollFunc(
  4002. void *notUsed,
  4003. int nKey1, const void *pKey1,
  4004. int nKey2, const void *pKey2
  4005. ){
  4006. const unsigned char *zA = (const unsigned char*)pKey1;
  4007. const unsigned char *zB = (const unsigned char*)pKey2;
  4008. int i=0, j=0, x;
  4009. (void)notUsed;
  4010. while( i<nKey1 && j<nKey2 ){
  4011. x = zA[i] - zB[j];
  4012. if( isdigit(zA[i]) ){
  4013. int k;
  4014. if( !isdigit(zB[j]) ) return x;
  4015. while( i<nKey1 && zA[i]=='0' ){ i++; }
  4016. while( j<nKey2 && zB[j]=='0' ){ j++; }
  4017. k = 0;
  4018. while( i+k<nKey1 && isdigit(zA[i+k])
  4019. && j+k<nKey2 && isdigit(zB[j+k]) ){
  4020. k++;
  4021. }
  4022. if( i+k<nKey1 && isdigit(zA[i+k]) ){
  4023. return +1;
  4024. }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
  4025. return -1;
  4026. }else{
  4027. x = memcmp(zA+i, zB+j, k);
  4028. if( x ) return x;
  4029. i += k;
  4030. j += k;
  4031. }
  4032. }else if( x ){
  4033. return x;
  4034. }else{
  4035. i++;
  4036. j++;
  4037. }
  4038. }
  4039. return (nKey1 - i) - (nKey2 - j);
  4040. }
  4041. #ifdef _WIN32
  4042. #endif
  4043. int sqlite3_uint_init(
  4044. sqlite3 *db,
  4045. char **pzErrMsg,
  4046. const sqlite3_api_routines *pApi
  4047. ){
  4048. SQLITE_EXTENSION_INIT2(pApi);
  4049. (void)pzErrMsg; /* Unused parameter */
  4050. return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
  4051. }
  4052. /************************* End ../ext/misc/uint.c ********************/
  4053. /************************* Begin ../ext/misc/decimal.c ******************/
  4054. /*
  4055. ** 2020-06-22
  4056. **
  4057. ** The author disclaims copyright to this source code. In place of
  4058. ** a legal notice, here is a blessing:
  4059. **
  4060. ** May you do good and not evil.
  4061. ** May you find forgiveness for yourself and forgive others.
  4062. ** May you share freely, never taking more than you give.
  4063. **
  4064. ******************************************************************************
  4065. **
  4066. ** Routines to implement arbitrary-precision decimal math.
  4067. **
  4068. ** The focus here is on simplicity and correctness, not performance.
  4069. */
  4070. /* #include "sqlite3ext.h" */
  4071. SQLITE_EXTENSION_INIT1
  4072. #include <assert.h>
  4073. #include <string.h>
  4074. #include <ctype.h>
  4075. #include <stdlib.h>
  4076. /* Mark a function parameter as unused, to suppress nuisance compiler
  4077. ** warnings. */
  4078. #ifndef UNUSED_PARAMETER
  4079. # define UNUSED_PARAMETER(X) (void)(X)
  4080. #endif
  4081. /* A decimal object */
  4082. typedef struct Decimal Decimal;
  4083. struct Decimal {
  4084. char sign; /* 0 for positive, 1 for negative */
  4085. char oom; /* True if an OOM is encountered */
  4086. char isNull; /* True if holds a NULL rather than a number */
  4087. char isInit; /* True upon initialization */
  4088. int nDigit; /* Total number of digits */
  4089. int nFrac; /* Number of digits to the right of the decimal point */
  4090. signed char *a; /* Array of digits. Most significant first. */
  4091. };
  4092. /*
  4093. ** Release memory held by a Decimal, but do not free the object itself.
  4094. */
  4095. static void decimal_clear(Decimal *p){
  4096. sqlite3_free(p->a);
  4097. }
  4098. /*
  4099. ** Destroy a Decimal object
  4100. */
  4101. static void decimal_free(Decimal *p){
  4102. if( p ){
  4103. decimal_clear(p);
  4104. sqlite3_free(p);
  4105. }
  4106. }
  4107. /*
  4108. ** Allocate a new Decimal object. Initialize it to the number given
  4109. ** by the input string.
  4110. */
  4111. static Decimal *decimal_new(
  4112. sqlite3_context *pCtx,
  4113. sqlite3_value *pIn,
  4114. int nAlt,
  4115. const unsigned char *zAlt
  4116. ){
  4117. Decimal *p;
  4118. int n, i;
  4119. const unsigned char *zIn;
  4120. int iExp = 0;
  4121. p = sqlite3_malloc( sizeof(*p) );
  4122. if( p==0 ) goto new_no_mem;
  4123. p->sign = 0;
  4124. p->oom = 0;
  4125. p->isInit = 1;
  4126. p->isNull = 0;
  4127. p->nDigit = 0;
  4128. p->nFrac = 0;
  4129. if( zAlt ){
  4130. n = nAlt,
  4131. zIn = zAlt;
  4132. }else{
  4133. if( sqlite3_value_type(pIn)==SQLITE_NULL ){
  4134. p->a = 0;
  4135. p->isNull = 1;
  4136. return p;
  4137. }
  4138. n = sqlite3_value_bytes(pIn);
  4139. zIn = sqlite3_value_text(pIn);
  4140. }
  4141. p->a = sqlite3_malloc64( n+1 );
  4142. if( p->a==0 ) goto new_no_mem;
  4143. for(i=0; isspace(zIn[i]); i++){}
  4144. if( zIn[i]=='-' ){
  4145. p->sign = 1;
  4146. i++;
  4147. }else if( zIn[i]=='+' ){
  4148. i++;
  4149. }
  4150. while( i<n && zIn[i]=='0' ) i++;
  4151. while( i<n ){
  4152. char c = zIn[i];
  4153. if( c>='0' && c<='9' ){
  4154. p->a[p->nDigit++] = c - '0';
  4155. }else if( c=='.' ){
  4156. p->nFrac = p->nDigit + 1;
  4157. }else if( c=='e' || c=='E' ){
  4158. int j = i+1;
  4159. int neg = 0;
  4160. if( j>=n ) break;
  4161. if( zIn[j]=='-' ){
  4162. neg = 1;
  4163. j++;
  4164. }else if( zIn[j]=='+' ){
  4165. j++;
  4166. }
  4167. while( j<n && iExp<1000000 ){
  4168. if( zIn[j]>='0' && zIn[j]<='9' ){
  4169. iExp = iExp*10 + zIn[j] - '0';
  4170. }
  4171. j++;
  4172. }
  4173. if( neg ) iExp = -iExp;
  4174. break;
  4175. }
  4176. i++;
  4177. }
  4178. if( p->nFrac ){
  4179. p->nFrac = p->nDigit - (p->nFrac - 1);
  4180. }
  4181. if( iExp>0 ){
  4182. if( p->nFrac>0 ){
  4183. if( iExp<=p->nFrac ){
  4184. p->nFrac -= iExp;
  4185. iExp = 0;
  4186. }else{
  4187. iExp -= p->nFrac;
  4188. p->nFrac = 0;
  4189. }
  4190. }
  4191. if( iExp>0 ){
  4192. p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
  4193. if( p->a==0 ) goto new_no_mem;
  4194. memset(p->a+p->nDigit, 0, iExp);
  4195. p->nDigit += iExp;
  4196. }
  4197. }else if( iExp<0 ){
  4198. int nExtra;
  4199. iExp = -iExp;
  4200. nExtra = p->nDigit - p->nFrac - 1;
  4201. if( nExtra ){
  4202. if( nExtra>=iExp ){
  4203. p->nFrac += iExp;
  4204. iExp = 0;
  4205. }else{
  4206. iExp -= nExtra;
  4207. p->nFrac = p->nDigit - 1;
  4208. }
  4209. }
  4210. if( iExp>0 ){
  4211. p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
  4212. if( p->a==0 ) goto new_no_mem;
  4213. memmove(p->a+iExp, p->a, p->nDigit);
  4214. memset(p->a, 0, iExp);
  4215. p->nDigit += iExp;
  4216. p->nFrac += iExp;
  4217. }
  4218. }
  4219. return p;
  4220. new_no_mem:
  4221. if( pCtx ) sqlite3_result_error_nomem(pCtx);
  4222. sqlite3_free(p);
  4223. return 0;
  4224. }
  4225. /*
  4226. ** Make the given Decimal the result.
  4227. */
  4228. static void decimal_result(sqlite3_context *pCtx, Decimal *p){
  4229. char *z;
  4230. int i, j;
  4231. int n;
  4232. if( p==0 || p->oom ){
  4233. sqlite3_result_error_nomem(pCtx);
  4234. return;
  4235. }
  4236. if( p->isNull ){
  4237. sqlite3_result_null(pCtx);
  4238. return;
  4239. }
  4240. z = sqlite3_malloc( p->nDigit+4 );
  4241. if( z==0 ){
  4242. sqlite3_result_error_nomem(pCtx);
  4243. return;
  4244. }
  4245. i = 0;
  4246. if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
  4247. p->sign = 0;
  4248. }
  4249. if( p->sign ){
  4250. z[0] = '-';
  4251. i = 1;
  4252. }
  4253. n = p->nDigit - p->nFrac;
  4254. if( n<=0 ){
  4255. z[i++] = '0';
  4256. }
  4257. j = 0;
  4258. while( n>1 && p->a[j]==0 ){
  4259. j++;
  4260. n--;
  4261. }
  4262. while( n>0 ){
  4263. z[i++] = p->a[j] + '0';
  4264. j++;
  4265. n--;
  4266. }
  4267. if( p->nFrac ){
  4268. z[i++] = '.';
  4269. do{
  4270. z[i++] = p->a[j] + '0';
  4271. j++;
  4272. }while( j<p->nDigit );
  4273. }
  4274. z[i] = 0;
  4275. sqlite3_result_text(pCtx, z, i, sqlite3_free);
  4276. }
  4277. /*
  4278. ** SQL Function: decimal(X)
  4279. **
  4280. ** Convert input X into decimal and then back into text
  4281. */
  4282. static void decimalFunc(
  4283. sqlite3_context *context,
  4284. int argc,
  4285. sqlite3_value **argv
  4286. ){
  4287. Decimal *p = decimal_new(context, argv[0], 0, 0);
  4288. UNUSED_PARAMETER(argc);
  4289. decimal_result(context, p);
  4290. decimal_free(p);
  4291. }
  4292. /*
  4293. ** Compare to Decimal objects. Return negative, 0, or positive if the
  4294. ** first object is less than, equal to, or greater than the second.
  4295. **
  4296. ** Preconditions for this routine:
  4297. **
  4298. ** pA!=0
  4299. ** pA->isNull==0
  4300. ** pB!=0
  4301. ** pB->isNull==0
  4302. */
  4303. static int decimal_cmp(const Decimal *pA, const Decimal *pB){
  4304. int nASig, nBSig, rc, n;
  4305. if( pA->sign!=pB->sign ){
  4306. return pA->sign ? -1 : +1;
  4307. }
  4308. if( pA->sign ){
  4309. const Decimal *pTemp = pA;
  4310. pA = pB;
  4311. pB = pTemp;
  4312. }
  4313. nASig = pA->nDigit - pA->nFrac;
  4314. nBSig = pB->nDigit - pB->nFrac;
  4315. if( nASig!=nBSig ){
  4316. return nASig - nBSig;
  4317. }
  4318. n = pA->nDigit;
  4319. if( n>pB->nDigit ) n = pB->nDigit;
  4320. rc = memcmp(pA->a, pB->a, n);
  4321. if( rc==0 ){
  4322. rc = pA->nDigit - pB->nDigit;
  4323. }
  4324. return rc;
  4325. }
  4326. /*
  4327. ** SQL Function: decimal_cmp(X, Y)
  4328. **
  4329. ** Return negative, zero, or positive if X is less then, equal to, or
  4330. ** greater than Y.
  4331. */
  4332. static void decimalCmpFunc(
  4333. sqlite3_context *context,
  4334. int argc,
  4335. sqlite3_value **argv
  4336. ){
  4337. Decimal *pA = 0, *pB = 0;
  4338. int rc;
  4339. UNUSED_PARAMETER(argc);
  4340. pA = decimal_new(context, argv[0], 0, 0);
  4341. if( pA==0 || pA->isNull ) goto cmp_done;
  4342. pB = decimal_new(context, argv[1], 0, 0);
  4343. if( pB==0 || pB->isNull ) goto cmp_done;
  4344. rc = decimal_cmp(pA, pB);
  4345. if( rc<0 ) rc = -1;
  4346. else if( rc>0 ) rc = +1;
  4347. sqlite3_result_int(context, rc);
  4348. cmp_done:
  4349. decimal_free(pA);
  4350. decimal_free(pB);
  4351. }
  4352. /*
  4353. ** Expand the Decimal so that it has a least nDigit digits and nFrac
  4354. ** digits to the right of the decimal point.
  4355. */
  4356. static void decimal_expand(Decimal *p, int nDigit, int nFrac){
  4357. int nAddSig;
  4358. int nAddFrac;
  4359. if( p==0 ) return;
  4360. nAddFrac = nFrac - p->nFrac;
  4361. nAddSig = (nDigit - p->nDigit) - nAddFrac;
  4362. if( nAddFrac==0 && nAddSig==0 ) return;
  4363. p->a = sqlite3_realloc64(p->a, nDigit+1);
  4364. if( p->a==0 ){
  4365. p->oom = 1;
  4366. return;
  4367. }
  4368. if( nAddSig ){
  4369. memmove(p->a+nAddSig, p->a, p->nDigit);
  4370. memset(p->a, 0, nAddSig);
  4371. p->nDigit += nAddSig;
  4372. }
  4373. if( nAddFrac ){
  4374. memset(p->a+p->nDigit, 0, nAddFrac);
  4375. p->nDigit += nAddFrac;
  4376. p->nFrac += nAddFrac;
  4377. }
  4378. }
  4379. /*
  4380. ** Add the value pB into pA.
  4381. **
  4382. ** Both pA and pB might become denormalized by this routine.
  4383. */
  4384. static void decimal_add(Decimal *pA, Decimal *pB){
  4385. int nSig, nFrac, nDigit;
  4386. int i, rc;
  4387. if( pA==0 ){
  4388. return;
  4389. }
  4390. if( pA->oom || pB==0 || pB->oom ){
  4391. pA->oom = 1;
  4392. return;
  4393. }
  4394. if( pA->isNull || pB->isNull ){
  4395. pA->isNull = 1;
  4396. return;
  4397. }
  4398. nSig = pA->nDigit - pA->nFrac;
  4399. if( nSig && pA->a[0]==0 ) nSig--;
  4400. if( nSig<pB->nDigit-pB->nFrac ){
  4401. nSig = pB->nDigit - pB->nFrac;
  4402. }
  4403. nFrac = pA->nFrac;
  4404. if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
  4405. nDigit = nSig + nFrac + 1;
  4406. decimal_expand(pA, nDigit, nFrac);
  4407. decimal_expand(pB, nDigit, nFrac);
  4408. if( pA->oom || pB->oom ){
  4409. pA->oom = 1;
  4410. }else{
  4411. if( pA->sign==pB->sign ){
  4412. int carry = 0;
  4413. for(i=nDigit-1; i>=0; i--){
  4414. int x = pA->a[i] + pB->a[i] + carry;
  4415. if( x>=10 ){
  4416. carry = 1;
  4417. pA->a[i] = x - 10;
  4418. }else{
  4419. carry = 0;
  4420. pA->a[i] = x;
  4421. }
  4422. }
  4423. }else{
  4424. signed char *aA, *aB;
  4425. int borrow = 0;
  4426. rc = memcmp(pA->a, pB->a, nDigit);
  4427. if( rc<0 ){
  4428. aA = pB->a;
  4429. aB = pA->a;
  4430. pA->sign = !pA->sign;
  4431. }else{
  4432. aA = pA->a;
  4433. aB = pB->a;
  4434. }
  4435. for(i=nDigit-1; i>=0; i--){
  4436. int x = aA[i] - aB[i] - borrow;
  4437. if( x<0 ){
  4438. pA->a[i] = x+10;
  4439. borrow = 1;
  4440. }else{
  4441. pA->a[i] = x;
  4442. borrow = 0;
  4443. }
  4444. }
  4445. }
  4446. }
  4447. }
  4448. /*
  4449. ** Compare text in decimal order.
  4450. */
  4451. static int decimalCollFunc(
  4452. void *notUsed,
  4453. int nKey1, const void *pKey1,
  4454. int nKey2, const void *pKey2
  4455. ){
  4456. const unsigned char *zA = (const unsigned char*)pKey1;
  4457. const unsigned char *zB = (const unsigned char*)pKey2;
  4458. Decimal *pA = decimal_new(0, 0, nKey1, zA);
  4459. Decimal *pB = decimal_new(0, 0, nKey2, zB);
  4460. int rc;
  4461. UNUSED_PARAMETER(notUsed);
  4462. if( pA==0 || pB==0 ){
  4463. rc = 0;
  4464. }else{
  4465. rc = decimal_cmp(pA, pB);
  4466. }
  4467. decimal_free(pA);
  4468. decimal_free(pB);
  4469. return rc;
  4470. }
  4471. /*
  4472. ** SQL Function: decimal_add(X, Y)
  4473. ** decimal_sub(X, Y)
  4474. **
  4475. ** Return the sum or difference of X and Y.
  4476. */
  4477. static void decimalAddFunc(
  4478. sqlite3_context *context,
  4479. int argc,
  4480. sqlite3_value **argv
  4481. ){
  4482. Decimal *pA = decimal_new(context, argv[0], 0, 0);
  4483. Decimal *pB = decimal_new(context, argv[1], 0, 0);
  4484. UNUSED_PARAMETER(argc);
  4485. decimal_add(pA, pB);
  4486. decimal_result(context, pA);
  4487. decimal_free(pA);
  4488. decimal_free(pB);
  4489. }
  4490. static void decimalSubFunc(
  4491. sqlite3_context *context,
  4492. int argc,
  4493. sqlite3_value **argv
  4494. ){
  4495. Decimal *pA = decimal_new(context, argv[0], 0, 0);
  4496. Decimal *pB = decimal_new(context, argv[1], 0, 0);
  4497. UNUSED_PARAMETER(argc);
  4498. if( pB==0 ) return;
  4499. pB->sign = !pB->sign;
  4500. decimal_add(pA, pB);
  4501. decimal_result(context, pA);
  4502. decimal_free(pA);
  4503. decimal_free(pB);
  4504. }
  4505. /* Aggregate funcion: decimal_sum(X)
  4506. **
  4507. ** Works like sum() except that it uses decimal arithmetic for unlimited
  4508. ** precision.
  4509. */
  4510. static void decimalSumStep(
  4511. sqlite3_context *context,
  4512. int argc,
  4513. sqlite3_value **argv
  4514. ){
  4515. Decimal *p;
  4516. Decimal *pArg;
  4517. UNUSED_PARAMETER(argc);
  4518. p = sqlite3_aggregate_context(context, sizeof(*p));
  4519. if( p==0 ) return;
  4520. if( !p->isInit ){
  4521. p->isInit = 1;
  4522. p->a = sqlite3_malloc(2);
  4523. if( p->a==0 ){
  4524. p->oom = 1;
  4525. }else{
  4526. p->a[0] = 0;
  4527. }
  4528. p->nDigit = 1;
  4529. p->nFrac = 0;
  4530. }
  4531. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  4532. pArg = decimal_new(context, argv[0], 0, 0);
  4533. decimal_add(p, pArg);
  4534. decimal_free(pArg);
  4535. }
  4536. static void decimalSumInverse(
  4537. sqlite3_context *context,
  4538. int argc,
  4539. sqlite3_value **argv
  4540. ){
  4541. Decimal *p;
  4542. Decimal *pArg;
  4543. UNUSED_PARAMETER(argc);
  4544. p = sqlite3_aggregate_context(context, sizeof(*p));
  4545. if( p==0 ) return;
  4546. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  4547. pArg = decimal_new(context, argv[0], 0, 0);
  4548. if( pArg ) pArg->sign = !pArg->sign;
  4549. decimal_add(p, pArg);
  4550. decimal_free(pArg);
  4551. }
  4552. static void decimalSumValue(sqlite3_context *context){
  4553. Decimal *p = sqlite3_aggregate_context(context, 0);
  4554. if( p==0 ) return;
  4555. decimal_result(context, p);
  4556. }
  4557. static void decimalSumFinalize(sqlite3_context *context){
  4558. Decimal *p = sqlite3_aggregate_context(context, 0);
  4559. if( p==0 ) return;
  4560. decimal_result(context, p);
  4561. decimal_clear(p);
  4562. }
  4563. /*
  4564. ** SQL Function: decimal_mul(X, Y)
  4565. **
  4566. ** Return the product of X and Y.
  4567. **
  4568. ** All significant digits after the decimal point are retained.
  4569. ** Trailing zeros after the decimal point are omitted as long as
  4570. ** the number of digits after the decimal point is no less than
  4571. ** either the number of digits in either input.
  4572. */
  4573. static void decimalMulFunc(
  4574. sqlite3_context *context,
  4575. int argc,
  4576. sqlite3_value **argv
  4577. ){
  4578. Decimal *pA = decimal_new(context, argv[0], 0, 0);
  4579. Decimal *pB = decimal_new(context, argv[1], 0, 0);
  4580. signed char *acc = 0;
  4581. int i, j, k;
  4582. int minFrac;
  4583. UNUSED_PARAMETER(argc);
  4584. if( pA==0 || pA->oom || pA->isNull
  4585. || pB==0 || pB->oom || pB->isNull
  4586. ){
  4587. goto mul_end;
  4588. }
  4589. acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
  4590. if( acc==0 ){
  4591. sqlite3_result_error_nomem(context);
  4592. goto mul_end;
  4593. }
  4594. memset(acc, 0, pA->nDigit + pB->nDigit + 2);
  4595. minFrac = pA->nFrac;
  4596. if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
  4597. for(i=pA->nDigit-1; i>=0; i--){
  4598. signed char f = pA->a[i];
  4599. int carry = 0, x;
  4600. for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
  4601. x = acc[k] + f*pB->a[j] + carry;
  4602. acc[k] = x%10;
  4603. carry = x/10;
  4604. }
  4605. x = acc[k] + carry;
  4606. acc[k] = x%10;
  4607. acc[k-1] += x/10;
  4608. }
  4609. sqlite3_free(pA->a);
  4610. pA->a = acc;
  4611. acc = 0;
  4612. pA->nDigit += pB->nDigit + 2;
  4613. pA->nFrac += pB->nFrac;
  4614. pA->sign ^= pB->sign;
  4615. while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
  4616. pA->nFrac--;
  4617. pA->nDigit--;
  4618. }
  4619. decimal_result(context, pA);
  4620. mul_end:
  4621. sqlite3_free(acc);
  4622. decimal_free(pA);
  4623. decimal_free(pB);
  4624. }
  4625. #ifdef _WIN32
  4626. #endif
  4627. int sqlite3_decimal_init(
  4628. sqlite3 *db,
  4629. char **pzErrMsg,
  4630. const sqlite3_api_routines *pApi
  4631. ){
  4632. int rc = SQLITE_OK;
  4633. static const struct {
  4634. const char *zFuncName;
  4635. int nArg;
  4636. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  4637. } aFunc[] = {
  4638. { "decimal", 1, decimalFunc },
  4639. { "decimal_cmp", 2, decimalCmpFunc },
  4640. { "decimal_add", 2, decimalAddFunc },
  4641. { "decimal_sub", 2, decimalSubFunc },
  4642. { "decimal_mul", 2, decimalMulFunc },
  4643. };
  4644. unsigned int i;
  4645. (void)pzErrMsg; /* Unused parameter */
  4646. SQLITE_EXTENSION_INIT2(pApi);
  4647. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  4648. rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
  4649. SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
  4650. 0, aFunc[i].xFunc, 0, 0);
  4651. }
  4652. if( rc==SQLITE_OK ){
  4653. rc = sqlite3_create_window_function(db, "decimal_sum", 1,
  4654. SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
  4655. decimalSumStep, decimalSumFinalize,
  4656. decimalSumValue, decimalSumInverse, 0);
  4657. }
  4658. if( rc==SQLITE_OK ){
  4659. rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
  4660. 0, decimalCollFunc);
  4661. }
  4662. return rc;
  4663. }
  4664. /************************* End ../ext/misc/decimal.c ********************/
  4665. /************************* Begin ../ext/misc/ieee754.c ******************/
  4666. /*
  4667. ** 2013-04-17
  4668. **
  4669. ** The author disclaims copyright to this source code. In place of
  4670. ** a legal notice, here is a blessing:
  4671. **
  4672. ** May you do good and not evil.
  4673. ** May you find forgiveness for yourself and forgive others.
  4674. ** May you share freely, never taking more than you give.
  4675. **
  4676. ******************************************************************************
  4677. **
  4678. ** This SQLite extension implements functions for the exact display
  4679. ** and input of IEEE754 Binary64 floating-point numbers.
  4680. **
  4681. ** ieee754(X)
  4682. ** ieee754(Y,Z)
  4683. **
  4684. ** In the first form, the value X should be a floating-point number.
  4685. ** The function will return a string of the form 'ieee754(Y,Z)' where
  4686. ** Y and Z are integers such that X==Y*pow(2,Z).
  4687. **
  4688. ** In the second form, Y and Z are integers which are the mantissa and
  4689. ** base-2 exponent of a new floating point number. The function returns
  4690. ** a floating-point value equal to Y*pow(2,Z).
  4691. **
  4692. ** Examples:
  4693. **
  4694. ** ieee754(2.0) -> 'ieee754(2,0)'
  4695. ** ieee754(45.25) -> 'ieee754(181,-2)'
  4696. ** ieee754(2, 0) -> 2.0
  4697. ** ieee754(181, -2) -> 45.25
  4698. **
  4699. ** Two additional functions break apart the one-argument ieee754()
  4700. ** result into separate integer values:
  4701. **
  4702. ** ieee754_mantissa(45.25) -> 181
  4703. ** ieee754_exponent(45.25) -> -2
  4704. **
  4705. ** These functions convert binary64 numbers into blobs and back again.
  4706. **
  4707. ** ieee754_from_blob(x'3ff0000000000000') -> 1.0
  4708. ** ieee754_to_blob(1.0) -> x'3ff0000000000000'
  4709. **
  4710. ** In all single-argument functions, if the argument is an 8-byte blob
  4711. ** then that blob is interpreted as a big-endian binary64 value.
  4712. **
  4713. **
  4714. ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
  4715. ** -----------------------------------------------
  4716. **
  4717. ** This extension in combination with the separate 'decimal' extension
  4718. ** can be used to compute the exact decimal representation of binary64
  4719. ** values. To begin, first compute a table of exponent values:
  4720. **
  4721. ** CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
  4722. ** WITH RECURSIVE c(x,v) AS (
  4723. ** VALUES(0,'1')
  4724. ** UNION ALL
  4725. ** SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
  4726. ** ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
  4727. ** WITH RECURSIVE c(x,v) AS (
  4728. ** VALUES(-1,'0.5')
  4729. ** UNION ALL
  4730. ** SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
  4731. ** ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
  4732. **
  4733. ** Then, to compute the exact decimal representation of a floating
  4734. ** point value (the value 47.49 is used in the example) do:
  4735. **
  4736. ** WITH c(n) AS (VALUES(47.49))
  4737. ** ---------------^^^^^---- Replace with whatever you want
  4738. ** SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
  4739. ** FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
  4740. **
  4741. ** Here is a query to show various boundry values for the binary64
  4742. ** number format:
  4743. **
  4744. ** WITH c(name,bin) AS (VALUES
  4745. ** ('minimum positive value', x'0000000000000001'),
  4746. ** ('maximum subnormal value', x'000fffffffffffff'),
  4747. ** ('mininum positive nornal value', x'0010000000000000'),
  4748. ** ('maximum value', x'7fefffffffffffff'))
  4749. ** SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
  4750. ** FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
  4751. **
  4752. */
  4753. /* #include "sqlite3ext.h" */
  4754. SQLITE_EXTENSION_INIT1
  4755. #include <assert.h>
  4756. #include <string.h>
  4757. /* Mark a function parameter as unused, to suppress nuisance compiler
  4758. ** warnings. */
  4759. #ifndef UNUSED_PARAMETER
  4760. # define UNUSED_PARAMETER(X) (void)(X)
  4761. #endif
  4762. /*
  4763. ** Implementation of the ieee754() function
  4764. */
  4765. static void ieee754func(
  4766. sqlite3_context *context,
  4767. int argc,
  4768. sqlite3_value **argv
  4769. ){
  4770. if( argc==1 ){
  4771. sqlite3_int64 m, a;
  4772. double r;
  4773. int e;
  4774. int isNeg;
  4775. char zResult[100];
  4776. assert( sizeof(m)==sizeof(r) );
  4777. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  4778. && sqlite3_value_bytes(argv[0])==sizeof(r)
  4779. ){
  4780. const unsigned char *x = sqlite3_value_blob(argv[0]);
  4781. unsigned int i;
  4782. sqlite3_uint64 v = 0;
  4783. for(i=0; i<sizeof(r); i++){
  4784. v = (v<<8) | x[i];
  4785. }
  4786. memcpy(&r, &v, sizeof(r));
  4787. }else{
  4788. r = sqlite3_value_double(argv[0]);
  4789. }
  4790. if( r<0.0 ){
  4791. isNeg = 1;
  4792. r = -r;
  4793. }else{
  4794. isNeg = 0;
  4795. }
  4796. memcpy(&a,&r,sizeof(a));
  4797. if( a==0 ){
  4798. e = 0;
  4799. m = 0;
  4800. }else{
  4801. e = a>>52;
  4802. m = a & ((((sqlite3_int64)1)<<52)-1);
  4803. if( e==0 ){
  4804. m <<= 1;
  4805. }else{
  4806. m |= ((sqlite3_int64)1)<<52;
  4807. }
  4808. while( e<1075 && m>0 && (m&1)==0 ){
  4809. m >>= 1;
  4810. e++;
  4811. }
  4812. if( isNeg ) m = -m;
  4813. }
  4814. switch( *(int*)sqlite3_user_data(context) ){
  4815. case 0:
  4816. sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
  4817. m, e-1075);
  4818. sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
  4819. break;
  4820. case 1:
  4821. sqlite3_result_int64(context, m);
  4822. break;
  4823. case 2:
  4824. sqlite3_result_int(context, e-1075);
  4825. break;
  4826. }
  4827. }else{
  4828. sqlite3_int64 m, e, a;
  4829. double r;
  4830. int isNeg = 0;
  4831. m = sqlite3_value_int64(argv[0]);
  4832. e = sqlite3_value_int64(argv[1]);
  4833. if( m<0 ){
  4834. isNeg = 1;
  4835. m = -m;
  4836. if( m<0 ) return;
  4837. }else if( m==0 && e>-1000 && e<1000 ){
  4838. sqlite3_result_double(context, 0.0);
  4839. return;
  4840. }
  4841. while( (m>>32)&0xffe00000 ){
  4842. m >>= 1;
  4843. e++;
  4844. }
  4845. while( m!=0 && ((m>>32)&0xfff00000)==0 ){
  4846. m <<= 1;
  4847. e--;
  4848. }
  4849. e += 1075;
  4850. if( e<=0 ){
  4851. /* Subnormal */
  4852. m >>= 1-e;
  4853. e = 0;
  4854. }else if( e>0x7ff ){
  4855. e = 0x7ff;
  4856. }
  4857. a = m & ((((sqlite3_int64)1)<<52)-1);
  4858. a |= e<<52;
  4859. if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
  4860. memcpy(&r, &a, sizeof(r));
  4861. sqlite3_result_double(context, r);
  4862. }
  4863. }
  4864. /*
  4865. ** Functions to convert between blobs and floats.
  4866. */
  4867. static void ieee754func_from_blob(
  4868. sqlite3_context *context,
  4869. int argc,
  4870. sqlite3_value **argv
  4871. ){
  4872. UNUSED_PARAMETER(argc);
  4873. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  4874. && sqlite3_value_bytes(argv[0])==sizeof(double)
  4875. ){
  4876. double r;
  4877. const unsigned char *x = sqlite3_value_blob(argv[0]);
  4878. unsigned int i;
  4879. sqlite3_uint64 v = 0;
  4880. for(i=0; i<sizeof(r); i++){
  4881. v = (v<<8) | x[i];
  4882. }
  4883. memcpy(&r, &v, sizeof(r));
  4884. sqlite3_result_double(context, r);
  4885. }
  4886. }
  4887. static void ieee754func_to_blob(
  4888. sqlite3_context *context,
  4889. int argc,
  4890. sqlite3_value **argv
  4891. ){
  4892. UNUSED_PARAMETER(argc);
  4893. if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
  4894. || sqlite3_value_type(argv[0])==SQLITE_INTEGER
  4895. ){
  4896. double r = sqlite3_value_double(argv[0]);
  4897. sqlite3_uint64 v;
  4898. unsigned char a[sizeof(r)];
  4899. unsigned int i;
  4900. memcpy(&v, &r, sizeof(r));
  4901. for(i=1; i<=sizeof(r); i++){
  4902. a[sizeof(r)-i] = v&0xff;
  4903. v >>= 8;
  4904. }
  4905. sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
  4906. }
  4907. }
  4908. #ifdef _WIN32
  4909. #endif
  4910. int sqlite3_ieee_init(
  4911. sqlite3 *db,
  4912. char **pzErrMsg,
  4913. const sqlite3_api_routines *pApi
  4914. ){
  4915. static const struct {
  4916. char *zFName;
  4917. int nArg;
  4918. int iAux;
  4919. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  4920. } aFunc[] = {
  4921. { "ieee754", 1, 0, ieee754func },
  4922. { "ieee754", 2, 0, ieee754func },
  4923. { "ieee754_mantissa", 1, 1, ieee754func },
  4924. { "ieee754_exponent", 1, 2, ieee754func },
  4925. { "ieee754_to_blob", 1, 0, ieee754func_to_blob },
  4926. { "ieee754_from_blob", 1, 0, ieee754func_from_blob },
  4927. };
  4928. unsigned int i;
  4929. int rc = SQLITE_OK;
  4930. SQLITE_EXTENSION_INIT2(pApi);
  4931. (void)pzErrMsg; /* Unused parameter */
  4932. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  4933. rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
  4934. SQLITE_UTF8|SQLITE_INNOCUOUS,
  4935. (void*)&aFunc[i].iAux,
  4936. aFunc[i].xFunc, 0, 0);
  4937. }
  4938. return rc;
  4939. }
  4940. /************************* End ../ext/misc/ieee754.c ********************/
  4941. #ifdef SQLITE_HAVE_ZLIB
  4942. /************************* Begin ../ext/misc/zipfile.c ******************/
  4943. /*
  4944. ** 2017-12-26
  4945. **
  4946. ** The author disclaims copyright to this source code. In place of
  4947. ** a legal notice, here is a blessing:
  4948. **
  4949. ** May you do good and not evil.
  4950. ** May you find forgiveness for yourself and forgive others.
  4951. ** May you share freely, never taking more than you give.
  4952. **
  4953. ******************************************************************************
  4954. **
  4955. ** This file implements a virtual table for reading and writing ZIP archive
  4956. ** files.
  4957. **
  4958. ** Usage example:
  4959. **
  4960. ** SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
  4961. **
  4962. ** Current limitations:
  4963. **
  4964. ** * No support for encryption
  4965. ** * No support for ZIP archives spanning multiple files
  4966. ** * No support for zip64 extensions
  4967. ** * Only the "inflate/deflate" (zlib) compression method is supported
  4968. */
  4969. /* #include "sqlite3ext.h" */
  4970. SQLITE_EXTENSION_INIT1
  4971. #include <stdio.h>
  4972. #include <string.h>
  4973. #include <assert.h>
  4974. #include <zlib.h>
  4975. #ifndef SQLITE_OMIT_VIRTUALTABLE
  4976. #ifndef SQLITE_AMALGAMATION
  4977. /* typedef sqlite3_int64 i64; */
  4978. /* typedef unsigned char u8; */
  4979. typedef unsigned short u16;
  4980. typedef unsigned long u32;
  4981. #define MIN(a,b) ((a)<(b) ? (a) : (b))
  4982. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  4983. # define ALWAYS(X) (1)
  4984. # define NEVER(X) (0)
  4985. #elif !defined(NDEBUG)
  4986. # define ALWAYS(X) ((X)?1:(assert(0),0))
  4987. # define NEVER(X) ((X)?(assert(0),1):0)
  4988. #else
  4989. # define ALWAYS(X) (X)
  4990. # define NEVER(X) (X)
  4991. #endif
  4992. #endif /* SQLITE_AMALGAMATION */
  4993. /*
  4994. ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
  4995. **
  4996. ** In some ways it would be better to obtain these values from system
  4997. ** header files. But, the dependency is undesirable and (a) these
  4998. ** have been stable for decades, (b) the values are part of POSIX and
  4999. ** are also made explicit in [man stat], and (c) are part of the
  5000. ** file format for zip archives.
  5001. */
  5002. #ifndef S_IFDIR
  5003. # define S_IFDIR 0040000
  5004. #endif
  5005. #ifndef S_IFREG
  5006. # define S_IFREG 0100000
  5007. #endif
  5008. #ifndef S_IFLNK
  5009. # define S_IFLNK 0120000
  5010. #endif
  5011. static const char ZIPFILE_SCHEMA[] =
  5012. "CREATE TABLE y("
  5013. "name PRIMARY KEY," /* 0: Name of file in zip archive */
  5014. "mode," /* 1: POSIX mode for file */
  5015. "mtime," /* 2: Last modification time (secs since 1970)*/
  5016. "sz," /* 3: Size of object */
  5017. "rawdata," /* 4: Raw data */
  5018. "data," /* 5: Uncompressed data */
  5019. "method," /* 6: Compression method (integer) */
  5020. "z HIDDEN" /* 7: Name of zip file */
  5021. ") WITHOUT ROWID;";
  5022. #define ZIPFILE_F_COLUMN_IDX 7 /* Index of column "file" in the above */
  5023. #define ZIPFILE_BUFFER_SIZE (64*1024)
  5024. /*
  5025. ** Magic numbers used to read and write zip files.
  5026. **
  5027. ** ZIPFILE_NEWENTRY_MADEBY:
  5028. ** Use this value for the "version-made-by" field in new zip file
  5029. ** entries. The upper byte indicates "unix", and the lower byte
  5030. ** indicates that the zip file matches pkzip specification 3.0.
  5031. ** This is what info-zip seems to do.
  5032. **
  5033. ** ZIPFILE_NEWENTRY_REQUIRED:
  5034. ** Value for "version-required-to-extract" field of new entries.
  5035. ** Version 2.0 is required to support folders and deflate compression.
  5036. **
  5037. ** ZIPFILE_NEWENTRY_FLAGS:
  5038. ** Value for "general-purpose-bit-flags" field of new entries. Bit
  5039. ** 11 means "utf-8 filename and comment".
  5040. **
  5041. ** ZIPFILE_SIGNATURE_CDS:
  5042. ** First 4 bytes of a valid CDS record.
  5043. **
  5044. ** ZIPFILE_SIGNATURE_LFH:
  5045. ** First 4 bytes of a valid LFH record.
  5046. **
  5047. ** ZIPFILE_SIGNATURE_EOCD
  5048. ** First 4 bytes of a valid EOCD record.
  5049. */
  5050. #define ZIPFILE_EXTRA_TIMESTAMP 0x5455
  5051. #define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30)
  5052. #define ZIPFILE_NEWENTRY_REQUIRED 20
  5053. #define ZIPFILE_NEWENTRY_FLAGS 0x800
  5054. #define ZIPFILE_SIGNATURE_CDS 0x02014b50
  5055. #define ZIPFILE_SIGNATURE_LFH 0x04034b50
  5056. #define ZIPFILE_SIGNATURE_EOCD 0x06054b50
  5057. /*
  5058. ** The sizes of the fixed-size part of each of the three main data
  5059. ** structures in a zip archive.
  5060. */
  5061. #define ZIPFILE_LFH_FIXED_SZ 30
  5062. #define ZIPFILE_EOCD_FIXED_SZ 22
  5063. #define ZIPFILE_CDS_FIXED_SZ 46
  5064. /*
  5065. *** 4.3.16 End of central directory record:
  5066. ***
  5067. *** end of central dir signature 4 bytes (0x06054b50)
  5068. *** number of this disk 2 bytes
  5069. *** number of the disk with the
  5070. *** start of the central directory 2 bytes
  5071. *** total number of entries in the
  5072. *** central directory on this disk 2 bytes
  5073. *** total number of entries in
  5074. *** the central directory 2 bytes
  5075. *** size of the central directory 4 bytes
  5076. *** offset of start of central
  5077. *** directory with respect to
  5078. *** the starting disk number 4 bytes
  5079. *** .ZIP file comment length 2 bytes
  5080. *** .ZIP file comment (variable size)
  5081. */
  5082. typedef struct ZipfileEOCD ZipfileEOCD;
  5083. struct ZipfileEOCD {
  5084. u16 iDisk;
  5085. u16 iFirstDisk;
  5086. u16 nEntry;
  5087. u16 nEntryTotal;
  5088. u32 nSize;
  5089. u32 iOffset;
  5090. };
  5091. /*
  5092. *** 4.3.12 Central directory structure:
  5093. ***
  5094. *** ...
  5095. ***
  5096. *** central file header signature 4 bytes (0x02014b50)
  5097. *** version made by 2 bytes
  5098. *** version needed to extract 2 bytes
  5099. *** general purpose bit flag 2 bytes
  5100. *** compression method 2 bytes
  5101. *** last mod file time 2 bytes
  5102. *** last mod file date 2 bytes
  5103. *** crc-32 4 bytes
  5104. *** compressed size 4 bytes
  5105. *** uncompressed size 4 bytes
  5106. *** file name length 2 bytes
  5107. *** extra field length 2 bytes
  5108. *** file comment length 2 bytes
  5109. *** disk number start 2 bytes
  5110. *** internal file attributes 2 bytes
  5111. *** external file attributes 4 bytes
  5112. *** relative offset of local header 4 bytes
  5113. */
  5114. typedef struct ZipfileCDS ZipfileCDS;
  5115. struct ZipfileCDS {
  5116. u16 iVersionMadeBy;
  5117. u16 iVersionExtract;
  5118. u16 flags;
  5119. u16 iCompression;
  5120. u16 mTime;
  5121. u16 mDate;
  5122. u32 crc32;
  5123. u32 szCompressed;
  5124. u32 szUncompressed;
  5125. u16 nFile;
  5126. u16 nExtra;
  5127. u16 nComment;
  5128. u16 iDiskStart;
  5129. u16 iInternalAttr;
  5130. u32 iExternalAttr;
  5131. u32 iOffset;
  5132. char *zFile; /* Filename (sqlite3_malloc()) */
  5133. };
  5134. /*
  5135. *** 4.3.7 Local file header:
  5136. ***
  5137. *** local file header signature 4 bytes (0x04034b50)
  5138. *** version needed to extract 2 bytes
  5139. *** general purpose bit flag 2 bytes
  5140. *** compression method 2 bytes
  5141. *** last mod file time 2 bytes
  5142. *** last mod file date 2 bytes
  5143. *** crc-32 4 bytes
  5144. *** compressed size 4 bytes
  5145. *** uncompressed size 4 bytes
  5146. *** file name length 2 bytes
  5147. *** extra field length 2 bytes
  5148. ***
  5149. */
  5150. typedef struct ZipfileLFH ZipfileLFH;
  5151. struct ZipfileLFH {
  5152. u16 iVersionExtract;
  5153. u16 flags;
  5154. u16 iCompression;
  5155. u16 mTime;
  5156. u16 mDate;
  5157. u32 crc32;
  5158. u32 szCompressed;
  5159. u32 szUncompressed;
  5160. u16 nFile;
  5161. u16 nExtra;
  5162. };
  5163. typedef struct ZipfileEntry ZipfileEntry;
  5164. struct ZipfileEntry {
  5165. ZipfileCDS cds; /* Parsed CDS record */
  5166. u32 mUnixTime; /* Modification time, in UNIX format */
  5167. u8 *aExtra; /* cds.nExtra+cds.nComment bytes of extra data */
  5168. i64 iDataOff; /* Offset to data in file (if aData==0) */
  5169. u8 *aData; /* cds.szCompressed bytes of compressed data */
  5170. ZipfileEntry *pNext; /* Next element in in-memory CDS */
  5171. };
  5172. /*
  5173. ** Cursor type for zipfile tables.
  5174. */
  5175. typedef struct ZipfileCsr ZipfileCsr;
  5176. struct ZipfileCsr {
  5177. sqlite3_vtab_cursor base; /* Base class - must be first */
  5178. i64 iId; /* Cursor ID */
  5179. u8 bEof; /* True when at EOF */
  5180. u8 bNoop; /* If next xNext() call is no-op */
  5181. /* Used outside of write transactions */
  5182. FILE *pFile; /* Zip file */
  5183. i64 iNextOff; /* Offset of next record in central directory */
  5184. ZipfileEOCD eocd; /* Parse of central directory record */
  5185. ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */
  5186. ZipfileEntry *pCurrent; /* Current entry */
  5187. ZipfileCsr *pCsrNext; /* Next cursor on same virtual table */
  5188. };
  5189. typedef struct ZipfileTab ZipfileTab;
  5190. struct ZipfileTab {
  5191. sqlite3_vtab base; /* Base class - must be first */
  5192. char *zFile; /* Zip file this table accesses (may be NULL) */
  5193. sqlite3 *db; /* Host database connection */
  5194. u8 *aBuffer; /* Temporary buffer used for various tasks */
  5195. ZipfileCsr *pCsrList; /* List of cursors */
  5196. i64 iNextCsrid;
  5197. /* The following are used by write transactions only */
  5198. ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
  5199. ZipfileEntry *pLastEntry; /* Last element in pFirstEntry list */
  5200. FILE *pWriteFd; /* File handle open on zip archive */
  5201. i64 szCurrent; /* Current size of zip archive */
  5202. i64 szOrig; /* Size of archive at start of transaction */
  5203. };
  5204. /*
  5205. ** Set the error message contained in context ctx to the results of
  5206. ** vprintf(zFmt, ...).
  5207. */
  5208. static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
  5209. char *zMsg = 0;
  5210. va_list ap;
  5211. va_start(ap, zFmt);
  5212. zMsg = sqlite3_vmprintf(zFmt, ap);
  5213. sqlite3_result_error(ctx, zMsg, -1);
  5214. sqlite3_free(zMsg);
  5215. va_end(ap);
  5216. }
  5217. /*
  5218. ** If string zIn is quoted, dequote it in place. Otherwise, if the string
  5219. ** is not quoted, do nothing.
  5220. */
  5221. static void zipfileDequote(char *zIn){
  5222. char q = zIn[0];
  5223. if( q=='"' || q=='\'' || q=='`' || q=='[' ){
  5224. int iIn = 1;
  5225. int iOut = 0;
  5226. if( q=='[' ) q = ']';
  5227. while( ALWAYS(zIn[iIn]) ){
  5228. char c = zIn[iIn++];
  5229. if( c==q && zIn[iIn++]!=q ) break;
  5230. zIn[iOut++] = c;
  5231. }
  5232. zIn[iOut] = '\0';
  5233. }
  5234. }
  5235. /*
  5236. ** Construct a new ZipfileTab virtual table object.
  5237. **
  5238. ** argv[0] -> module name ("zipfile")
  5239. ** argv[1] -> database name
  5240. ** argv[2] -> table name
  5241. ** argv[...] -> "column name" and other module argument fields.
  5242. */
  5243. static int zipfileConnect(
  5244. sqlite3 *db,
  5245. void *pAux,
  5246. int argc, const char *const*argv,
  5247. sqlite3_vtab **ppVtab,
  5248. char **pzErr
  5249. ){
  5250. int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
  5251. int nFile = 0;
  5252. const char *zFile = 0;
  5253. ZipfileTab *pNew = 0;
  5254. int rc;
  5255. /* If the table name is not "zipfile", require that the argument be
  5256. ** specified. This stops zipfile tables from being created as:
  5257. **
  5258. ** CREATE VIRTUAL TABLE zzz USING zipfile();
  5259. **
  5260. ** It does not prevent:
  5261. **
  5262. ** CREATE VIRTUAL TABLE zipfile USING zipfile();
  5263. */
  5264. assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
  5265. if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
  5266. *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
  5267. return SQLITE_ERROR;
  5268. }
  5269. if( argc>3 ){
  5270. zFile = argv[3];
  5271. nFile = (int)strlen(zFile)+1;
  5272. }
  5273. rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
  5274. if( rc==SQLITE_OK ){
  5275. pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
  5276. if( pNew==0 ) return SQLITE_NOMEM;
  5277. memset(pNew, 0, nByte+nFile);
  5278. pNew->db = db;
  5279. pNew->aBuffer = (u8*)&pNew[1];
  5280. if( zFile ){
  5281. pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
  5282. memcpy(pNew->zFile, zFile, nFile);
  5283. zipfileDequote(pNew->zFile);
  5284. }
  5285. }
  5286. sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
  5287. *ppVtab = (sqlite3_vtab*)pNew;
  5288. return rc;
  5289. }
  5290. /*
  5291. ** Free the ZipfileEntry structure indicated by the only argument.
  5292. */
  5293. static void zipfileEntryFree(ZipfileEntry *p){
  5294. if( p ){
  5295. sqlite3_free(p->cds.zFile);
  5296. sqlite3_free(p);
  5297. }
  5298. }
  5299. /*
  5300. ** Release resources that should be freed at the end of a write
  5301. ** transaction.
  5302. */
  5303. static void zipfileCleanupTransaction(ZipfileTab *pTab){
  5304. ZipfileEntry *pEntry;
  5305. ZipfileEntry *pNext;
  5306. if( pTab->pWriteFd ){
  5307. fclose(pTab->pWriteFd);
  5308. pTab->pWriteFd = 0;
  5309. }
  5310. for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
  5311. pNext = pEntry->pNext;
  5312. zipfileEntryFree(pEntry);
  5313. }
  5314. pTab->pFirstEntry = 0;
  5315. pTab->pLastEntry = 0;
  5316. pTab->szCurrent = 0;
  5317. pTab->szOrig = 0;
  5318. }
  5319. /*
  5320. ** This method is the destructor for zipfile vtab objects.
  5321. */
  5322. static int zipfileDisconnect(sqlite3_vtab *pVtab){
  5323. zipfileCleanupTransaction((ZipfileTab*)pVtab);
  5324. sqlite3_free(pVtab);
  5325. return SQLITE_OK;
  5326. }
  5327. /*
  5328. ** Constructor for a new ZipfileCsr object.
  5329. */
  5330. static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
  5331. ZipfileTab *pTab = (ZipfileTab*)p;
  5332. ZipfileCsr *pCsr;
  5333. pCsr = sqlite3_malloc(sizeof(*pCsr));
  5334. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  5335. if( pCsr==0 ){
  5336. return SQLITE_NOMEM;
  5337. }
  5338. memset(pCsr, 0, sizeof(*pCsr));
  5339. pCsr->iId = ++pTab->iNextCsrid;
  5340. pCsr->pCsrNext = pTab->pCsrList;
  5341. pTab->pCsrList = pCsr;
  5342. return SQLITE_OK;
  5343. }
  5344. /*
  5345. ** Reset a cursor back to the state it was in when first returned
  5346. ** by zipfileOpen().
  5347. */
  5348. static void zipfileResetCursor(ZipfileCsr *pCsr){
  5349. ZipfileEntry *p;
  5350. ZipfileEntry *pNext;
  5351. pCsr->bEof = 0;
  5352. if( pCsr->pFile ){
  5353. fclose(pCsr->pFile);
  5354. pCsr->pFile = 0;
  5355. zipfileEntryFree(pCsr->pCurrent);
  5356. pCsr->pCurrent = 0;
  5357. }
  5358. for(p=pCsr->pFreeEntry; p; p=pNext){
  5359. pNext = p->pNext;
  5360. zipfileEntryFree(p);
  5361. }
  5362. }
  5363. /*
  5364. ** Destructor for an ZipfileCsr.
  5365. */
  5366. static int zipfileClose(sqlite3_vtab_cursor *cur){
  5367. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  5368. ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
  5369. ZipfileCsr **pp;
  5370. zipfileResetCursor(pCsr);
  5371. /* Remove this cursor from the ZipfileTab.pCsrList list. */
  5372. for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
  5373. *pp = pCsr->pCsrNext;
  5374. sqlite3_free(pCsr);
  5375. return SQLITE_OK;
  5376. }
  5377. /*
  5378. ** Set the error message for the virtual table associated with cursor
  5379. ** pCsr to the results of vprintf(zFmt, ...).
  5380. */
  5381. static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
  5382. va_list ap;
  5383. va_start(ap, zFmt);
  5384. sqlite3_free(pTab->base.zErrMsg);
  5385. pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
  5386. va_end(ap);
  5387. }
  5388. static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
  5389. va_list ap;
  5390. va_start(ap, zFmt);
  5391. sqlite3_free(pCsr->base.pVtab->zErrMsg);
  5392. pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
  5393. va_end(ap);
  5394. }
  5395. /*
  5396. ** Read nRead bytes of data from offset iOff of file pFile into buffer
  5397. ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
  5398. ** otherwise.
  5399. **
  5400. ** If an error does occur, output variable (*pzErrmsg) may be set to point
  5401. ** to an English language error message. It is the responsibility of the
  5402. ** caller to eventually free this buffer using
  5403. ** sqlite3_free().
  5404. */
  5405. static int zipfileReadData(
  5406. FILE *pFile, /* Read from this file */
  5407. u8 *aRead, /* Read into this buffer */
  5408. int nRead, /* Number of bytes to read */
  5409. i64 iOff, /* Offset to read from */
  5410. char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */
  5411. ){
  5412. size_t n;
  5413. fseek(pFile, (long)iOff, SEEK_SET);
  5414. n = fread(aRead, 1, nRead, pFile);
  5415. if( (int)n!=nRead ){
  5416. *pzErrmsg = sqlite3_mprintf("error in fread()");
  5417. return SQLITE_ERROR;
  5418. }
  5419. return SQLITE_OK;
  5420. }
  5421. static int zipfileAppendData(
  5422. ZipfileTab *pTab,
  5423. const u8 *aWrite,
  5424. int nWrite
  5425. ){
  5426. size_t n;
  5427. fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
  5428. n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
  5429. if( (int)n!=nWrite ){
  5430. pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
  5431. return SQLITE_ERROR;
  5432. }
  5433. pTab->szCurrent += nWrite;
  5434. return SQLITE_OK;
  5435. }
  5436. /*
  5437. ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
  5438. */
  5439. static u16 zipfileGetU16(const u8 *aBuf){
  5440. return (aBuf[1] << 8) + aBuf[0];
  5441. }
  5442. /*
  5443. ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
  5444. */
  5445. static u32 zipfileGetU32(const u8 *aBuf){
  5446. return ((u32)(aBuf[3]) << 24)
  5447. + ((u32)(aBuf[2]) << 16)
  5448. + ((u32)(aBuf[1]) << 8)
  5449. + ((u32)(aBuf[0]) << 0);
  5450. }
  5451. /*
  5452. ** Write a 16-bit little endiate integer into buffer aBuf.
  5453. */
  5454. static void zipfilePutU16(u8 *aBuf, u16 val){
  5455. aBuf[0] = val & 0xFF;
  5456. aBuf[1] = (val>>8) & 0xFF;
  5457. }
  5458. /*
  5459. ** Write a 32-bit little endiate integer into buffer aBuf.
  5460. */
  5461. static void zipfilePutU32(u8 *aBuf, u32 val){
  5462. aBuf[0] = val & 0xFF;
  5463. aBuf[1] = (val>>8) & 0xFF;
  5464. aBuf[2] = (val>>16) & 0xFF;
  5465. aBuf[3] = (val>>24) & 0xFF;
  5466. }
  5467. #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
  5468. #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
  5469. #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
  5470. #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
  5471. /*
  5472. ** Magic numbers used to read CDS records.
  5473. */
  5474. #define ZIPFILE_CDS_NFILE_OFF 28
  5475. #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
  5476. /*
  5477. ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
  5478. ** if the record is not well-formed, or SQLITE_OK otherwise.
  5479. */
  5480. static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
  5481. u8 *aRead = aBuf;
  5482. u32 sig = zipfileRead32(aRead);
  5483. int rc = SQLITE_OK;
  5484. if( sig!=ZIPFILE_SIGNATURE_CDS ){
  5485. rc = SQLITE_ERROR;
  5486. }else{
  5487. pCDS->iVersionMadeBy = zipfileRead16(aRead);
  5488. pCDS->iVersionExtract = zipfileRead16(aRead);
  5489. pCDS->flags = zipfileRead16(aRead);
  5490. pCDS->iCompression = zipfileRead16(aRead);
  5491. pCDS->mTime = zipfileRead16(aRead);
  5492. pCDS->mDate = zipfileRead16(aRead);
  5493. pCDS->crc32 = zipfileRead32(aRead);
  5494. pCDS->szCompressed = zipfileRead32(aRead);
  5495. pCDS->szUncompressed = zipfileRead32(aRead);
  5496. assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
  5497. pCDS->nFile = zipfileRead16(aRead);
  5498. pCDS->nExtra = zipfileRead16(aRead);
  5499. pCDS->nComment = zipfileRead16(aRead);
  5500. pCDS->iDiskStart = zipfileRead16(aRead);
  5501. pCDS->iInternalAttr = zipfileRead16(aRead);
  5502. pCDS->iExternalAttr = zipfileRead32(aRead);
  5503. pCDS->iOffset = zipfileRead32(aRead);
  5504. assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
  5505. }
  5506. return rc;
  5507. }
  5508. /*
  5509. ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
  5510. ** if the record is not well-formed, or SQLITE_OK otherwise.
  5511. */
  5512. static int zipfileReadLFH(
  5513. u8 *aBuffer,
  5514. ZipfileLFH *pLFH
  5515. ){
  5516. u8 *aRead = aBuffer;
  5517. int rc = SQLITE_OK;
  5518. u32 sig = zipfileRead32(aRead);
  5519. if( sig!=ZIPFILE_SIGNATURE_LFH ){
  5520. rc = SQLITE_ERROR;
  5521. }else{
  5522. pLFH->iVersionExtract = zipfileRead16(aRead);
  5523. pLFH->flags = zipfileRead16(aRead);
  5524. pLFH->iCompression = zipfileRead16(aRead);
  5525. pLFH->mTime = zipfileRead16(aRead);
  5526. pLFH->mDate = zipfileRead16(aRead);
  5527. pLFH->crc32 = zipfileRead32(aRead);
  5528. pLFH->szCompressed = zipfileRead32(aRead);
  5529. pLFH->szUncompressed = zipfileRead32(aRead);
  5530. pLFH->nFile = zipfileRead16(aRead);
  5531. pLFH->nExtra = zipfileRead16(aRead);
  5532. }
  5533. return rc;
  5534. }
  5535. /*
  5536. ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
  5537. ** Scan through this buffer to find an "extra-timestamp" field. If one
  5538. ** exists, extract the 32-bit modification-timestamp from it and store
  5539. ** the value in output parameter *pmTime.
  5540. **
  5541. ** Zero is returned if no extra-timestamp record could be found (and so
  5542. ** *pmTime is left unchanged), or non-zero otherwise.
  5543. **
  5544. ** The general format of an extra field is:
  5545. **
  5546. ** Header ID 2 bytes
  5547. ** Data Size 2 bytes
  5548. ** Data N bytes
  5549. */
  5550. static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
  5551. int ret = 0;
  5552. u8 *p = aExtra;
  5553. u8 *pEnd = &aExtra[nExtra];
  5554. while( p<pEnd ){
  5555. u16 id = zipfileRead16(p);
  5556. u16 nByte = zipfileRead16(p);
  5557. switch( id ){
  5558. case ZIPFILE_EXTRA_TIMESTAMP: {
  5559. u8 b = p[0];
  5560. if( b & 0x01 ){ /* 0x01 -> modtime is present */
  5561. *pmTime = zipfileGetU32(&p[1]);
  5562. ret = 1;
  5563. }
  5564. break;
  5565. }
  5566. }
  5567. p += nByte;
  5568. }
  5569. return ret;
  5570. }
  5571. /*
  5572. ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
  5573. ** fields of the CDS structure passed as the only argument to a 32-bit
  5574. ** UNIX seconds-since-the-epoch timestamp. Return the result.
  5575. **
  5576. ** "Standard" MS-DOS time format:
  5577. **
  5578. ** File modification time:
  5579. ** Bits 00-04: seconds divided by 2
  5580. ** Bits 05-10: minute
  5581. ** Bits 11-15: hour
  5582. ** File modification date:
  5583. ** Bits 00-04: day
  5584. ** Bits 05-08: month (1-12)
  5585. ** Bits 09-15: years from 1980
  5586. **
  5587. ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
  5588. */
  5589. static u32 zipfileMtime(ZipfileCDS *pCDS){
  5590. int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
  5591. int M = ((pCDS->mDate >> 5) & 0x0F);
  5592. int D = (pCDS->mDate & 0x1F);
  5593. int B = -13;
  5594. int sec = (pCDS->mTime & 0x1F)*2;
  5595. int min = (pCDS->mTime >> 5) & 0x3F;
  5596. int hr = (pCDS->mTime >> 11) & 0x1F;
  5597. i64 JD;
  5598. /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */
  5599. /* Calculate the JD in seconds for noon on the day in question */
  5600. if( M<3 ){
  5601. Y = Y-1;
  5602. M = M+12;
  5603. }
  5604. JD = (i64)(24*60*60) * (
  5605. (int)(365.25 * (Y + 4716))
  5606. + (int)(30.6001 * (M + 1))
  5607. + D + B - 1524
  5608. );
  5609. /* Correct the JD for the time within the day */
  5610. JD += (hr-12) * 3600 + min * 60 + sec;
  5611. /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */
  5612. return (u32)(JD - (i64)(24405875) * 24*60*6);
  5613. }
  5614. /*
  5615. ** The opposite of zipfileMtime(). This function populates the mTime and
  5616. ** mDate fields of the CDS structure passed as the first argument according
  5617. ** to the UNIX timestamp value passed as the second.
  5618. */
  5619. static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
  5620. /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
  5621. i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
  5622. int A, B, C, D, E;
  5623. int yr, mon, day;
  5624. int hr, min, sec;
  5625. A = (int)((JD - 1867216.25)/36524.25);
  5626. A = (int)(JD + 1 + A - (A/4));
  5627. B = A + 1524;
  5628. C = (int)((B - 122.1)/365.25);
  5629. D = (36525*(C&32767))/100;
  5630. E = (int)((B-D)/30.6001);
  5631. day = B - D - (int)(30.6001*E);
  5632. mon = (E<14 ? E-1 : E-13);
  5633. yr = mon>2 ? C-4716 : C-4715;
  5634. hr = (mUnixTime % (24*60*60)) / (60*60);
  5635. min = (mUnixTime % (60*60)) / 60;
  5636. sec = (mUnixTime % 60);
  5637. if( yr>=1980 ){
  5638. pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
  5639. pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
  5640. }else{
  5641. pCds->mDate = pCds->mTime = 0;
  5642. }
  5643. assert( mUnixTime<315507600
  5644. || mUnixTime==zipfileMtime(pCds)
  5645. || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
  5646. /* || (mUnixTime % 2) */
  5647. );
  5648. }
  5649. /*
  5650. ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
  5651. ** size) containing an entire zip archive image. Or, if aBlob is NULL,
  5652. ** then pFile is a file-handle open on a zip file. In either case, this
  5653. ** function creates a ZipfileEntry object based on the zip archive entry
  5654. ** for which the CDS record is at offset iOff.
  5655. **
  5656. ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
  5657. ** the new object. Otherwise, an SQLite error code is returned and the
  5658. ** final value of (*ppEntry) undefined.
  5659. */
  5660. static int zipfileGetEntry(
  5661. ZipfileTab *pTab, /* Store any error message here */
  5662. const u8 *aBlob, /* Pointer to in-memory file image */
  5663. int nBlob, /* Size of aBlob[] in bytes */
  5664. FILE *pFile, /* If aBlob==0, read from this file */
  5665. i64 iOff, /* Offset of CDS record */
  5666. ZipfileEntry **ppEntry /* OUT: Pointer to new object */
  5667. ){
  5668. u8 *aRead;
  5669. char **pzErr = &pTab->base.zErrMsg;
  5670. int rc = SQLITE_OK;
  5671. if( aBlob==0 ){
  5672. aRead = pTab->aBuffer;
  5673. rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
  5674. }else{
  5675. aRead = (u8*)&aBlob[iOff];
  5676. }
  5677. if( rc==SQLITE_OK ){
  5678. sqlite3_int64 nAlloc;
  5679. ZipfileEntry *pNew;
  5680. int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
  5681. int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
  5682. nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
  5683. nAlloc = sizeof(ZipfileEntry) + nExtra;
  5684. if( aBlob ){
  5685. nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
  5686. }
  5687. pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
  5688. if( pNew==0 ){
  5689. rc = SQLITE_NOMEM;
  5690. }else{
  5691. memset(pNew, 0, sizeof(ZipfileEntry));
  5692. rc = zipfileReadCDS(aRead, &pNew->cds);
  5693. if( rc!=SQLITE_OK ){
  5694. *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
  5695. }else if( aBlob==0 ){
  5696. rc = zipfileReadData(
  5697. pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
  5698. );
  5699. }else{
  5700. aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
  5701. }
  5702. }
  5703. if( rc==SQLITE_OK ){
  5704. u32 *pt = &pNew->mUnixTime;
  5705. pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
  5706. pNew->aExtra = (u8*)&pNew[1];
  5707. memcpy(pNew->aExtra, &aRead[nFile], nExtra);
  5708. if( pNew->cds.zFile==0 ){
  5709. rc = SQLITE_NOMEM;
  5710. }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
  5711. pNew->mUnixTime = zipfileMtime(&pNew->cds);
  5712. }
  5713. }
  5714. if( rc==SQLITE_OK ){
  5715. static const int szFix = ZIPFILE_LFH_FIXED_SZ;
  5716. ZipfileLFH lfh;
  5717. if( pFile ){
  5718. rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
  5719. }else{
  5720. aRead = (u8*)&aBlob[pNew->cds.iOffset];
  5721. }
  5722. rc = zipfileReadLFH(aRead, &lfh);
  5723. if( rc==SQLITE_OK ){
  5724. pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
  5725. pNew->iDataOff += lfh.nFile + lfh.nExtra;
  5726. if( aBlob && pNew->cds.szCompressed ){
  5727. pNew->aData = &pNew->aExtra[nExtra];
  5728. memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
  5729. }
  5730. }else{
  5731. *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
  5732. (int)pNew->cds.iOffset
  5733. );
  5734. }
  5735. }
  5736. if( rc!=SQLITE_OK ){
  5737. zipfileEntryFree(pNew);
  5738. }else{
  5739. *ppEntry = pNew;
  5740. }
  5741. }
  5742. return rc;
  5743. }
  5744. /*
  5745. ** Advance an ZipfileCsr to its next row of output.
  5746. */
  5747. static int zipfileNext(sqlite3_vtab_cursor *cur){
  5748. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  5749. int rc = SQLITE_OK;
  5750. if( pCsr->pFile ){
  5751. i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
  5752. zipfileEntryFree(pCsr->pCurrent);
  5753. pCsr->pCurrent = 0;
  5754. if( pCsr->iNextOff>=iEof ){
  5755. pCsr->bEof = 1;
  5756. }else{
  5757. ZipfileEntry *p = 0;
  5758. ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
  5759. rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
  5760. if( rc==SQLITE_OK ){
  5761. pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
  5762. pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
  5763. }
  5764. pCsr->pCurrent = p;
  5765. }
  5766. }else{
  5767. if( !pCsr->bNoop ){
  5768. pCsr->pCurrent = pCsr->pCurrent->pNext;
  5769. }
  5770. if( pCsr->pCurrent==0 ){
  5771. pCsr->bEof = 1;
  5772. }
  5773. }
  5774. pCsr->bNoop = 0;
  5775. return rc;
  5776. }
  5777. static void zipfileFree(void *p) {
  5778. sqlite3_free(p);
  5779. }
  5780. /*
  5781. ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
  5782. ** size is nOut bytes. This function uncompresses the data and sets the
  5783. ** return value in context pCtx to the result (a blob).
  5784. **
  5785. ** If an error occurs, an error code is left in pCtx instead.
  5786. */
  5787. static void zipfileInflate(
  5788. sqlite3_context *pCtx, /* Store result here */
  5789. const u8 *aIn, /* Compressed data */
  5790. int nIn, /* Size of buffer aIn[] in bytes */
  5791. int nOut /* Expected output size */
  5792. ){
  5793. u8 *aRes = sqlite3_malloc(nOut);
  5794. if( aRes==0 ){
  5795. sqlite3_result_error_nomem(pCtx);
  5796. }else{
  5797. int err;
  5798. z_stream str;
  5799. memset(&str, 0, sizeof(str));
  5800. str.next_in = (Byte*)aIn;
  5801. str.avail_in = nIn;
  5802. str.next_out = (Byte*)aRes;
  5803. str.avail_out = nOut;
  5804. err = inflateInit2(&str, -15);
  5805. if( err!=Z_OK ){
  5806. zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
  5807. }else{
  5808. err = inflate(&str, Z_NO_FLUSH);
  5809. if( err!=Z_STREAM_END ){
  5810. zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
  5811. }else{
  5812. sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
  5813. aRes = 0;
  5814. }
  5815. }
  5816. sqlite3_free(aRes);
  5817. inflateEnd(&str);
  5818. }
  5819. }
  5820. /*
  5821. ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
  5822. ** compresses it and sets (*ppOut) to point to a buffer containing the
  5823. ** compressed data. The caller is responsible for eventually calling
  5824. ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
  5825. ** is set to the size of buffer (*ppOut) in bytes.
  5826. **
  5827. ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
  5828. ** code is returned and an error message left in virtual-table handle
  5829. ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
  5830. ** case.
  5831. */
  5832. static int zipfileDeflate(
  5833. const u8 *aIn, int nIn, /* Input */
  5834. u8 **ppOut, int *pnOut, /* Output */
  5835. char **pzErr /* OUT: Error message */
  5836. ){
  5837. int rc = SQLITE_OK;
  5838. sqlite3_int64 nAlloc;
  5839. z_stream str;
  5840. u8 *aOut;
  5841. memset(&str, 0, sizeof(str));
  5842. str.next_in = (Bytef*)aIn;
  5843. str.avail_in = nIn;
  5844. deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
  5845. nAlloc = deflateBound(&str, nIn);
  5846. aOut = (u8*)sqlite3_malloc64(nAlloc);
  5847. if( aOut==0 ){
  5848. rc = SQLITE_NOMEM;
  5849. }else{
  5850. int res;
  5851. str.next_out = aOut;
  5852. str.avail_out = nAlloc;
  5853. res = deflate(&str, Z_FINISH);
  5854. if( res==Z_STREAM_END ){
  5855. *ppOut = aOut;
  5856. *pnOut = (int)str.total_out;
  5857. }else{
  5858. sqlite3_free(aOut);
  5859. *pzErr = sqlite3_mprintf("zipfile: deflate() error");
  5860. rc = SQLITE_ERROR;
  5861. }
  5862. deflateEnd(&str);
  5863. }
  5864. return rc;
  5865. }
  5866. /*
  5867. ** Return values of columns for the row at which the series_cursor
  5868. ** is currently pointing.
  5869. */
  5870. static int zipfileColumn(
  5871. sqlite3_vtab_cursor *cur, /* The cursor */
  5872. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  5873. int i /* Which column to return */
  5874. ){
  5875. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  5876. ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
  5877. int rc = SQLITE_OK;
  5878. switch( i ){
  5879. case 0: /* name */
  5880. sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
  5881. break;
  5882. case 1: /* mode */
  5883. /* TODO: Whether or not the following is correct surely depends on
  5884. ** the platform on which the archive was created. */
  5885. sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
  5886. break;
  5887. case 2: { /* mtime */
  5888. sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
  5889. break;
  5890. }
  5891. case 3: { /* sz */
  5892. if( sqlite3_vtab_nochange(ctx)==0 ){
  5893. sqlite3_result_int64(ctx, pCDS->szUncompressed);
  5894. }
  5895. break;
  5896. }
  5897. case 4: /* rawdata */
  5898. if( sqlite3_vtab_nochange(ctx) ) break;
  5899. case 5: { /* data */
  5900. if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
  5901. int sz = pCDS->szCompressed;
  5902. int szFinal = pCDS->szUncompressed;
  5903. if( szFinal>0 ){
  5904. u8 *aBuf;
  5905. u8 *aFree = 0;
  5906. if( pCsr->pCurrent->aData ){
  5907. aBuf = pCsr->pCurrent->aData;
  5908. }else{
  5909. aBuf = aFree = sqlite3_malloc64(sz);
  5910. if( aBuf==0 ){
  5911. rc = SQLITE_NOMEM;
  5912. }else{
  5913. FILE *pFile = pCsr->pFile;
  5914. if( pFile==0 ){
  5915. pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
  5916. }
  5917. rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
  5918. &pCsr->base.pVtab->zErrMsg
  5919. );
  5920. }
  5921. }
  5922. if( rc==SQLITE_OK ){
  5923. if( i==5 && pCDS->iCompression ){
  5924. zipfileInflate(ctx, aBuf, sz, szFinal);
  5925. }else{
  5926. sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
  5927. }
  5928. }
  5929. sqlite3_free(aFree);
  5930. }else{
  5931. /* Figure out if this is a directory or a zero-sized file. Consider
  5932. ** it to be a directory either if the mode suggests so, or if
  5933. ** the final character in the name is '/'. */
  5934. u32 mode = pCDS->iExternalAttr >> 16;
  5935. if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
  5936. sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
  5937. }
  5938. }
  5939. }
  5940. break;
  5941. }
  5942. case 6: /* method */
  5943. sqlite3_result_int(ctx, pCDS->iCompression);
  5944. break;
  5945. default: /* z */
  5946. assert( i==7 );
  5947. sqlite3_result_int64(ctx, pCsr->iId);
  5948. break;
  5949. }
  5950. return rc;
  5951. }
  5952. /*
  5953. ** Return TRUE if the cursor is at EOF.
  5954. */
  5955. static int zipfileEof(sqlite3_vtab_cursor *cur){
  5956. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  5957. return pCsr->bEof;
  5958. }
  5959. /*
  5960. ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
  5961. ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
  5962. ** is guaranteed to be a file-handle open on a zip file.
  5963. **
  5964. ** This function attempts to locate the EOCD record within the zip archive
  5965. ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
  5966. ** returned if successful. Otherwise, an SQLite error code is returned and
  5967. ** an English language error message may be left in virtual-table pTab.
  5968. */
  5969. static int zipfileReadEOCD(
  5970. ZipfileTab *pTab, /* Return errors here */
  5971. const u8 *aBlob, /* Pointer to in-memory file image */
  5972. int nBlob, /* Size of aBlob[] in bytes */
  5973. FILE *pFile, /* Read from this file if aBlob==0 */
  5974. ZipfileEOCD *pEOCD /* Object to populate */
  5975. ){
  5976. u8 *aRead = pTab->aBuffer; /* Temporary buffer */
  5977. int nRead; /* Bytes to read from file */
  5978. int rc = SQLITE_OK;
  5979. if( aBlob==0 ){
  5980. i64 iOff; /* Offset to read from */
  5981. i64 szFile; /* Total size of file in bytes */
  5982. fseek(pFile, 0, SEEK_END);
  5983. szFile = (i64)ftell(pFile);
  5984. if( szFile==0 ){
  5985. memset(pEOCD, 0, sizeof(ZipfileEOCD));
  5986. return SQLITE_OK;
  5987. }
  5988. nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
  5989. iOff = szFile - nRead;
  5990. rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
  5991. }else{
  5992. nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
  5993. aRead = (u8*)&aBlob[nBlob-nRead];
  5994. }
  5995. if( rc==SQLITE_OK ){
  5996. int i;
  5997. /* Scan backwards looking for the signature bytes */
  5998. for(i=nRead-20; i>=0; i--){
  5999. if( aRead[i]==0x50 && aRead[i+1]==0x4b
  6000. && aRead[i+2]==0x05 && aRead[i+3]==0x06
  6001. ){
  6002. break;
  6003. }
  6004. }
  6005. if( i<0 ){
  6006. pTab->base.zErrMsg = sqlite3_mprintf(
  6007. "cannot find end of central directory record"
  6008. );
  6009. return SQLITE_ERROR;
  6010. }
  6011. aRead += i+4;
  6012. pEOCD->iDisk = zipfileRead16(aRead);
  6013. pEOCD->iFirstDisk = zipfileRead16(aRead);
  6014. pEOCD->nEntry = zipfileRead16(aRead);
  6015. pEOCD->nEntryTotal = zipfileRead16(aRead);
  6016. pEOCD->nSize = zipfileRead32(aRead);
  6017. pEOCD->iOffset = zipfileRead32(aRead);
  6018. }
  6019. return rc;
  6020. }
  6021. /*
  6022. ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
  6023. ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
  6024. ** to the end of the list. Otherwise, it is added to the list immediately
  6025. ** before pBefore (which is guaranteed to be a part of said list).
  6026. */
  6027. static void zipfileAddEntry(
  6028. ZipfileTab *pTab,
  6029. ZipfileEntry *pBefore,
  6030. ZipfileEntry *pNew
  6031. ){
  6032. assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
  6033. assert( pNew->pNext==0 );
  6034. if( pBefore==0 ){
  6035. if( pTab->pFirstEntry==0 ){
  6036. pTab->pFirstEntry = pTab->pLastEntry = pNew;
  6037. }else{
  6038. assert( pTab->pLastEntry->pNext==0 );
  6039. pTab->pLastEntry->pNext = pNew;
  6040. pTab->pLastEntry = pNew;
  6041. }
  6042. }else{
  6043. ZipfileEntry **pp;
  6044. for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
  6045. pNew->pNext = pBefore;
  6046. *pp = pNew;
  6047. }
  6048. }
  6049. static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
  6050. ZipfileEOCD eocd;
  6051. int rc;
  6052. int i;
  6053. i64 iOff;
  6054. rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
  6055. iOff = eocd.iOffset;
  6056. for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
  6057. ZipfileEntry *pNew = 0;
  6058. rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
  6059. if( rc==SQLITE_OK ){
  6060. zipfileAddEntry(pTab, 0, pNew);
  6061. iOff += ZIPFILE_CDS_FIXED_SZ;
  6062. iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
  6063. }
  6064. }
  6065. return rc;
  6066. }
  6067. /*
  6068. ** xFilter callback.
  6069. */
  6070. static int zipfileFilter(
  6071. sqlite3_vtab_cursor *cur,
  6072. int idxNum, const char *idxStr,
  6073. int argc, sqlite3_value **argv
  6074. ){
  6075. ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
  6076. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  6077. const char *zFile = 0; /* Zip file to scan */
  6078. int rc = SQLITE_OK; /* Return Code */
  6079. int bInMemory = 0; /* True for an in-memory zipfile */
  6080. zipfileResetCursor(pCsr);
  6081. if( pTab->zFile ){
  6082. zFile = pTab->zFile;
  6083. }else if( idxNum==0 ){
  6084. zipfileCursorErr(pCsr, "zipfile() function requires an argument");
  6085. return SQLITE_ERROR;
  6086. }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
  6087. const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
  6088. int nBlob = sqlite3_value_bytes(argv[0]);
  6089. assert( pTab->pFirstEntry==0 );
  6090. rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
  6091. pCsr->pFreeEntry = pTab->pFirstEntry;
  6092. pTab->pFirstEntry = pTab->pLastEntry = 0;
  6093. if( rc!=SQLITE_OK ) return rc;
  6094. bInMemory = 1;
  6095. }else{
  6096. zFile = (const char*)sqlite3_value_text(argv[0]);
  6097. }
  6098. if( 0==pTab->pWriteFd && 0==bInMemory ){
  6099. pCsr->pFile = fopen(zFile, "rb");
  6100. if( pCsr->pFile==0 ){
  6101. zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
  6102. rc = SQLITE_ERROR;
  6103. }else{
  6104. rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
  6105. if( rc==SQLITE_OK ){
  6106. if( pCsr->eocd.nEntry==0 ){
  6107. pCsr->bEof = 1;
  6108. }else{
  6109. pCsr->iNextOff = pCsr->eocd.iOffset;
  6110. rc = zipfileNext(cur);
  6111. }
  6112. }
  6113. }
  6114. }else{
  6115. pCsr->bNoop = 1;
  6116. pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
  6117. rc = zipfileNext(cur);
  6118. }
  6119. return rc;
  6120. }
  6121. /*
  6122. ** xBestIndex callback.
  6123. */
  6124. static int zipfileBestIndex(
  6125. sqlite3_vtab *tab,
  6126. sqlite3_index_info *pIdxInfo
  6127. ){
  6128. int i;
  6129. int idx = -1;
  6130. int unusable = 0;
  6131. for(i=0; i<pIdxInfo->nConstraint; i++){
  6132. const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
  6133. if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
  6134. if( pCons->usable==0 ){
  6135. unusable = 1;
  6136. }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  6137. idx = i;
  6138. }
  6139. }
  6140. pIdxInfo->estimatedCost = 1000.0;
  6141. if( idx>=0 ){
  6142. pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
  6143. pIdxInfo->aConstraintUsage[idx].omit = 1;
  6144. pIdxInfo->idxNum = 1;
  6145. }else if( unusable ){
  6146. return SQLITE_CONSTRAINT;
  6147. }
  6148. return SQLITE_OK;
  6149. }
  6150. static ZipfileEntry *zipfileNewEntry(const char *zPath){
  6151. ZipfileEntry *pNew;
  6152. pNew = sqlite3_malloc(sizeof(ZipfileEntry));
  6153. if( pNew ){
  6154. memset(pNew, 0, sizeof(ZipfileEntry));
  6155. pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
  6156. if( pNew->cds.zFile==0 ){
  6157. sqlite3_free(pNew);
  6158. pNew = 0;
  6159. }
  6160. }
  6161. return pNew;
  6162. }
  6163. static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
  6164. ZipfileCDS *pCds = &pEntry->cds;
  6165. u8 *a = aBuf;
  6166. pCds->nExtra = 9;
  6167. /* Write the LFH itself */
  6168. zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
  6169. zipfileWrite16(a, pCds->iVersionExtract);
  6170. zipfileWrite16(a, pCds->flags);
  6171. zipfileWrite16(a, pCds->iCompression);
  6172. zipfileWrite16(a, pCds->mTime);
  6173. zipfileWrite16(a, pCds->mDate);
  6174. zipfileWrite32(a, pCds->crc32);
  6175. zipfileWrite32(a, pCds->szCompressed);
  6176. zipfileWrite32(a, pCds->szUncompressed);
  6177. zipfileWrite16(a, (u16)pCds->nFile);
  6178. zipfileWrite16(a, pCds->nExtra);
  6179. assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
  6180. /* Add the file name */
  6181. memcpy(a, pCds->zFile, (int)pCds->nFile);
  6182. a += (int)pCds->nFile;
  6183. /* The "extra" data */
  6184. zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
  6185. zipfileWrite16(a, 5);
  6186. *a++ = 0x01;
  6187. zipfileWrite32(a, pEntry->mUnixTime);
  6188. return a-aBuf;
  6189. }
  6190. static int zipfileAppendEntry(
  6191. ZipfileTab *pTab,
  6192. ZipfileEntry *pEntry,
  6193. const u8 *pData,
  6194. int nData
  6195. ){
  6196. u8 *aBuf = pTab->aBuffer;
  6197. int nBuf;
  6198. int rc;
  6199. nBuf = zipfileSerializeLFH(pEntry, aBuf);
  6200. rc = zipfileAppendData(pTab, aBuf, nBuf);
  6201. if( rc==SQLITE_OK ){
  6202. pEntry->iDataOff = pTab->szCurrent;
  6203. rc = zipfileAppendData(pTab, pData, nData);
  6204. }
  6205. return rc;
  6206. }
  6207. static int zipfileGetMode(
  6208. sqlite3_value *pVal,
  6209. int bIsDir, /* If true, default to directory */
  6210. u32 *pMode, /* OUT: Mode value */
  6211. char **pzErr /* OUT: Error message */
  6212. ){
  6213. const char *z = (const char*)sqlite3_value_text(pVal);
  6214. u32 mode = 0;
  6215. if( z==0 ){
  6216. mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
  6217. }else if( z[0]>='0' && z[0]<='9' ){
  6218. mode = (unsigned int)sqlite3_value_int(pVal);
  6219. }else{
  6220. const char zTemplate[11] = "-rwxrwxrwx";
  6221. int i;
  6222. if( strlen(z)!=10 ) goto parse_error;
  6223. switch( z[0] ){
  6224. case '-': mode |= S_IFREG; break;
  6225. case 'd': mode |= S_IFDIR; break;
  6226. case 'l': mode |= S_IFLNK; break;
  6227. default: goto parse_error;
  6228. }
  6229. for(i=1; i<10; i++){
  6230. if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
  6231. else if( z[i]!='-' ) goto parse_error;
  6232. }
  6233. }
  6234. if( ((mode & S_IFDIR)==0)==bIsDir ){
  6235. /* The "mode" attribute is a directory, but data has been specified.
  6236. ** Or vice-versa - no data but "mode" is a file or symlink. */
  6237. *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
  6238. return SQLITE_CONSTRAINT;
  6239. }
  6240. *pMode = mode;
  6241. return SQLITE_OK;
  6242. parse_error:
  6243. *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
  6244. return SQLITE_ERROR;
  6245. }
  6246. /*
  6247. ** Both (const char*) arguments point to nul-terminated strings. Argument
  6248. ** nB is the value of strlen(zB). This function returns 0 if the strings are
  6249. ** identical, ignoring any trailing '/' character in either path. */
  6250. static int zipfileComparePath(const char *zA, const char *zB, int nB){
  6251. int nA = (int)strlen(zA);
  6252. if( nA>0 && zA[nA-1]=='/' ) nA--;
  6253. if( nB>0 && zB[nB-1]=='/' ) nB--;
  6254. if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
  6255. return 1;
  6256. }
  6257. static int zipfileBegin(sqlite3_vtab *pVtab){
  6258. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  6259. int rc = SQLITE_OK;
  6260. assert( pTab->pWriteFd==0 );
  6261. if( pTab->zFile==0 || pTab->zFile[0]==0 ){
  6262. pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
  6263. return SQLITE_ERROR;
  6264. }
  6265. /* Open a write fd on the file. Also load the entire central directory
  6266. ** structure into memory. During the transaction any new file data is
  6267. ** appended to the archive file, but the central directory is accumulated
  6268. ** in main-memory until the transaction is committed. */
  6269. pTab->pWriteFd = fopen(pTab->zFile, "ab+");
  6270. if( pTab->pWriteFd==0 ){
  6271. pTab->base.zErrMsg = sqlite3_mprintf(
  6272. "zipfile: failed to open file %s for writing", pTab->zFile
  6273. );
  6274. rc = SQLITE_ERROR;
  6275. }else{
  6276. fseek(pTab->pWriteFd, 0, SEEK_END);
  6277. pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
  6278. rc = zipfileLoadDirectory(pTab, 0, 0);
  6279. }
  6280. if( rc!=SQLITE_OK ){
  6281. zipfileCleanupTransaction(pTab);
  6282. }
  6283. return rc;
  6284. }
  6285. /*
  6286. ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
  6287. ** time(2)).
  6288. */
  6289. static u32 zipfileTime(void){
  6290. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  6291. u32 ret;
  6292. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  6293. i64 ms;
  6294. pVfs->xCurrentTimeInt64(pVfs, &ms);
  6295. ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
  6296. }else{
  6297. double day;
  6298. pVfs->xCurrentTime(pVfs, &day);
  6299. ret = (u32)((day - 2440587.5) * 86400);
  6300. }
  6301. return ret;
  6302. }
  6303. /*
  6304. ** Return a 32-bit timestamp in UNIX epoch format.
  6305. **
  6306. ** If the value passed as the only argument is either NULL or an SQL NULL,
  6307. ** return the current time. Otherwise, return the value stored in (*pVal)
  6308. ** cast to a 32-bit unsigned integer.
  6309. */
  6310. static u32 zipfileGetTime(sqlite3_value *pVal){
  6311. if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
  6312. return zipfileTime();
  6313. }
  6314. return (u32)sqlite3_value_int64(pVal);
  6315. }
  6316. /*
  6317. ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
  6318. ** linked list. Remove it from the list and free the object.
  6319. */
  6320. static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
  6321. if( pOld ){
  6322. ZipfileEntry **pp;
  6323. for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
  6324. *pp = (*pp)->pNext;
  6325. zipfileEntryFree(pOld);
  6326. }
  6327. }
  6328. /*
  6329. ** xUpdate method.
  6330. */
  6331. static int zipfileUpdate(
  6332. sqlite3_vtab *pVtab,
  6333. int nVal,
  6334. sqlite3_value **apVal,
  6335. sqlite_int64 *pRowid
  6336. ){
  6337. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  6338. int rc = SQLITE_OK; /* Return Code */
  6339. ZipfileEntry *pNew = 0; /* New in-memory CDS entry */
  6340. u32 mode = 0; /* Mode for new entry */
  6341. u32 mTime = 0; /* Modification time for new entry */
  6342. i64 sz = 0; /* Uncompressed size */
  6343. const char *zPath = 0; /* Path for new entry */
  6344. int nPath = 0; /* strlen(zPath) */
  6345. const u8 *pData = 0; /* Pointer to buffer containing content */
  6346. int nData = 0; /* Size of pData buffer in bytes */
  6347. int iMethod = 0; /* Compression method for new entry */
  6348. u8 *pFree = 0; /* Free this */
  6349. char *zFree = 0; /* Also free this */
  6350. ZipfileEntry *pOld = 0;
  6351. ZipfileEntry *pOld2 = 0;
  6352. int bUpdate = 0; /* True for an update that modifies "name" */
  6353. int bIsDir = 0;
  6354. u32 iCrc32 = 0;
  6355. if( pTab->pWriteFd==0 ){
  6356. rc = zipfileBegin(pVtab);
  6357. if( rc!=SQLITE_OK ) return rc;
  6358. }
  6359. /* If this is a DELETE or UPDATE, find the archive entry to delete. */
  6360. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  6361. const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
  6362. int nDelete = (int)strlen(zDelete);
  6363. if( nVal>1 ){
  6364. const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
  6365. if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
  6366. bUpdate = 1;
  6367. }
  6368. }
  6369. for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
  6370. if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
  6371. break;
  6372. }
  6373. assert( pOld->pNext );
  6374. }
  6375. }
  6376. if( nVal>1 ){
  6377. /* Check that "sz" and "rawdata" are both NULL: */
  6378. if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
  6379. zipfileTableErr(pTab, "sz must be NULL");
  6380. rc = SQLITE_CONSTRAINT;
  6381. }
  6382. if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
  6383. zipfileTableErr(pTab, "rawdata must be NULL");
  6384. rc = SQLITE_CONSTRAINT;
  6385. }
  6386. if( rc==SQLITE_OK ){
  6387. if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
  6388. /* data=NULL. A directory */
  6389. bIsDir = 1;
  6390. }else{
  6391. /* Value specified for "data", and possibly "method". This must be
  6392. ** a regular file or a symlink. */
  6393. const u8 *aIn = sqlite3_value_blob(apVal[7]);
  6394. int nIn = sqlite3_value_bytes(apVal[7]);
  6395. int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
  6396. iMethod = sqlite3_value_int(apVal[8]);
  6397. sz = nIn;
  6398. pData = aIn;
  6399. nData = nIn;
  6400. if( iMethod!=0 && iMethod!=8 ){
  6401. zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
  6402. rc = SQLITE_CONSTRAINT;
  6403. }else{
  6404. if( bAuto || iMethod ){
  6405. int nCmp;
  6406. rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
  6407. if( rc==SQLITE_OK ){
  6408. if( iMethod || nCmp<nIn ){
  6409. iMethod = 8;
  6410. pData = pFree;
  6411. nData = nCmp;
  6412. }
  6413. }
  6414. }
  6415. iCrc32 = crc32(0, aIn, nIn);
  6416. }
  6417. }
  6418. }
  6419. if( rc==SQLITE_OK ){
  6420. rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
  6421. }
  6422. if( rc==SQLITE_OK ){
  6423. zPath = (const char*)sqlite3_value_text(apVal[2]);
  6424. if( zPath==0 ) zPath = "";
  6425. nPath = (int)strlen(zPath);
  6426. mTime = zipfileGetTime(apVal[4]);
  6427. }
  6428. if( rc==SQLITE_OK && bIsDir ){
  6429. /* For a directory, check that the last character in the path is a
  6430. ** '/'. This appears to be required for compatibility with info-zip
  6431. ** (the unzip command on unix). It does not create directories
  6432. ** otherwise. */
  6433. if( nPath<=0 || zPath[nPath-1]!='/' ){
  6434. zFree = sqlite3_mprintf("%s/", zPath);
  6435. zPath = (const char*)zFree;
  6436. if( zFree==0 ){
  6437. rc = SQLITE_NOMEM;
  6438. nPath = 0;
  6439. }else{
  6440. nPath = (int)strlen(zPath);
  6441. }
  6442. }
  6443. }
  6444. /* Check that we're not inserting a duplicate entry -OR- updating an
  6445. ** entry with a path, thereby making it into a duplicate. */
  6446. if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
  6447. ZipfileEntry *p;
  6448. for(p=pTab->pFirstEntry; p; p=p->pNext){
  6449. if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
  6450. switch( sqlite3_vtab_on_conflict(pTab->db) ){
  6451. case SQLITE_IGNORE: {
  6452. goto zipfile_update_done;
  6453. }
  6454. case SQLITE_REPLACE: {
  6455. pOld2 = p;
  6456. break;
  6457. }
  6458. default: {
  6459. zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
  6460. rc = SQLITE_CONSTRAINT;
  6461. break;
  6462. }
  6463. }
  6464. break;
  6465. }
  6466. }
  6467. }
  6468. if( rc==SQLITE_OK ){
  6469. /* Create the new CDS record. */
  6470. pNew = zipfileNewEntry(zPath);
  6471. if( pNew==0 ){
  6472. rc = SQLITE_NOMEM;
  6473. }else{
  6474. pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
  6475. pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
  6476. pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
  6477. pNew->cds.iCompression = (u16)iMethod;
  6478. zipfileMtimeToDos(&pNew->cds, mTime);
  6479. pNew->cds.crc32 = iCrc32;
  6480. pNew->cds.szCompressed = nData;
  6481. pNew->cds.szUncompressed = (u32)sz;
  6482. pNew->cds.iExternalAttr = (mode<<16);
  6483. pNew->cds.iOffset = (u32)pTab->szCurrent;
  6484. pNew->cds.nFile = (u16)nPath;
  6485. pNew->mUnixTime = (u32)mTime;
  6486. rc = zipfileAppendEntry(pTab, pNew, pData, nData);
  6487. zipfileAddEntry(pTab, pOld, pNew);
  6488. }
  6489. }
  6490. }
  6491. if( rc==SQLITE_OK && (pOld || pOld2) ){
  6492. ZipfileCsr *pCsr;
  6493. for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
  6494. if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
  6495. pCsr->pCurrent = pCsr->pCurrent->pNext;
  6496. pCsr->bNoop = 1;
  6497. }
  6498. }
  6499. zipfileRemoveEntryFromList(pTab, pOld);
  6500. zipfileRemoveEntryFromList(pTab, pOld2);
  6501. }
  6502. zipfile_update_done:
  6503. sqlite3_free(pFree);
  6504. sqlite3_free(zFree);
  6505. return rc;
  6506. }
  6507. static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
  6508. u8 *a = aBuf;
  6509. zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
  6510. zipfileWrite16(a, p->iDisk);
  6511. zipfileWrite16(a, p->iFirstDisk);
  6512. zipfileWrite16(a, p->nEntry);
  6513. zipfileWrite16(a, p->nEntryTotal);
  6514. zipfileWrite32(a, p->nSize);
  6515. zipfileWrite32(a, p->iOffset);
  6516. zipfileWrite16(a, 0); /* Size of trailing comment in bytes*/
  6517. return a-aBuf;
  6518. }
  6519. static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
  6520. int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
  6521. assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
  6522. return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
  6523. }
  6524. /*
  6525. ** Serialize the CDS structure into buffer aBuf[]. Return the number
  6526. ** of bytes written.
  6527. */
  6528. static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
  6529. u8 *a = aBuf;
  6530. ZipfileCDS *pCDS = &pEntry->cds;
  6531. if( pEntry->aExtra==0 ){
  6532. pCDS->nExtra = 9;
  6533. }
  6534. zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
  6535. zipfileWrite16(a, pCDS->iVersionMadeBy);
  6536. zipfileWrite16(a, pCDS->iVersionExtract);
  6537. zipfileWrite16(a, pCDS->flags);
  6538. zipfileWrite16(a, pCDS->iCompression);
  6539. zipfileWrite16(a, pCDS->mTime);
  6540. zipfileWrite16(a, pCDS->mDate);
  6541. zipfileWrite32(a, pCDS->crc32);
  6542. zipfileWrite32(a, pCDS->szCompressed);
  6543. zipfileWrite32(a, pCDS->szUncompressed);
  6544. assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
  6545. zipfileWrite16(a, pCDS->nFile);
  6546. zipfileWrite16(a, pCDS->nExtra);
  6547. zipfileWrite16(a, pCDS->nComment);
  6548. zipfileWrite16(a, pCDS->iDiskStart);
  6549. zipfileWrite16(a, pCDS->iInternalAttr);
  6550. zipfileWrite32(a, pCDS->iExternalAttr);
  6551. zipfileWrite32(a, pCDS->iOffset);
  6552. memcpy(a, pCDS->zFile, pCDS->nFile);
  6553. a += pCDS->nFile;
  6554. if( pEntry->aExtra ){
  6555. int n = (int)pCDS->nExtra + (int)pCDS->nComment;
  6556. memcpy(a, pEntry->aExtra, n);
  6557. a += n;
  6558. }else{
  6559. assert( pCDS->nExtra==9 );
  6560. zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
  6561. zipfileWrite16(a, 5);
  6562. *a++ = 0x01;
  6563. zipfileWrite32(a, pEntry->mUnixTime);
  6564. }
  6565. return a-aBuf;
  6566. }
  6567. static int zipfileCommit(sqlite3_vtab *pVtab){
  6568. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  6569. int rc = SQLITE_OK;
  6570. if( pTab->pWriteFd ){
  6571. i64 iOffset = pTab->szCurrent;
  6572. ZipfileEntry *p;
  6573. ZipfileEOCD eocd;
  6574. int nEntry = 0;
  6575. /* Write out all entries */
  6576. for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
  6577. int n = zipfileSerializeCDS(p, pTab->aBuffer);
  6578. rc = zipfileAppendData(pTab, pTab->aBuffer, n);
  6579. nEntry++;
  6580. }
  6581. /* Write out the EOCD record */
  6582. eocd.iDisk = 0;
  6583. eocd.iFirstDisk = 0;
  6584. eocd.nEntry = (u16)nEntry;
  6585. eocd.nEntryTotal = (u16)nEntry;
  6586. eocd.nSize = (u32)(pTab->szCurrent - iOffset);
  6587. eocd.iOffset = (u32)iOffset;
  6588. rc = zipfileAppendEOCD(pTab, &eocd);
  6589. zipfileCleanupTransaction(pTab);
  6590. }
  6591. return rc;
  6592. }
  6593. static int zipfileRollback(sqlite3_vtab *pVtab){
  6594. return zipfileCommit(pVtab);
  6595. }
  6596. static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
  6597. ZipfileCsr *pCsr;
  6598. for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
  6599. if( iId==pCsr->iId ) break;
  6600. }
  6601. return pCsr;
  6602. }
  6603. static void zipfileFunctionCds(
  6604. sqlite3_context *context,
  6605. int argc,
  6606. sqlite3_value **argv
  6607. ){
  6608. ZipfileCsr *pCsr;
  6609. ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
  6610. assert( argc>0 );
  6611. pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
  6612. if( pCsr ){
  6613. ZipfileCDS *p = &pCsr->pCurrent->cds;
  6614. char *zRes = sqlite3_mprintf("{"
  6615. "\"version-made-by\" : %u, "
  6616. "\"version-to-extract\" : %u, "
  6617. "\"flags\" : %u, "
  6618. "\"compression\" : %u, "
  6619. "\"time\" : %u, "
  6620. "\"date\" : %u, "
  6621. "\"crc32\" : %u, "
  6622. "\"compressed-size\" : %u, "
  6623. "\"uncompressed-size\" : %u, "
  6624. "\"file-name-length\" : %u, "
  6625. "\"extra-field-length\" : %u, "
  6626. "\"file-comment-length\" : %u, "
  6627. "\"disk-number-start\" : %u, "
  6628. "\"internal-attr\" : %u, "
  6629. "\"external-attr\" : %u, "
  6630. "\"offset\" : %u }",
  6631. (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
  6632. (u32)p->flags, (u32)p->iCompression,
  6633. (u32)p->mTime, (u32)p->mDate,
  6634. (u32)p->crc32, (u32)p->szCompressed,
  6635. (u32)p->szUncompressed, (u32)p->nFile,
  6636. (u32)p->nExtra, (u32)p->nComment,
  6637. (u32)p->iDiskStart, (u32)p->iInternalAttr,
  6638. (u32)p->iExternalAttr, (u32)p->iOffset
  6639. );
  6640. if( zRes==0 ){
  6641. sqlite3_result_error_nomem(context);
  6642. }else{
  6643. sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
  6644. sqlite3_free(zRes);
  6645. }
  6646. }
  6647. }
  6648. /*
  6649. ** xFindFunction method.
  6650. */
  6651. static int zipfileFindFunction(
  6652. sqlite3_vtab *pVtab, /* Virtual table handle */
  6653. int nArg, /* Number of SQL function arguments */
  6654. const char *zName, /* Name of SQL function */
  6655. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  6656. void **ppArg /* OUT: User data for *pxFunc */
  6657. ){
  6658. if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
  6659. *pxFunc = zipfileFunctionCds;
  6660. *ppArg = (void*)pVtab;
  6661. return 1;
  6662. }
  6663. return 0;
  6664. }
  6665. typedef struct ZipfileBuffer ZipfileBuffer;
  6666. struct ZipfileBuffer {
  6667. u8 *a; /* Pointer to buffer */
  6668. int n; /* Size of buffer in bytes */
  6669. int nAlloc; /* Byte allocated at a[] */
  6670. };
  6671. typedef struct ZipfileCtx ZipfileCtx;
  6672. struct ZipfileCtx {
  6673. int nEntry;
  6674. ZipfileBuffer body;
  6675. ZipfileBuffer cds;
  6676. };
  6677. static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
  6678. if( pBuf->n+nByte>pBuf->nAlloc ){
  6679. u8 *aNew;
  6680. sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
  6681. int nReq = pBuf->n + nByte;
  6682. while( nNew<nReq ) nNew = nNew*2;
  6683. aNew = sqlite3_realloc64(pBuf->a, nNew);
  6684. if( aNew==0 ) return SQLITE_NOMEM;
  6685. pBuf->a = aNew;
  6686. pBuf->nAlloc = (int)nNew;
  6687. }
  6688. return SQLITE_OK;
  6689. }
  6690. /*
  6691. ** xStep() callback for the zipfile() aggregate. This can be called in
  6692. ** any of the following ways:
  6693. **
  6694. ** SELECT zipfile(name,data) ...
  6695. ** SELECT zipfile(name,mode,mtime,data) ...
  6696. ** SELECT zipfile(name,mode,mtime,data,method) ...
  6697. */
  6698. void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
  6699. ZipfileCtx *p; /* Aggregate function context */
  6700. ZipfileEntry e; /* New entry to add to zip archive */
  6701. sqlite3_value *pName = 0;
  6702. sqlite3_value *pMode = 0;
  6703. sqlite3_value *pMtime = 0;
  6704. sqlite3_value *pData = 0;
  6705. sqlite3_value *pMethod = 0;
  6706. int bIsDir = 0;
  6707. u32 mode;
  6708. int rc = SQLITE_OK;
  6709. char *zErr = 0;
  6710. int iMethod = -1; /* Compression method to use (0 or 8) */
  6711. const u8 *aData = 0; /* Possibly compressed data for new entry */
  6712. int nData = 0; /* Size of aData[] in bytes */
  6713. int szUncompressed = 0; /* Size of data before compression */
  6714. u8 *aFree = 0; /* Free this before returning */
  6715. u32 iCrc32 = 0; /* crc32 of uncompressed data */
  6716. char *zName = 0; /* Path (name) of new entry */
  6717. int nName = 0; /* Size of zName in bytes */
  6718. char *zFree = 0; /* Free this before returning */
  6719. int nByte;
  6720. memset(&e, 0, sizeof(e));
  6721. p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
  6722. if( p==0 ) return;
  6723. /* Martial the arguments into stack variables */
  6724. if( nVal!=2 && nVal!=4 && nVal!=5 ){
  6725. zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
  6726. rc = SQLITE_ERROR;
  6727. goto zipfile_step_out;
  6728. }
  6729. pName = apVal[0];
  6730. if( nVal==2 ){
  6731. pData = apVal[1];
  6732. }else{
  6733. pMode = apVal[1];
  6734. pMtime = apVal[2];
  6735. pData = apVal[3];
  6736. if( nVal==5 ){
  6737. pMethod = apVal[4];
  6738. }
  6739. }
  6740. /* Check that the 'name' parameter looks ok. */
  6741. zName = (char*)sqlite3_value_text(pName);
  6742. nName = sqlite3_value_bytes(pName);
  6743. if( zName==0 ){
  6744. zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
  6745. rc = SQLITE_ERROR;
  6746. goto zipfile_step_out;
  6747. }
  6748. /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
  6749. ** deflate compression) or NULL (choose automatically). */
  6750. if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
  6751. iMethod = (int)sqlite3_value_int64(pMethod);
  6752. if( iMethod!=0 && iMethod!=8 ){
  6753. zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
  6754. rc = SQLITE_ERROR;
  6755. goto zipfile_step_out;
  6756. }
  6757. }
  6758. /* Now inspect the data. If this is NULL, then the new entry must be a
  6759. ** directory. Otherwise, figure out whether or not the data should
  6760. ** be deflated or simply stored in the zip archive. */
  6761. if( sqlite3_value_type(pData)==SQLITE_NULL ){
  6762. bIsDir = 1;
  6763. iMethod = 0;
  6764. }else{
  6765. aData = sqlite3_value_blob(pData);
  6766. szUncompressed = nData = sqlite3_value_bytes(pData);
  6767. iCrc32 = crc32(0, aData, nData);
  6768. if( iMethod<0 || iMethod==8 ){
  6769. int nOut = 0;
  6770. rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
  6771. if( rc!=SQLITE_OK ){
  6772. goto zipfile_step_out;
  6773. }
  6774. if( iMethod==8 || nOut<nData ){
  6775. aData = aFree;
  6776. nData = nOut;
  6777. iMethod = 8;
  6778. }else{
  6779. iMethod = 0;
  6780. }
  6781. }
  6782. }
  6783. /* Decode the "mode" argument. */
  6784. rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
  6785. if( rc ) goto zipfile_step_out;
  6786. /* Decode the "mtime" argument. */
  6787. e.mUnixTime = zipfileGetTime(pMtime);
  6788. /* If this is a directory entry, ensure that there is exactly one '/'
  6789. ** at the end of the path. Or, if this is not a directory and the path
  6790. ** ends in '/' it is an error. */
  6791. if( bIsDir==0 ){
  6792. if( nName>0 && zName[nName-1]=='/' ){
  6793. zErr = sqlite3_mprintf("non-directory name must not end with /");
  6794. rc = SQLITE_ERROR;
  6795. goto zipfile_step_out;
  6796. }
  6797. }else{
  6798. if( nName==0 || zName[nName-1]!='/' ){
  6799. zName = zFree = sqlite3_mprintf("%s/", zName);
  6800. if( zName==0 ){
  6801. rc = SQLITE_NOMEM;
  6802. goto zipfile_step_out;
  6803. }
  6804. nName = (int)strlen(zName);
  6805. }else{
  6806. while( nName>1 && zName[nName-2]=='/' ) nName--;
  6807. }
  6808. }
  6809. /* Assemble the ZipfileEntry object for the new zip archive entry */
  6810. e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
  6811. e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
  6812. e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
  6813. e.cds.iCompression = (u16)iMethod;
  6814. zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
  6815. e.cds.crc32 = iCrc32;
  6816. e.cds.szCompressed = nData;
  6817. e.cds.szUncompressed = szUncompressed;
  6818. e.cds.iExternalAttr = (mode<<16);
  6819. e.cds.iOffset = p->body.n;
  6820. e.cds.nFile = (u16)nName;
  6821. e.cds.zFile = zName;
  6822. /* Append the LFH to the body of the new archive */
  6823. nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
  6824. if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
  6825. p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
  6826. /* Append the data to the body of the new archive */
  6827. if( nData>0 ){
  6828. if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
  6829. memcpy(&p->body.a[p->body.n], aData, nData);
  6830. p->body.n += nData;
  6831. }
  6832. /* Append the CDS record to the directory of the new archive */
  6833. nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
  6834. if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
  6835. p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
  6836. /* Increment the count of entries in the archive */
  6837. p->nEntry++;
  6838. zipfile_step_out:
  6839. sqlite3_free(aFree);
  6840. sqlite3_free(zFree);
  6841. if( rc ){
  6842. if( zErr ){
  6843. sqlite3_result_error(pCtx, zErr, -1);
  6844. }else{
  6845. sqlite3_result_error_code(pCtx, rc);
  6846. }
  6847. }
  6848. sqlite3_free(zErr);
  6849. }
  6850. /*
  6851. ** xFinalize() callback for zipfile aggregate function.
  6852. */
  6853. void zipfileFinal(sqlite3_context *pCtx){
  6854. ZipfileCtx *p;
  6855. ZipfileEOCD eocd;
  6856. sqlite3_int64 nZip;
  6857. u8 *aZip;
  6858. p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
  6859. if( p==0 ) return;
  6860. if( p->nEntry>0 ){
  6861. memset(&eocd, 0, sizeof(eocd));
  6862. eocd.nEntry = (u16)p->nEntry;
  6863. eocd.nEntryTotal = (u16)p->nEntry;
  6864. eocd.nSize = p->cds.n;
  6865. eocd.iOffset = p->body.n;
  6866. nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
  6867. aZip = (u8*)sqlite3_malloc64(nZip);
  6868. if( aZip==0 ){
  6869. sqlite3_result_error_nomem(pCtx);
  6870. }else{
  6871. memcpy(aZip, p->body.a, p->body.n);
  6872. memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
  6873. zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
  6874. sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
  6875. }
  6876. }
  6877. sqlite3_free(p->body.a);
  6878. sqlite3_free(p->cds.a);
  6879. }
  6880. /*
  6881. ** Register the "zipfile" virtual table.
  6882. */
  6883. static int zipfileRegister(sqlite3 *db){
  6884. static sqlite3_module zipfileModule = {
  6885. 1, /* iVersion */
  6886. zipfileConnect, /* xCreate */
  6887. zipfileConnect, /* xConnect */
  6888. zipfileBestIndex, /* xBestIndex */
  6889. zipfileDisconnect, /* xDisconnect */
  6890. zipfileDisconnect, /* xDestroy */
  6891. zipfileOpen, /* xOpen - open a cursor */
  6892. zipfileClose, /* xClose - close a cursor */
  6893. zipfileFilter, /* xFilter - configure scan constraints */
  6894. zipfileNext, /* xNext - advance a cursor */
  6895. zipfileEof, /* xEof - check for end of scan */
  6896. zipfileColumn, /* xColumn - read data */
  6897. 0, /* xRowid - read data */
  6898. zipfileUpdate, /* xUpdate */
  6899. zipfileBegin, /* xBegin */
  6900. 0, /* xSync */
  6901. zipfileCommit, /* xCommit */
  6902. zipfileRollback, /* xRollback */
  6903. zipfileFindFunction, /* xFindMethod */
  6904. 0, /* xRename */
  6905. };
  6906. int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0);
  6907. if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
  6908. if( rc==SQLITE_OK ){
  6909. rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
  6910. zipfileStep, zipfileFinal
  6911. );
  6912. }
  6913. return rc;
  6914. }
  6915. #else /* SQLITE_OMIT_VIRTUALTABLE */
  6916. # define zipfileRegister(x) SQLITE_OK
  6917. #endif
  6918. #ifdef _WIN32
  6919. #endif
  6920. int sqlite3_zipfile_init(
  6921. sqlite3 *db,
  6922. char **pzErrMsg,
  6923. const sqlite3_api_routines *pApi
  6924. ){
  6925. SQLITE_EXTENSION_INIT2(pApi);
  6926. (void)pzErrMsg; /* Unused parameter */
  6927. return zipfileRegister(db);
  6928. }
  6929. /************************* End ../ext/misc/zipfile.c ********************/
  6930. /************************* Begin ../ext/misc/sqlar.c ******************/
  6931. /*
  6932. ** 2017-12-17
  6933. **
  6934. ** The author disclaims copyright to this source code. In place of
  6935. ** a legal notice, here is a blessing:
  6936. **
  6937. ** May you do good and not evil.
  6938. ** May you find forgiveness for yourself and forgive others.
  6939. ** May you share freely, never taking more than you give.
  6940. **
  6941. ******************************************************************************
  6942. **
  6943. ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
  6944. ** for working with sqlar archives and used by the shell tool's built-in
  6945. ** sqlar support.
  6946. */
  6947. /* #include "sqlite3ext.h" */
  6948. SQLITE_EXTENSION_INIT1
  6949. #include <zlib.h>
  6950. #include <assert.h>
  6951. /*
  6952. ** Implementation of the "sqlar_compress(X)" SQL function.
  6953. **
  6954. ** If the type of X is SQLITE_BLOB, and compressing that blob using
  6955. ** zlib utility function compress() yields a smaller blob, return the
  6956. ** compressed blob. Otherwise, return a copy of X.
  6957. **
  6958. ** SQLar uses the "zlib format" for compressed content. The zlib format
  6959. ** contains a two-byte identification header and a four-byte checksum at
  6960. ** the end. This is different from ZIP which uses the raw deflate format.
  6961. **
  6962. ** Future enhancements to SQLar might add support for new compression formats.
  6963. ** If so, those new formats will be identified by alternative headers in the
  6964. ** compressed data.
  6965. */
  6966. static void sqlarCompressFunc(
  6967. sqlite3_context *context,
  6968. int argc,
  6969. sqlite3_value **argv
  6970. ){
  6971. assert( argc==1 );
  6972. if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
  6973. const Bytef *pData = sqlite3_value_blob(argv[0]);
  6974. uLong nData = sqlite3_value_bytes(argv[0]);
  6975. uLongf nOut = compressBound(nData);
  6976. Bytef *pOut;
  6977. pOut = (Bytef*)sqlite3_malloc(nOut);
  6978. if( pOut==0 ){
  6979. sqlite3_result_error_nomem(context);
  6980. return;
  6981. }else{
  6982. if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
  6983. sqlite3_result_error(context, "error in compress()", -1);
  6984. }else if( nOut<nData ){
  6985. sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
  6986. }else{
  6987. sqlite3_result_value(context, argv[0]);
  6988. }
  6989. sqlite3_free(pOut);
  6990. }
  6991. }else{
  6992. sqlite3_result_value(context, argv[0]);
  6993. }
  6994. }
  6995. /*
  6996. ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
  6997. **
  6998. ** Parameter SZ is interpreted as an integer. If it is less than or
  6999. ** equal to zero, then this function returns a copy of X. Or, if
  7000. ** SZ is equal to the size of X when interpreted as a blob, also
  7001. ** return a copy of X. Otherwise, decompress blob X using zlib
  7002. ** utility function uncompress() and return the results (another
  7003. ** blob).
  7004. */
  7005. static void sqlarUncompressFunc(
  7006. sqlite3_context *context,
  7007. int argc,
  7008. sqlite3_value **argv
  7009. ){
  7010. uLong nData;
  7011. uLongf sz;
  7012. assert( argc==2 );
  7013. sz = sqlite3_value_int(argv[1]);
  7014. if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
  7015. sqlite3_result_value(context, argv[0]);
  7016. }else{
  7017. const Bytef *pData= sqlite3_value_blob(argv[0]);
  7018. Bytef *pOut = sqlite3_malloc(sz);
  7019. if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
  7020. sqlite3_result_error(context, "error in uncompress()", -1);
  7021. }else{
  7022. sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
  7023. }
  7024. sqlite3_free(pOut);
  7025. }
  7026. }
  7027. #ifdef _WIN32
  7028. #endif
  7029. int sqlite3_sqlar_init(
  7030. sqlite3 *db,
  7031. char **pzErrMsg,
  7032. const sqlite3_api_routines *pApi
  7033. ){
  7034. int rc = SQLITE_OK;
  7035. SQLITE_EXTENSION_INIT2(pApi);
  7036. (void)pzErrMsg; /* Unused parameter */
  7037. rc = sqlite3_create_function(db, "sqlar_compress", 1,
  7038. SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
  7039. sqlarCompressFunc, 0, 0);
  7040. if( rc==SQLITE_OK ){
  7041. rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
  7042. SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
  7043. sqlarUncompressFunc, 0, 0);
  7044. }
  7045. return rc;
  7046. }
  7047. /************************* End ../ext/misc/sqlar.c ********************/
  7048. #endif
  7049. /************************* Begin ../ext/expert/sqlite3expert.h ******************/
  7050. /*
  7051. ** 2017 April 07
  7052. **
  7053. ** The author disclaims copyright to this source code. In place of
  7054. ** a legal notice, here is a blessing:
  7055. **
  7056. ** May you do good and not evil.
  7057. ** May you find forgiveness for yourself and forgive others.
  7058. ** May you share freely, never taking more than you give.
  7059. **
  7060. *************************************************************************
  7061. */
  7062. #if !defined(SQLITEEXPERT_H)
  7063. #define SQLITEEXPERT_H 1
  7064. /* #include "sqlite3.h" */
  7065. typedef struct sqlite3expert sqlite3expert;
  7066. /*
  7067. ** Create a new sqlite3expert object.
  7068. **
  7069. ** If successful, a pointer to the new object is returned and (*pzErr) set
  7070. ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
  7071. ** an English-language error message. In this case it is the responsibility
  7072. ** of the caller to eventually free the error message buffer using
  7073. ** sqlite3_free().
  7074. */
  7075. sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
  7076. /*
  7077. ** Configure an sqlite3expert object.
  7078. **
  7079. ** EXPERT_CONFIG_SAMPLE:
  7080. ** By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
  7081. ** each candidate index. This involves scanning and sorting the entire
  7082. ** contents of each user database table once for each candidate index
  7083. ** associated with the table. For large databases, this can be
  7084. ** prohibitively slow. This option allows the sqlite3expert object to
  7085. ** be configured so that sqlite_stat1 data is instead generated based on a
  7086. ** subset of each table, or so that no sqlite_stat1 data is used at all.
  7087. **
  7088. ** A single integer argument is passed to this option. If the value is less
  7089. ** than or equal to zero, then no sqlite_stat1 data is generated or used by
  7090. ** the analysis - indexes are recommended based on the database schema only.
  7091. ** Or, if the value is 100 or greater, complete sqlite_stat1 data is
  7092. ** generated for each candidate index (this is the default). Finally, if the
  7093. ** value falls between 0 and 100, then it represents the percentage of user
  7094. ** table rows that should be considered when generating sqlite_stat1 data.
  7095. **
  7096. ** Examples:
  7097. **
  7098. ** // Do not generate any sqlite_stat1 data
  7099. ** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
  7100. **
  7101. ** // Generate sqlite_stat1 data based on 10% of the rows in each table.
  7102. ** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
  7103. */
  7104. int sqlite3_expert_config(sqlite3expert *p, int op, ...);
  7105. #define EXPERT_CONFIG_SAMPLE 1 /* int */
  7106. /*
  7107. ** Specify zero or more SQL statements to be included in the analysis.
  7108. **
  7109. ** Buffer zSql must contain zero or more complete SQL statements. This
  7110. ** function parses all statements contained in the buffer and adds them
  7111. ** to the internal list of statements to analyze. If successful, SQLITE_OK
  7112. ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
  7113. ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
  7114. ** may be set to point to an English language error message. In this case
  7115. ** the caller is responsible for eventually freeing the error message buffer
  7116. ** using sqlite3_free().
  7117. **
  7118. ** If an error does occur while processing one of the statements in the
  7119. ** buffer passed as the second argument, none of the statements in the
  7120. ** buffer are added to the analysis.
  7121. **
  7122. ** This function must be called before sqlite3_expert_analyze(). If a call
  7123. ** to this function is made on an sqlite3expert object that has already
  7124. ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
  7125. ** immediately and no statements are added to the analysis.
  7126. */
  7127. int sqlite3_expert_sql(
  7128. sqlite3expert *p, /* From a successful sqlite3_expert_new() */
  7129. const char *zSql, /* SQL statement(s) to add */
  7130. char **pzErr /* OUT: Error message (if any) */
  7131. );
  7132. /*
  7133. ** This function is called after the sqlite3expert object has been configured
  7134. ** with all SQL statements using sqlite3_expert_sql() to actually perform
  7135. ** the analysis. Once this function has been called, it is not possible to
  7136. ** add further SQL statements to the analysis.
  7137. **
  7138. ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
  7139. ** an error occurs, an SQLite error code is returned and (*pzErr) set to
  7140. ** point to a buffer containing an English language error message. In this
  7141. ** case it is the responsibility of the caller to eventually free the buffer
  7142. ** using sqlite3_free().
  7143. **
  7144. ** If an error does occur within this function, the sqlite3expert object
  7145. ** is no longer useful for any purpose. At that point it is no longer
  7146. ** possible to add further SQL statements to the object or to re-attempt
  7147. ** the analysis. The sqlite3expert object must still be freed using a call
  7148. ** sqlite3_expert_destroy().
  7149. */
  7150. int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
  7151. /*
  7152. ** Return the total number of statements loaded using sqlite3_expert_sql().
  7153. ** The total number of SQL statements may be different from the total number
  7154. ** to calls to sqlite3_expert_sql().
  7155. */
  7156. int sqlite3_expert_count(sqlite3expert*);
  7157. /*
  7158. ** Return a component of the report.
  7159. **
  7160. ** This function is called after sqlite3_expert_analyze() to extract the
  7161. ** results of the analysis. Each call to this function returns either a
  7162. ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
  7163. ** The value passed as the third argument must be one of the EXPERT_REPORT_*
  7164. ** #define constants defined below.
  7165. **
  7166. ** For some EXPERT_REPORT_* parameters, the buffer returned contains
  7167. ** information relating to a specific SQL statement. In these cases that
  7168. ** SQL statement is identified by the value passed as the second argument.
  7169. ** SQL statements are numbered from 0 in the order in which they are parsed.
  7170. ** If an out-of-range value (less than zero or equal to or greater than the
  7171. ** value returned by sqlite3_expert_count()) is passed as the second argument
  7172. ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
  7173. **
  7174. ** EXPERT_REPORT_SQL:
  7175. ** Return the text of SQL statement iStmt.
  7176. **
  7177. ** EXPERT_REPORT_INDEXES:
  7178. ** Return a buffer containing the CREATE INDEX statements for all recommended
  7179. ** indexes for statement iStmt. If there are no new recommeded indexes, NULL
  7180. ** is returned.
  7181. **
  7182. ** EXPERT_REPORT_PLAN:
  7183. ** Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
  7184. ** iStmt after the proposed indexes have been added to the database schema.
  7185. **
  7186. ** EXPERT_REPORT_CANDIDATES:
  7187. ** Return a pointer to a buffer containing the CREATE INDEX statements
  7188. ** for all indexes that were tested (for all SQL statements). The iStmt
  7189. ** parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
  7190. */
  7191. const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
  7192. /*
  7193. ** Values for the third argument passed to sqlite3_expert_report().
  7194. */
  7195. #define EXPERT_REPORT_SQL 1
  7196. #define EXPERT_REPORT_INDEXES 2
  7197. #define EXPERT_REPORT_PLAN 3
  7198. #define EXPERT_REPORT_CANDIDATES 4
  7199. /*
  7200. ** Free an (sqlite3expert*) handle and all associated resources. There
  7201. ** should be one call to this function for each successful call to
  7202. ** sqlite3-expert_new().
  7203. */
  7204. void sqlite3_expert_destroy(sqlite3expert*);
  7205. #endif /* !defined(SQLITEEXPERT_H) */
  7206. /************************* End ../ext/expert/sqlite3expert.h ********************/
  7207. /************************* Begin ../ext/expert/sqlite3expert.c ******************/
  7208. /*
  7209. ** 2017 April 09
  7210. **
  7211. ** The author disclaims copyright to this source code. In place of
  7212. ** a legal notice, here is a blessing:
  7213. **
  7214. ** May you do good and not evil.
  7215. ** May you find forgiveness for yourself and forgive others.
  7216. ** May you share freely, never taking more than you give.
  7217. **
  7218. *************************************************************************
  7219. */
  7220. /* #include "sqlite3expert.h" */
  7221. #include <assert.h>
  7222. #include <string.h>
  7223. #include <stdio.h>
  7224. #ifndef SQLITE_OMIT_VIRTUALTABLE
  7225. /* typedef sqlite3_int64 i64; */
  7226. /* typedef sqlite3_uint64 u64; */
  7227. typedef struct IdxColumn IdxColumn;
  7228. typedef struct IdxConstraint IdxConstraint;
  7229. typedef struct IdxScan IdxScan;
  7230. typedef struct IdxStatement IdxStatement;
  7231. typedef struct IdxTable IdxTable;
  7232. typedef struct IdxWrite IdxWrite;
  7233. #define STRLEN (int)strlen
  7234. /*
  7235. ** A temp table name that we assume no user database will actually use.
  7236. ** If this assumption proves incorrect triggers on the table with the
  7237. ** conflicting name will be ignored.
  7238. */
  7239. #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
  7240. /*
  7241. ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
  7242. ** any other type of single-ended range constraint on a column).
  7243. **
  7244. ** pLink:
  7245. ** Used to temporarily link IdxConstraint objects into lists while
  7246. ** creating candidate indexes.
  7247. */
  7248. struct IdxConstraint {
  7249. char *zColl; /* Collation sequence */
  7250. int bRange; /* True for range, false for eq */
  7251. int iCol; /* Constrained table column */
  7252. int bFlag; /* Used by idxFindCompatible() */
  7253. int bDesc; /* True if ORDER BY <expr> DESC */
  7254. IdxConstraint *pNext; /* Next constraint in pEq or pRange list */
  7255. IdxConstraint *pLink; /* See above */
  7256. };
  7257. /*
  7258. ** A single scan of a single table.
  7259. */
  7260. struct IdxScan {
  7261. IdxTable *pTab; /* Associated table object */
  7262. int iDb; /* Database containing table zTable */
  7263. i64 covering; /* Mask of columns required for cov. index */
  7264. IdxConstraint *pOrder; /* ORDER BY columns */
  7265. IdxConstraint *pEq; /* List of == constraints */
  7266. IdxConstraint *pRange; /* List of < constraints */
  7267. IdxScan *pNextScan; /* Next IdxScan object for same analysis */
  7268. };
  7269. /*
  7270. ** Information regarding a single database table. Extracted from
  7271. ** "PRAGMA table_info" by function idxGetTableInfo().
  7272. */
  7273. struct IdxColumn {
  7274. char *zName;
  7275. char *zColl;
  7276. int iPk;
  7277. };
  7278. struct IdxTable {
  7279. int nCol;
  7280. char *zName; /* Table name */
  7281. IdxColumn *aCol;
  7282. IdxTable *pNext; /* Next table in linked list of all tables */
  7283. };
  7284. /*
  7285. ** An object of the following type is created for each unique table/write-op
  7286. ** seen. The objects are stored in a singly-linked list beginning at
  7287. ** sqlite3expert.pWrite.
  7288. */
  7289. struct IdxWrite {
  7290. IdxTable *pTab;
  7291. int eOp; /* SQLITE_UPDATE, DELETE or INSERT */
  7292. IdxWrite *pNext;
  7293. };
  7294. /*
  7295. ** Each statement being analyzed is represented by an instance of this
  7296. ** structure.
  7297. */
  7298. struct IdxStatement {
  7299. int iId; /* Statement number */
  7300. char *zSql; /* SQL statement */
  7301. char *zIdx; /* Indexes */
  7302. char *zEQP; /* Plan */
  7303. IdxStatement *pNext;
  7304. };
  7305. /*
  7306. ** A hash table for storing strings. With space for a payload string
  7307. ** with each entry. Methods are:
  7308. **
  7309. ** idxHashInit()
  7310. ** idxHashClear()
  7311. ** idxHashAdd()
  7312. ** idxHashSearch()
  7313. */
  7314. #define IDX_HASH_SIZE 1023
  7315. typedef struct IdxHashEntry IdxHashEntry;
  7316. typedef struct IdxHash IdxHash;
  7317. struct IdxHashEntry {
  7318. char *zKey; /* nul-terminated key */
  7319. char *zVal; /* nul-terminated value string */
  7320. char *zVal2; /* nul-terminated value string 2 */
  7321. IdxHashEntry *pHashNext; /* Next entry in same hash bucket */
  7322. IdxHashEntry *pNext; /* Next entry in hash */
  7323. };
  7324. struct IdxHash {
  7325. IdxHashEntry *pFirst;
  7326. IdxHashEntry *aHash[IDX_HASH_SIZE];
  7327. };
  7328. /*
  7329. ** sqlite3expert object.
  7330. */
  7331. struct sqlite3expert {
  7332. int iSample; /* Percentage of tables to sample for stat1 */
  7333. sqlite3 *db; /* User database */
  7334. sqlite3 *dbm; /* In-memory db for this analysis */
  7335. sqlite3 *dbv; /* Vtab schema for this analysis */
  7336. IdxTable *pTable; /* List of all IdxTable objects */
  7337. IdxScan *pScan; /* List of scan objects */
  7338. IdxWrite *pWrite; /* List of write objects */
  7339. IdxStatement *pStatement; /* List of IdxStatement objects */
  7340. int bRun; /* True once analysis has run */
  7341. char **pzErrmsg;
  7342. int rc; /* Error code from whereinfo hook */
  7343. IdxHash hIdx; /* Hash containing all candidate indexes */
  7344. char *zCandidates; /* For EXPERT_REPORT_CANDIDATES */
  7345. };
  7346. /*
  7347. ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
  7348. ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
  7349. */
  7350. static void *idxMalloc(int *pRc, int nByte){
  7351. void *pRet;
  7352. assert( *pRc==SQLITE_OK );
  7353. assert( nByte>0 );
  7354. pRet = sqlite3_malloc(nByte);
  7355. if( pRet ){
  7356. memset(pRet, 0, nByte);
  7357. }else{
  7358. *pRc = SQLITE_NOMEM;
  7359. }
  7360. return pRet;
  7361. }
  7362. /*
  7363. ** Initialize an IdxHash hash table.
  7364. */
  7365. static void idxHashInit(IdxHash *pHash){
  7366. memset(pHash, 0, sizeof(IdxHash));
  7367. }
  7368. /*
  7369. ** Reset an IdxHash hash table.
  7370. */
  7371. static void idxHashClear(IdxHash *pHash){
  7372. int i;
  7373. for(i=0; i<IDX_HASH_SIZE; i++){
  7374. IdxHashEntry *pEntry;
  7375. IdxHashEntry *pNext;
  7376. for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
  7377. pNext = pEntry->pHashNext;
  7378. sqlite3_free(pEntry->zVal2);
  7379. sqlite3_free(pEntry);
  7380. }
  7381. }
  7382. memset(pHash, 0, sizeof(IdxHash));
  7383. }
  7384. /*
  7385. ** Return the index of the hash bucket that the string specified by the
  7386. ** arguments to this function belongs.
  7387. */
  7388. static int idxHashString(const char *z, int n){
  7389. unsigned int ret = 0;
  7390. int i;
  7391. for(i=0; i<n; i++){
  7392. ret += (ret<<3) + (unsigned char)(z[i]);
  7393. }
  7394. return (int)(ret % IDX_HASH_SIZE);
  7395. }
  7396. /*
  7397. ** If zKey is already present in the hash table, return non-zero and do
  7398. ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
  7399. ** the hash table passed as the second argument.
  7400. */
  7401. static int idxHashAdd(
  7402. int *pRc,
  7403. IdxHash *pHash,
  7404. const char *zKey,
  7405. const char *zVal
  7406. ){
  7407. int nKey = STRLEN(zKey);
  7408. int iHash = idxHashString(zKey, nKey);
  7409. int nVal = (zVal ? STRLEN(zVal) : 0);
  7410. IdxHashEntry *pEntry;
  7411. assert( iHash>=0 );
  7412. for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
  7413. if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
  7414. return 1;
  7415. }
  7416. }
  7417. pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
  7418. if( pEntry ){
  7419. pEntry->zKey = (char*)&pEntry[1];
  7420. memcpy(pEntry->zKey, zKey, nKey);
  7421. if( zVal ){
  7422. pEntry->zVal = &pEntry->zKey[nKey+1];
  7423. memcpy(pEntry->zVal, zVal, nVal);
  7424. }
  7425. pEntry->pHashNext = pHash->aHash[iHash];
  7426. pHash->aHash[iHash] = pEntry;
  7427. pEntry->pNext = pHash->pFirst;
  7428. pHash->pFirst = pEntry;
  7429. }
  7430. return 0;
  7431. }
  7432. /*
  7433. ** If zKey/nKey is present in the hash table, return a pointer to the
  7434. ** hash-entry object.
  7435. */
  7436. static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
  7437. int iHash;
  7438. IdxHashEntry *pEntry;
  7439. if( nKey<0 ) nKey = STRLEN(zKey);
  7440. iHash = idxHashString(zKey, nKey);
  7441. assert( iHash>=0 );
  7442. for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
  7443. if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
  7444. return pEntry;
  7445. }
  7446. }
  7447. return 0;
  7448. }
  7449. /*
  7450. ** If the hash table contains an entry with a key equal to the string
  7451. ** passed as the final two arguments to this function, return a pointer
  7452. ** to the payload string. Otherwise, if zKey/nKey is not present in the
  7453. ** hash table, return NULL.
  7454. */
  7455. static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
  7456. IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
  7457. if( pEntry ) return pEntry->zVal;
  7458. return 0;
  7459. }
  7460. /*
  7461. ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
  7462. ** variable to point to a copy of nul-terminated string zColl.
  7463. */
  7464. static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
  7465. IdxConstraint *pNew;
  7466. int nColl = STRLEN(zColl);
  7467. assert( *pRc==SQLITE_OK );
  7468. pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
  7469. if( pNew ){
  7470. pNew->zColl = (char*)&pNew[1];
  7471. memcpy(pNew->zColl, zColl, nColl+1);
  7472. }
  7473. return pNew;
  7474. }
  7475. /*
  7476. ** An error associated with database handle db has just occurred. Pass
  7477. ** the error message to callback function xOut.
  7478. */
  7479. static void idxDatabaseError(
  7480. sqlite3 *db, /* Database handle */
  7481. char **pzErrmsg /* Write error here */
  7482. ){
  7483. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  7484. }
  7485. /*
  7486. ** Prepare an SQL statement.
  7487. */
  7488. static int idxPrepareStmt(
  7489. sqlite3 *db, /* Database handle to compile against */
  7490. sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
  7491. char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
  7492. const char *zSql /* SQL statement to compile */
  7493. ){
  7494. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  7495. if( rc!=SQLITE_OK ){
  7496. *ppStmt = 0;
  7497. idxDatabaseError(db, pzErrmsg);
  7498. }
  7499. return rc;
  7500. }
  7501. /*
  7502. ** Prepare an SQL statement using the results of a printf() formatting.
  7503. */
  7504. static int idxPrintfPrepareStmt(
  7505. sqlite3 *db, /* Database handle to compile against */
  7506. sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
  7507. char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
  7508. const char *zFmt, /* printf() format of SQL statement */
  7509. ... /* Trailing printf() arguments */
  7510. ){
  7511. va_list ap;
  7512. int rc;
  7513. char *zSql;
  7514. va_start(ap, zFmt);
  7515. zSql = sqlite3_vmprintf(zFmt, ap);
  7516. if( zSql==0 ){
  7517. rc = SQLITE_NOMEM;
  7518. }else{
  7519. rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
  7520. sqlite3_free(zSql);
  7521. }
  7522. va_end(ap);
  7523. return rc;
  7524. }
  7525. /*************************************************************************
  7526. ** Beginning of virtual table implementation.
  7527. */
  7528. typedef struct ExpertVtab ExpertVtab;
  7529. struct ExpertVtab {
  7530. sqlite3_vtab base;
  7531. IdxTable *pTab;
  7532. sqlite3expert *pExpert;
  7533. };
  7534. typedef struct ExpertCsr ExpertCsr;
  7535. struct ExpertCsr {
  7536. sqlite3_vtab_cursor base;
  7537. sqlite3_stmt *pData;
  7538. };
  7539. static char *expertDequote(const char *zIn){
  7540. int n = STRLEN(zIn);
  7541. char *zRet = sqlite3_malloc(n);
  7542. assert( zIn[0]=='\'' );
  7543. assert( zIn[n-1]=='\'' );
  7544. if( zRet ){
  7545. int iOut = 0;
  7546. int iIn = 0;
  7547. for(iIn=1; iIn<(n-1); iIn++){
  7548. if( zIn[iIn]=='\'' ){
  7549. assert( zIn[iIn+1]=='\'' );
  7550. iIn++;
  7551. }
  7552. zRet[iOut++] = zIn[iIn];
  7553. }
  7554. zRet[iOut] = '\0';
  7555. }
  7556. return zRet;
  7557. }
  7558. /*
  7559. ** This function is the implementation of both the xConnect and xCreate
  7560. ** methods of the r-tree virtual table.
  7561. **
  7562. ** argv[0] -> module name
  7563. ** argv[1] -> database name
  7564. ** argv[2] -> table name
  7565. ** argv[...] -> column names...
  7566. */
  7567. static int expertConnect(
  7568. sqlite3 *db,
  7569. void *pAux,
  7570. int argc, const char *const*argv,
  7571. sqlite3_vtab **ppVtab,
  7572. char **pzErr
  7573. ){
  7574. sqlite3expert *pExpert = (sqlite3expert*)pAux;
  7575. ExpertVtab *p = 0;
  7576. int rc;
  7577. if( argc!=4 ){
  7578. *pzErr = sqlite3_mprintf("internal error!");
  7579. rc = SQLITE_ERROR;
  7580. }else{
  7581. char *zCreateTable = expertDequote(argv[3]);
  7582. if( zCreateTable ){
  7583. rc = sqlite3_declare_vtab(db, zCreateTable);
  7584. if( rc==SQLITE_OK ){
  7585. p = idxMalloc(&rc, sizeof(ExpertVtab));
  7586. }
  7587. if( rc==SQLITE_OK ){
  7588. p->pExpert = pExpert;
  7589. p->pTab = pExpert->pTable;
  7590. assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
  7591. }
  7592. sqlite3_free(zCreateTable);
  7593. }else{
  7594. rc = SQLITE_NOMEM;
  7595. }
  7596. }
  7597. *ppVtab = (sqlite3_vtab*)p;
  7598. return rc;
  7599. }
  7600. static int expertDisconnect(sqlite3_vtab *pVtab){
  7601. ExpertVtab *p = (ExpertVtab*)pVtab;
  7602. sqlite3_free(p);
  7603. return SQLITE_OK;
  7604. }
  7605. static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
  7606. ExpertVtab *p = (ExpertVtab*)pVtab;
  7607. int rc = SQLITE_OK;
  7608. int n = 0;
  7609. IdxScan *pScan;
  7610. const int opmask =
  7611. SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
  7612. SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
  7613. SQLITE_INDEX_CONSTRAINT_LE;
  7614. pScan = idxMalloc(&rc, sizeof(IdxScan));
  7615. if( pScan ){
  7616. int i;
  7617. /* Link the new scan object into the list */
  7618. pScan->pTab = p->pTab;
  7619. pScan->pNextScan = p->pExpert->pScan;
  7620. p->pExpert->pScan = pScan;
  7621. /* Add the constraints to the IdxScan object */
  7622. for(i=0; i<pIdxInfo->nConstraint; i++){
  7623. struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
  7624. if( pCons->usable
  7625. && pCons->iColumn>=0
  7626. && p->pTab->aCol[pCons->iColumn].iPk==0
  7627. && (pCons->op & opmask)
  7628. ){
  7629. IdxConstraint *pNew;
  7630. const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
  7631. pNew = idxNewConstraint(&rc, zColl);
  7632. if( pNew ){
  7633. pNew->iCol = pCons->iColumn;
  7634. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  7635. pNew->pNext = pScan->pEq;
  7636. pScan->pEq = pNew;
  7637. }else{
  7638. pNew->bRange = 1;
  7639. pNew->pNext = pScan->pRange;
  7640. pScan->pRange = pNew;
  7641. }
  7642. }
  7643. n++;
  7644. pIdxInfo->aConstraintUsage[i].argvIndex = n;
  7645. }
  7646. }
  7647. /* Add the ORDER BY to the IdxScan object */
  7648. for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
  7649. int iCol = pIdxInfo->aOrderBy[i].iColumn;
  7650. if( iCol>=0 ){
  7651. IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
  7652. if( pNew ){
  7653. pNew->iCol = iCol;
  7654. pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
  7655. pNew->pNext = pScan->pOrder;
  7656. pNew->pLink = pScan->pOrder;
  7657. pScan->pOrder = pNew;
  7658. n++;
  7659. }
  7660. }
  7661. }
  7662. }
  7663. pIdxInfo->estimatedCost = 1000000.0 / (n+1);
  7664. return rc;
  7665. }
  7666. static int expertUpdate(
  7667. sqlite3_vtab *pVtab,
  7668. int nData,
  7669. sqlite3_value **azData,
  7670. sqlite_int64 *pRowid
  7671. ){
  7672. (void)pVtab;
  7673. (void)nData;
  7674. (void)azData;
  7675. (void)pRowid;
  7676. return SQLITE_OK;
  7677. }
  7678. /*
  7679. ** Virtual table module xOpen method.
  7680. */
  7681. static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  7682. int rc = SQLITE_OK;
  7683. ExpertCsr *pCsr;
  7684. (void)pVTab;
  7685. pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
  7686. *ppCursor = (sqlite3_vtab_cursor*)pCsr;
  7687. return rc;
  7688. }
  7689. /*
  7690. ** Virtual table module xClose method.
  7691. */
  7692. static int expertClose(sqlite3_vtab_cursor *cur){
  7693. ExpertCsr *pCsr = (ExpertCsr*)cur;
  7694. sqlite3_finalize(pCsr->pData);
  7695. sqlite3_free(pCsr);
  7696. return SQLITE_OK;
  7697. }
  7698. /*
  7699. ** Virtual table module xEof method.
  7700. **
  7701. ** Return non-zero if the cursor does not currently point to a valid
  7702. ** record (i.e if the scan has finished), or zero otherwise.
  7703. */
  7704. static int expertEof(sqlite3_vtab_cursor *cur){
  7705. ExpertCsr *pCsr = (ExpertCsr*)cur;
  7706. return pCsr->pData==0;
  7707. }
  7708. /*
  7709. ** Virtual table module xNext method.
  7710. */
  7711. static int expertNext(sqlite3_vtab_cursor *cur){
  7712. ExpertCsr *pCsr = (ExpertCsr*)cur;
  7713. int rc = SQLITE_OK;
  7714. assert( pCsr->pData );
  7715. rc = sqlite3_step(pCsr->pData);
  7716. if( rc!=SQLITE_ROW ){
  7717. rc = sqlite3_finalize(pCsr->pData);
  7718. pCsr->pData = 0;
  7719. }else{
  7720. rc = SQLITE_OK;
  7721. }
  7722. return rc;
  7723. }
  7724. /*
  7725. ** Virtual table module xRowid method.
  7726. */
  7727. static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  7728. (void)cur;
  7729. *pRowid = 0;
  7730. return SQLITE_OK;
  7731. }
  7732. /*
  7733. ** Virtual table module xColumn method.
  7734. */
  7735. static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  7736. ExpertCsr *pCsr = (ExpertCsr*)cur;
  7737. sqlite3_value *pVal;
  7738. pVal = sqlite3_column_value(pCsr->pData, i);
  7739. if( pVal ){
  7740. sqlite3_result_value(ctx, pVal);
  7741. }
  7742. return SQLITE_OK;
  7743. }
  7744. /*
  7745. ** Virtual table module xFilter method.
  7746. */
  7747. static int expertFilter(
  7748. sqlite3_vtab_cursor *cur,
  7749. int idxNum, const char *idxStr,
  7750. int argc, sqlite3_value **argv
  7751. ){
  7752. ExpertCsr *pCsr = (ExpertCsr*)cur;
  7753. ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
  7754. sqlite3expert *pExpert = pVtab->pExpert;
  7755. int rc;
  7756. (void)idxNum;
  7757. (void)idxStr;
  7758. (void)argc;
  7759. (void)argv;
  7760. rc = sqlite3_finalize(pCsr->pData);
  7761. pCsr->pData = 0;
  7762. if( rc==SQLITE_OK ){
  7763. rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
  7764. "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
  7765. );
  7766. }
  7767. if( rc==SQLITE_OK ){
  7768. rc = expertNext(cur);
  7769. }
  7770. return rc;
  7771. }
  7772. static int idxRegisterVtab(sqlite3expert *p){
  7773. static sqlite3_module expertModule = {
  7774. 2, /* iVersion */
  7775. expertConnect, /* xCreate - create a table */
  7776. expertConnect, /* xConnect - connect to an existing table */
  7777. expertBestIndex, /* xBestIndex - Determine search strategy */
  7778. expertDisconnect, /* xDisconnect - Disconnect from a table */
  7779. expertDisconnect, /* xDestroy - Drop a table */
  7780. expertOpen, /* xOpen - open a cursor */
  7781. expertClose, /* xClose - close a cursor */
  7782. expertFilter, /* xFilter - configure scan constraints */
  7783. expertNext, /* xNext - advance a cursor */
  7784. expertEof, /* xEof */
  7785. expertColumn, /* xColumn - read data */
  7786. expertRowid, /* xRowid - read data */
  7787. expertUpdate, /* xUpdate - write data */
  7788. 0, /* xBegin - begin transaction */
  7789. 0, /* xSync - sync transaction */
  7790. 0, /* xCommit - commit transaction */
  7791. 0, /* xRollback - rollback transaction */
  7792. 0, /* xFindFunction - function overloading */
  7793. 0, /* xRename - rename the table */
  7794. 0, /* xSavepoint */
  7795. 0, /* xRelease */
  7796. 0, /* xRollbackTo */
  7797. 0, /* xShadowName */
  7798. };
  7799. return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
  7800. }
  7801. /*
  7802. ** End of virtual table implementation.
  7803. *************************************************************************/
  7804. /*
  7805. ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
  7806. ** is called, set it to the return value of sqlite3_finalize() before
  7807. ** returning. Otherwise, discard the sqlite3_finalize() return value.
  7808. */
  7809. static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
  7810. int rc = sqlite3_finalize(pStmt);
  7811. if( *pRc==SQLITE_OK ) *pRc = rc;
  7812. }
  7813. /*
  7814. ** Attempt to allocate an IdxTable structure corresponding to table zTab
  7815. ** in the main database of connection db. If successful, set (*ppOut) to
  7816. ** point to the new object and return SQLITE_OK. Otherwise, return an
  7817. ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
  7818. ** set to point to an error string.
  7819. **
  7820. ** It is the responsibility of the caller to eventually free either the
  7821. ** IdxTable object or error message using sqlite3_free().
  7822. */
  7823. static int idxGetTableInfo(
  7824. sqlite3 *db, /* Database connection to read details from */
  7825. const char *zTab, /* Table name */
  7826. IdxTable **ppOut, /* OUT: New object (if successful) */
  7827. char **pzErrmsg /* OUT: Error message (if not) */
  7828. ){
  7829. sqlite3_stmt *p1 = 0;
  7830. int nCol = 0;
  7831. int nTab = STRLEN(zTab);
  7832. int nByte = sizeof(IdxTable) + nTab + 1;
  7833. IdxTable *pNew = 0;
  7834. int rc, rc2;
  7835. char *pCsr = 0;
  7836. rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_info=%Q", zTab);
  7837. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
  7838. const char *zCol = (const char*)sqlite3_column_text(p1, 1);
  7839. nByte += 1 + STRLEN(zCol);
  7840. rc = sqlite3_table_column_metadata(
  7841. db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
  7842. );
  7843. nByte += 1 + STRLEN(zCol);
  7844. nCol++;
  7845. }
  7846. rc2 = sqlite3_reset(p1);
  7847. if( rc==SQLITE_OK ) rc = rc2;
  7848. nByte += sizeof(IdxColumn) * nCol;
  7849. if( rc==SQLITE_OK ){
  7850. pNew = idxMalloc(&rc, nByte);
  7851. }
  7852. if( rc==SQLITE_OK ){
  7853. pNew->aCol = (IdxColumn*)&pNew[1];
  7854. pNew->nCol = nCol;
  7855. pCsr = (char*)&pNew->aCol[nCol];
  7856. }
  7857. nCol = 0;
  7858. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
  7859. const char *zCol = (const char*)sqlite3_column_text(p1, 1);
  7860. int nCopy = STRLEN(zCol) + 1;
  7861. pNew->aCol[nCol].zName = pCsr;
  7862. pNew->aCol[nCol].iPk = sqlite3_column_int(p1, 5);
  7863. memcpy(pCsr, zCol, nCopy);
  7864. pCsr += nCopy;
  7865. rc = sqlite3_table_column_metadata(
  7866. db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
  7867. );
  7868. if( rc==SQLITE_OK ){
  7869. nCopy = STRLEN(zCol) + 1;
  7870. pNew->aCol[nCol].zColl = pCsr;
  7871. memcpy(pCsr, zCol, nCopy);
  7872. pCsr += nCopy;
  7873. }
  7874. nCol++;
  7875. }
  7876. idxFinalize(&rc, p1);
  7877. if( rc!=SQLITE_OK ){
  7878. sqlite3_free(pNew);
  7879. pNew = 0;
  7880. }else{
  7881. pNew->zName = pCsr;
  7882. memcpy(pNew->zName, zTab, nTab+1);
  7883. }
  7884. *ppOut = pNew;
  7885. return rc;
  7886. }
  7887. /*
  7888. ** This function is a no-op if *pRc is set to anything other than
  7889. ** SQLITE_OK when it is called.
  7890. **
  7891. ** If *pRc is initially set to SQLITE_OK, then the text specified by
  7892. ** the printf() style arguments is appended to zIn and the result returned
  7893. ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
  7894. ** zIn before returning.
  7895. */
  7896. static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
  7897. va_list ap;
  7898. char *zAppend = 0;
  7899. char *zRet = 0;
  7900. int nIn = zIn ? STRLEN(zIn) : 0;
  7901. int nAppend = 0;
  7902. va_start(ap, zFmt);
  7903. if( *pRc==SQLITE_OK ){
  7904. zAppend = sqlite3_vmprintf(zFmt, ap);
  7905. if( zAppend ){
  7906. nAppend = STRLEN(zAppend);
  7907. zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
  7908. }
  7909. if( zAppend && zRet ){
  7910. if( nIn ) memcpy(zRet, zIn, nIn);
  7911. memcpy(&zRet[nIn], zAppend, nAppend+1);
  7912. }else{
  7913. sqlite3_free(zRet);
  7914. zRet = 0;
  7915. *pRc = SQLITE_NOMEM;
  7916. }
  7917. sqlite3_free(zAppend);
  7918. sqlite3_free(zIn);
  7919. }
  7920. va_end(ap);
  7921. return zRet;
  7922. }
  7923. /*
  7924. ** Return true if zId must be quoted in order to use it as an SQL
  7925. ** identifier, or false otherwise.
  7926. */
  7927. static int idxIdentifierRequiresQuotes(const char *zId){
  7928. int i;
  7929. for(i=0; zId[i]; i++){
  7930. if( !(zId[i]=='_')
  7931. && !(zId[i]>='0' && zId[i]<='9')
  7932. && !(zId[i]>='a' && zId[i]<='z')
  7933. && !(zId[i]>='A' && zId[i]<='Z')
  7934. ){
  7935. return 1;
  7936. }
  7937. }
  7938. return 0;
  7939. }
  7940. /*
  7941. ** This function appends an index column definition suitable for constraint
  7942. ** pCons to the string passed as zIn and returns the result.
  7943. */
  7944. static char *idxAppendColDefn(
  7945. int *pRc, /* IN/OUT: Error code */
  7946. char *zIn, /* Column defn accumulated so far */
  7947. IdxTable *pTab, /* Table index will be created on */
  7948. IdxConstraint *pCons
  7949. ){
  7950. char *zRet = zIn;
  7951. IdxColumn *p = &pTab->aCol[pCons->iCol];
  7952. if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
  7953. if( idxIdentifierRequiresQuotes(p->zName) ){
  7954. zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
  7955. }else{
  7956. zRet = idxAppendText(pRc, zRet, "%s", p->zName);
  7957. }
  7958. if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
  7959. if( idxIdentifierRequiresQuotes(pCons->zColl) ){
  7960. zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
  7961. }else{
  7962. zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
  7963. }
  7964. }
  7965. if( pCons->bDesc ){
  7966. zRet = idxAppendText(pRc, zRet, " DESC");
  7967. }
  7968. return zRet;
  7969. }
  7970. /*
  7971. ** Search database dbm for an index compatible with the one idxCreateFromCons()
  7972. ** would create from arguments pScan, pEq and pTail. If no error occurs and
  7973. ** such an index is found, return non-zero. Or, if no such index is found,
  7974. ** return zero.
  7975. **
  7976. ** If an error occurs, set *pRc to an SQLite error code and return zero.
  7977. */
  7978. static int idxFindCompatible(
  7979. int *pRc, /* OUT: Error code */
  7980. sqlite3* dbm, /* Database to search */
  7981. IdxScan *pScan, /* Scan for table to search for index on */
  7982. IdxConstraint *pEq, /* List of == constraints */
  7983. IdxConstraint *pTail /* List of range constraints */
  7984. ){
  7985. const char *zTbl = pScan->pTab->zName;
  7986. sqlite3_stmt *pIdxList = 0;
  7987. IdxConstraint *pIter;
  7988. int nEq = 0; /* Number of elements in pEq */
  7989. int rc;
  7990. /* Count the elements in list pEq */
  7991. for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
  7992. rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
  7993. while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
  7994. int bMatch = 1;
  7995. IdxConstraint *pT = pTail;
  7996. sqlite3_stmt *pInfo = 0;
  7997. const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
  7998. /* Zero the IdxConstraint.bFlag values in the pEq list */
  7999. for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
  8000. rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
  8001. while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
  8002. int iIdx = sqlite3_column_int(pInfo, 0);
  8003. int iCol = sqlite3_column_int(pInfo, 1);
  8004. const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
  8005. if( iIdx<nEq ){
  8006. for(pIter=pEq; pIter; pIter=pIter->pLink){
  8007. if( pIter->bFlag ) continue;
  8008. if( pIter->iCol!=iCol ) continue;
  8009. if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
  8010. pIter->bFlag = 1;
  8011. break;
  8012. }
  8013. if( pIter==0 ){
  8014. bMatch = 0;
  8015. break;
  8016. }
  8017. }else{
  8018. if( pT ){
  8019. if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
  8020. bMatch = 0;
  8021. break;
  8022. }
  8023. pT = pT->pLink;
  8024. }
  8025. }
  8026. }
  8027. idxFinalize(&rc, pInfo);
  8028. if( rc==SQLITE_OK && bMatch ){
  8029. sqlite3_finalize(pIdxList);
  8030. return 1;
  8031. }
  8032. }
  8033. idxFinalize(&rc, pIdxList);
  8034. *pRc = rc;
  8035. return 0;
  8036. }
  8037. static int idxCreateFromCons(
  8038. sqlite3expert *p,
  8039. IdxScan *pScan,
  8040. IdxConstraint *pEq,
  8041. IdxConstraint *pTail
  8042. ){
  8043. sqlite3 *dbm = p->dbm;
  8044. int rc = SQLITE_OK;
  8045. if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
  8046. IdxTable *pTab = pScan->pTab;
  8047. char *zCols = 0;
  8048. char *zIdx = 0;
  8049. IdxConstraint *pCons;
  8050. unsigned int h = 0;
  8051. const char *zFmt;
  8052. for(pCons=pEq; pCons; pCons=pCons->pLink){
  8053. zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
  8054. }
  8055. for(pCons=pTail; pCons; pCons=pCons->pLink){
  8056. zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
  8057. }
  8058. if( rc==SQLITE_OK ){
  8059. /* Hash the list of columns to come up with a name for the index */
  8060. const char *zTable = pScan->pTab->zName;
  8061. char *zName; /* Index name */
  8062. int i;
  8063. for(i=0; zCols[i]; i++){
  8064. h += ((h<<3) + zCols[i]);
  8065. }
  8066. zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
  8067. if( zName==0 ){
  8068. rc = SQLITE_NOMEM;
  8069. }else{
  8070. if( idxIdentifierRequiresQuotes(zTable) ){
  8071. zFmt = "CREATE INDEX '%q' ON %Q(%s)";
  8072. }else{
  8073. zFmt = "CREATE INDEX %s ON %s(%s)";
  8074. }
  8075. zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
  8076. if( !zIdx ){
  8077. rc = SQLITE_NOMEM;
  8078. }else{
  8079. rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
  8080. idxHashAdd(&rc, &p->hIdx, zName, zIdx);
  8081. }
  8082. sqlite3_free(zName);
  8083. sqlite3_free(zIdx);
  8084. }
  8085. }
  8086. sqlite3_free(zCols);
  8087. }
  8088. return rc;
  8089. }
  8090. /*
  8091. ** Return true if list pList (linked by IdxConstraint.pLink) contains
  8092. ** a constraint compatible with *p. Otherwise return false.
  8093. */
  8094. static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
  8095. IdxConstraint *pCmp;
  8096. for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
  8097. if( p->iCol==pCmp->iCol ) return 1;
  8098. }
  8099. return 0;
  8100. }
  8101. static int idxCreateFromWhere(
  8102. sqlite3expert *p,
  8103. IdxScan *pScan, /* Create indexes for this scan */
  8104. IdxConstraint *pTail /* range/ORDER BY constraints for inclusion */
  8105. ){
  8106. IdxConstraint *p1 = 0;
  8107. IdxConstraint *pCon;
  8108. int rc;
  8109. /* Gather up all the == constraints. */
  8110. for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
  8111. if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
  8112. pCon->pLink = p1;
  8113. p1 = pCon;
  8114. }
  8115. }
  8116. /* Create an index using the == constraints collected above. And the
  8117. ** range constraint/ORDER BY terms passed in by the caller, if any. */
  8118. rc = idxCreateFromCons(p, pScan, p1, pTail);
  8119. /* If no range/ORDER BY passed by the caller, create a version of the
  8120. ** index for each range constraint. */
  8121. if( pTail==0 ){
  8122. for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
  8123. assert( pCon->pLink==0 );
  8124. if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
  8125. rc = idxCreateFromCons(p, pScan, p1, pCon);
  8126. }
  8127. }
  8128. }
  8129. return rc;
  8130. }
  8131. /*
  8132. ** Create candidate indexes in database [dbm] based on the data in
  8133. ** linked-list pScan.
  8134. */
  8135. static int idxCreateCandidates(sqlite3expert *p){
  8136. int rc = SQLITE_OK;
  8137. IdxScan *pIter;
  8138. for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
  8139. rc = idxCreateFromWhere(p, pIter, 0);
  8140. if( rc==SQLITE_OK && pIter->pOrder ){
  8141. rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
  8142. }
  8143. }
  8144. return rc;
  8145. }
  8146. /*
  8147. ** Free all elements of the linked list starting at pConstraint.
  8148. */
  8149. static void idxConstraintFree(IdxConstraint *pConstraint){
  8150. IdxConstraint *pNext;
  8151. IdxConstraint *p;
  8152. for(p=pConstraint; p; p=pNext){
  8153. pNext = p->pNext;
  8154. sqlite3_free(p);
  8155. }
  8156. }
  8157. /*
  8158. ** Free all elements of the linked list starting from pScan up until pLast
  8159. ** (pLast is not freed).
  8160. */
  8161. static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
  8162. IdxScan *p;
  8163. IdxScan *pNext;
  8164. for(p=pScan; p!=pLast; p=pNext){
  8165. pNext = p->pNextScan;
  8166. idxConstraintFree(p->pOrder);
  8167. idxConstraintFree(p->pEq);
  8168. idxConstraintFree(p->pRange);
  8169. sqlite3_free(p);
  8170. }
  8171. }
  8172. /*
  8173. ** Free all elements of the linked list starting from pStatement up
  8174. ** until pLast (pLast is not freed).
  8175. */
  8176. static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
  8177. IdxStatement *p;
  8178. IdxStatement *pNext;
  8179. for(p=pStatement; p!=pLast; p=pNext){
  8180. pNext = p->pNext;
  8181. sqlite3_free(p->zEQP);
  8182. sqlite3_free(p->zIdx);
  8183. sqlite3_free(p);
  8184. }
  8185. }
  8186. /*
  8187. ** Free the linked list of IdxTable objects starting at pTab.
  8188. */
  8189. static void idxTableFree(IdxTable *pTab){
  8190. IdxTable *pIter;
  8191. IdxTable *pNext;
  8192. for(pIter=pTab; pIter; pIter=pNext){
  8193. pNext = pIter->pNext;
  8194. sqlite3_free(pIter);
  8195. }
  8196. }
  8197. /*
  8198. ** Free the linked list of IdxWrite objects starting at pTab.
  8199. */
  8200. static void idxWriteFree(IdxWrite *pTab){
  8201. IdxWrite *pIter;
  8202. IdxWrite *pNext;
  8203. for(pIter=pTab; pIter; pIter=pNext){
  8204. pNext = pIter->pNext;
  8205. sqlite3_free(pIter);
  8206. }
  8207. }
  8208. /*
  8209. ** This function is called after candidate indexes have been created. It
  8210. ** runs all the queries to see which indexes they prefer, and populates
  8211. ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
  8212. */
  8213. int idxFindIndexes(
  8214. sqlite3expert *p,
  8215. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  8216. ){
  8217. IdxStatement *pStmt;
  8218. sqlite3 *dbm = p->dbm;
  8219. int rc = SQLITE_OK;
  8220. IdxHash hIdx;
  8221. idxHashInit(&hIdx);
  8222. for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
  8223. IdxHashEntry *pEntry;
  8224. sqlite3_stmt *pExplain = 0;
  8225. idxHashClear(&hIdx);
  8226. rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
  8227. "EXPLAIN QUERY PLAN %s", pStmt->zSql
  8228. );
  8229. while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
  8230. /* int iId = sqlite3_column_int(pExplain, 0); */
  8231. /* int iParent = sqlite3_column_int(pExplain, 1); */
  8232. /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
  8233. const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
  8234. int nDetail;
  8235. int i;
  8236. if( !zDetail ) continue;
  8237. nDetail = STRLEN(zDetail);
  8238. for(i=0; i<nDetail; i++){
  8239. const char *zIdx = 0;
  8240. if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
  8241. zIdx = &zDetail[i+13];
  8242. }else if( i+22<nDetail
  8243. && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
  8244. ){
  8245. zIdx = &zDetail[i+22];
  8246. }
  8247. if( zIdx ){
  8248. const char *zSql;
  8249. int nIdx = 0;
  8250. while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
  8251. nIdx++;
  8252. }
  8253. zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
  8254. if( zSql ){
  8255. idxHashAdd(&rc, &hIdx, zSql, 0);
  8256. if( rc ) goto find_indexes_out;
  8257. }
  8258. break;
  8259. }
  8260. }
  8261. if( zDetail[0]!='-' ){
  8262. pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
  8263. }
  8264. }
  8265. for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
  8266. pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
  8267. }
  8268. idxFinalize(&rc, pExplain);
  8269. }
  8270. find_indexes_out:
  8271. idxHashClear(&hIdx);
  8272. return rc;
  8273. }
  8274. static int idxAuthCallback(
  8275. void *pCtx,
  8276. int eOp,
  8277. const char *z3,
  8278. const char *z4,
  8279. const char *zDb,
  8280. const char *zTrigger
  8281. ){
  8282. int rc = SQLITE_OK;
  8283. (void)z4;
  8284. (void)zTrigger;
  8285. if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
  8286. if( sqlite3_stricmp(zDb, "main")==0 ){
  8287. sqlite3expert *p = (sqlite3expert*)pCtx;
  8288. IdxTable *pTab;
  8289. for(pTab=p->pTable; pTab; pTab=pTab->pNext){
  8290. if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
  8291. }
  8292. if( pTab ){
  8293. IdxWrite *pWrite;
  8294. for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
  8295. if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
  8296. }
  8297. if( pWrite==0 ){
  8298. pWrite = idxMalloc(&rc, sizeof(IdxWrite));
  8299. if( rc==SQLITE_OK ){
  8300. pWrite->pTab = pTab;
  8301. pWrite->eOp = eOp;
  8302. pWrite->pNext = p->pWrite;
  8303. p->pWrite = pWrite;
  8304. }
  8305. }
  8306. }
  8307. }
  8308. }
  8309. return rc;
  8310. }
  8311. static int idxProcessOneTrigger(
  8312. sqlite3expert *p,
  8313. IdxWrite *pWrite,
  8314. char **pzErr
  8315. ){
  8316. static const char *zInt = UNIQUE_TABLE_NAME;
  8317. static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
  8318. IdxTable *pTab = pWrite->pTab;
  8319. const char *zTab = pTab->zName;
  8320. const char *zSql =
  8321. "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
  8322. "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
  8323. "ORDER BY type;";
  8324. sqlite3_stmt *pSelect = 0;
  8325. int rc = SQLITE_OK;
  8326. char *zWrite = 0;
  8327. /* Create the table and its triggers in the temp schema */
  8328. rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
  8329. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
  8330. const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
  8331. rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
  8332. }
  8333. idxFinalize(&rc, pSelect);
  8334. /* Rename the table in the temp schema to zInt */
  8335. if( rc==SQLITE_OK ){
  8336. char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
  8337. if( z==0 ){
  8338. rc = SQLITE_NOMEM;
  8339. }else{
  8340. rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
  8341. sqlite3_free(z);
  8342. }
  8343. }
  8344. switch( pWrite->eOp ){
  8345. case SQLITE_INSERT: {
  8346. int i;
  8347. zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
  8348. for(i=0; i<pTab->nCol; i++){
  8349. zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
  8350. }
  8351. zWrite = idxAppendText(&rc, zWrite, ")");
  8352. break;
  8353. }
  8354. case SQLITE_UPDATE: {
  8355. int i;
  8356. zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
  8357. for(i=0; i<pTab->nCol; i++){
  8358. zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
  8359. pTab->aCol[i].zName
  8360. );
  8361. }
  8362. break;
  8363. }
  8364. default: {
  8365. assert( pWrite->eOp==SQLITE_DELETE );
  8366. if( rc==SQLITE_OK ){
  8367. zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
  8368. if( zWrite==0 ) rc = SQLITE_NOMEM;
  8369. }
  8370. }
  8371. }
  8372. if( rc==SQLITE_OK ){
  8373. sqlite3_stmt *pX = 0;
  8374. rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
  8375. idxFinalize(&rc, pX);
  8376. if( rc!=SQLITE_OK ){
  8377. idxDatabaseError(p->dbv, pzErr);
  8378. }
  8379. }
  8380. sqlite3_free(zWrite);
  8381. if( rc==SQLITE_OK ){
  8382. rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
  8383. }
  8384. return rc;
  8385. }
  8386. static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
  8387. int rc = SQLITE_OK;
  8388. IdxWrite *pEnd = 0;
  8389. IdxWrite *pFirst = p->pWrite;
  8390. while( rc==SQLITE_OK && pFirst!=pEnd ){
  8391. IdxWrite *pIter;
  8392. for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
  8393. rc = idxProcessOneTrigger(p, pIter, pzErr);
  8394. }
  8395. pEnd = pFirst;
  8396. pFirst = p->pWrite;
  8397. }
  8398. return rc;
  8399. }
  8400. static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
  8401. int rc = idxRegisterVtab(p);
  8402. sqlite3_stmt *pSchema = 0;
  8403. /* For each table in the main db schema:
  8404. **
  8405. ** 1) Add an entry to the p->pTable list, and
  8406. ** 2) Create the equivalent virtual table in dbv.
  8407. */
  8408. rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
  8409. "SELECT type, name, sql, 1 FROM sqlite_schema "
  8410. "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
  8411. " UNION ALL "
  8412. "SELECT type, name, sql, 2 FROM sqlite_schema "
  8413. "WHERE type = 'trigger'"
  8414. " AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
  8415. "ORDER BY 4, 1"
  8416. );
  8417. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
  8418. const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
  8419. const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
  8420. const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
  8421. if( zType[0]=='v' || zType[1]=='r' ){
  8422. rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
  8423. }else{
  8424. IdxTable *pTab;
  8425. rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
  8426. if( rc==SQLITE_OK ){
  8427. int i;
  8428. char *zInner = 0;
  8429. char *zOuter = 0;
  8430. pTab->pNext = p->pTable;
  8431. p->pTable = pTab;
  8432. /* The statement the vtab will pass to sqlite3_declare_vtab() */
  8433. zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
  8434. for(i=0; i<pTab->nCol; i++){
  8435. zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
  8436. (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
  8437. );
  8438. }
  8439. zInner = idxAppendText(&rc, zInner, ")");
  8440. /* The CVT statement to create the vtab */
  8441. zOuter = idxAppendText(&rc, 0,
  8442. "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
  8443. );
  8444. if( rc==SQLITE_OK ){
  8445. rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
  8446. }
  8447. sqlite3_free(zInner);
  8448. sqlite3_free(zOuter);
  8449. }
  8450. }
  8451. }
  8452. idxFinalize(&rc, pSchema);
  8453. return rc;
  8454. }
  8455. struct IdxSampleCtx {
  8456. int iTarget;
  8457. double target; /* Target nRet/nRow value */
  8458. double nRow; /* Number of rows seen */
  8459. double nRet; /* Number of rows returned */
  8460. };
  8461. static void idxSampleFunc(
  8462. sqlite3_context *pCtx,
  8463. int argc,
  8464. sqlite3_value **argv
  8465. ){
  8466. struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
  8467. int bRet;
  8468. (void)argv;
  8469. assert( argc==0 );
  8470. if( p->nRow==0.0 ){
  8471. bRet = 1;
  8472. }else{
  8473. bRet = (p->nRet / p->nRow) <= p->target;
  8474. if( bRet==0 ){
  8475. unsigned short rnd;
  8476. sqlite3_randomness(2, (void*)&rnd);
  8477. bRet = ((int)rnd % 100) <= p->iTarget;
  8478. }
  8479. }
  8480. sqlite3_result_int(pCtx, bRet);
  8481. p->nRow += 1.0;
  8482. p->nRet += (double)bRet;
  8483. }
  8484. struct IdxRemCtx {
  8485. int nSlot;
  8486. struct IdxRemSlot {
  8487. int eType; /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
  8488. i64 iVal; /* SQLITE_INTEGER value */
  8489. double rVal; /* SQLITE_FLOAT value */
  8490. int nByte; /* Bytes of space allocated at z */
  8491. int n; /* Size of buffer z */
  8492. char *z; /* SQLITE_TEXT/BLOB value */
  8493. } aSlot[1];
  8494. };
  8495. /*
  8496. ** Implementation of scalar function rem().
  8497. */
  8498. static void idxRemFunc(
  8499. sqlite3_context *pCtx,
  8500. int argc,
  8501. sqlite3_value **argv
  8502. ){
  8503. struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
  8504. struct IdxRemSlot *pSlot;
  8505. int iSlot;
  8506. assert( argc==2 );
  8507. iSlot = sqlite3_value_int(argv[0]);
  8508. assert( iSlot<=p->nSlot );
  8509. pSlot = &p->aSlot[iSlot];
  8510. switch( pSlot->eType ){
  8511. case SQLITE_NULL:
  8512. /* no-op */
  8513. break;
  8514. case SQLITE_INTEGER:
  8515. sqlite3_result_int64(pCtx, pSlot->iVal);
  8516. break;
  8517. case SQLITE_FLOAT:
  8518. sqlite3_result_double(pCtx, pSlot->rVal);
  8519. break;
  8520. case SQLITE_BLOB:
  8521. sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
  8522. break;
  8523. case SQLITE_TEXT:
  8524. sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
  8525. break;
  8526. }
  8527. pSlot->eType = sqlite3_value_type(argv[1]);
  8528. switch( pSlot->eType ){
  8529. case SQLITE_NULL:
  8530. /* no-op */
  8531. break;
  8532. case SQLITE_INTEGER:
  8533. pSlot->iVal = sqlite3_value_int64(argv[1]);
  8534. break;
  8535. case SQLITE_FLOAT:
  8536. pSlot->rVal = sqlite3_value_double(argv[1]);
  8537. break;
  8538. case SQLITE_BLOB:
  8539. case SQLITE_TEXT: {
  8540. int nByte = sqlite3_value_bytes(argv[1]);
  8541. if( nByte>pSlot->nByte ){
  8542. char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
  8543. if( zNew==0 ){
  8544. sqlite3_result_error_nomem(pCtx);
  8545. return;
  8546. }
  8547. pSlot->nByte = nByte*2;
  8548. pSlot->z = zNew;
  8549. }
  8550. pSlot->n = nByte;
  8551. if( pSlot->eType==SQLITE_BLOB ){
  8552. memcpy(pSlot->z, sqlite3_value_blob(argv[1]), nByte);
  8553. }else{
  8554. memcpy(pSlot->z, sqlite3_value_text(argv[1]), nByte);
  8555. }
  8556. break;
  8557. }
  8558. }
  8559. }
  8560. static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
  8561. int rc = SQLITE_OK;
  8562. const char *zMax =
  8563. "SELECT max(i.seqno) FROM "
  8564. " sqlite_schema AS s, "
  8565. " pragma_index_list(s.name) AS l, "
  8566. " pragma_index_info(l.name) AS i "
  8567. "WHERE s.type = 'table'";
  8568. sqlite3_stmt *pMax = 0;
  8569. *pnMax = 0;
  8570. rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
  8571. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
  8572. *pnMax = sqlite3_column_int(pMax, 0) + 1;
  8573. }
  8574. idxFinalize(&rc, pMax);
  8575. return rc;
  8576. }
  8577. static int idxPopulateOneStat1(
  8578. sqlite3expert *p,
  8579. sqlite3_stmt *pIndexXInfo,
  8580. sqlite3_stmt *pWriteStat,
  8581. const char *zTab,
  8582. const char *zIdx,
  8583. char **pzErr
  8584. ){
  8585. char *zCols = 0;
  8586. char *zOrder = 0;
  8587. char *zQuery = 0;
  8588. int nCol = 0;
  8589. int i;
  8590. sqlite3_stmt *pQuery = 0;
  8591. int *aStat = 0;
  8592. int rc = SQLITE_OK;
  8593. assert( p->iSample>0 );
  8594. /* Formulate the query text */
  8595. sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
  8596. while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
  8597. const char *zComma = zCols==0 ? "" : ", ";
  8598. const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
  8599. const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
  8600. zCols = idxAppendText(&rc, zCols,
  8601. "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
  8602. );
  8603. zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
  8604. }
  8605. sqlite3_reset(pIndexXInfo);
  8606. if( rc==SQLITE_OK ){
  8607. if( p->iSample==100 ){
  8608. zQuery = sqlite3_mprintf(
  8609. "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
  8610. );
  8611. }else{
  8612. zQuery = sqlite3_mprintf(
  8613. "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
  8614. );
  8615. }
  8616. }
  8617. sqlite3_free(zCols);
  8618. sqlite3_free(zOrder);
  8619. /* Formulate the query text */
  8620. if( rc==SQLITE_OK ){
  8621. sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
  8622. rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
  8623. }
  8624. sqlite3_free(zQuery);
  8625. if( rc==SQLITE_OK ){
  8626. aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
  8627. }
  8628. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
  8629. IdxHashEntry *pEntry;
  8630. char *zStat = 0;
  8631. for(i=0; i<=nCol; i++) aStat[i] = 1;
  8632. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
  8633. aStat[0]++;
  8634. for(i=0; i<nCol; i++){
  8635. if( sqlite3_column_int(pQuery, i)==0 ) break;
  8636. }
  8637. for(/*no-op*/; i<nCol; i++){
  8638. aStat[i+1]++;
  8639. }
  8640. }
  8641. if( rc==SQLITE_OK ){
  8642. int s0 = aStat[0];
  8643. zStat = sqlite3_mprintf("%d", s0);
  8644. if( zStat==0 ) rc = SQLITE_NOMEM;
  8645. for(i=1; rc==SQLITE_OK && i<=nCol; i++){
  8646. zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
  8647. }
  8648. }
  8649. if( rc==SQLITE_OK ){
  8650. sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
  8651. sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
  8652. sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
  8653. sqlite3_step(pWriteStat);
  8654. rc = sqlite3_reset(pWriteStat);
  8655. }
  8656. pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
  8657. if( pEntry ){
  8658. assert( pEntry->zVal2==0 );
  8659. pEntry->zVal2 = zStat;
  8660. }else{
  8661. sqlite3_free(zStat);
  8662. }
  8663. }
  8664. sqlite3_free(aStat);
  8665. idxFinalize(&rc, pQuery);
  8666. return rc;
  8667. }
  8668. static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
  8669. int rc;
  8670. char *zSql;
  8671. rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
  8672. if( rc!=SQLITE_OK ) return rc;
  8673. zSql = sqlite3_mprintf(
  8674. "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
  8675. );
  8676. if( zSql==0 ) return SQLITE_NOMEM;
  8677. rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
  8678. sqlite3_free(zSql);
  8679. return rc;
  8680. }
  8681. /*
  8682. ** This function is called as part of sqlite3_expert_analyze(). Candidate
  8683. ** indexes have already been created in database sqlite3expert.dbm, this
  8684. ** function populates sqlite_stat1 table in the same database.
  8685. **
  8686. ** The stat1 data is generated by querying the
  8687. */
  8688. static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
  8689. int rc = SQLITE_OK;
  8690. int nMax =0;
  8691. struct IdxRemCtx *pCtx = 0;
  8692. struct IdxSampleCtx samplectx;
  8693. int i;
  8694. i64 iPrev = -100000;
  8695. sqlite3_stmt *pAllIndex = 0;
  8696. sqlite3_stmt *pIndexXInfo = 0;
  8697. sqlite3_stmt *pWrite = 0;
  8698. const char *zAllIndex =
  8699. "SELECT s.rowid, s.name, l.name FROM "
  8700. " sqlite_schema AS s, "
  8701. " pragma_index_list(s.name) AS l "
  8702. "WHERE s.type = 'table'";
  8703. const char *zIndexXInfo =
  8704. "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
  8705. const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
  8706. /* If iSample==0, no sqlite_stat1 data is required. */
  8707. if( p->iSample==0 ) return SQLITE_OK;
  8708. rc = idxLargestIndex(p->dbm, &nMax, pzErr);
  8709. if( nMax<=0 || rc!=SQLITE_OK ) return rc;
  8710. rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
  8711. if( rc==SQLITE_OK ){
  8712. int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
  8713. pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
  8714. }
  8715. if( rc==SQLITE_OK ){
  8716. sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
  8717. rc = sqlite3_create_function(
  8718. dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
  8719. );
  8720. }
  8721. if( rc==SQLITE_OK ){
  8722. rc = sqlite3_create_function(
  8723. p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
  8724. );
  8725. }
  8726. if( rc==SQLITE_OK ){
  8727. pCtx->nSlot = nMax+1;
  8728. rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
  8729. }
  8730. if( rc==SQLITE_OK ){
  8731. rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
  8732. }
  8733. if( rc==SQLITE_OK ){
  8734. rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
  8735. }
  8736. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
  8737. i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
  8738. const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
  8739. const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
  8740. if( p->iSample<100 && iPrev!=iRowid ){
  8741. samplectx.target = (double)p->iSample / 100.0;
  8742. samplectx.iTarget = p->iSample;
  8743. samplectx.nRow = 0.0;
  8744. samplectx.nRet = 0.0;
  8745. rc = idxBuildSampleTable(p, zTab);
  8746. if( rc!=SQLITE_OK ) break;
  8747. }
  8748. rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
  8749. iPrev = iRowid;
  8750. }
  8751. if( rc==SQLITE_OK && p->iSample<100 ){
  8752. rc = sqlite3_exec(p->dbv,
  8753. "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
  8754. );
  8755. }
  8756. idxFinalize(&rc, pAllIndex);
  8757. idxFinalize(&rc, pIndexXInfo);
  8758. idxFinalize(&rc, pWrite);
  8759. for(i=0; i<pCtx->nSlot; i++){
  8760. sqlite3_free(pCtx->aSlot[i].z);
  8761. }
  8762. sqlite3_free(pCtx);
  8763. if( rc==SQLITE_OK ){
  8764. rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
  8765. }
  8766. sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
  8767. return rc;
  8768. }
  8769. /*
  8770. ** Allocate a new sqlite3expert object.
  8771. */
  8772. sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
  8773. int rc = SQLITE_OK;
  8774. sqlite3expert *pNew;
  8775. pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
  8776. /* Open two in-memory databases to work with. The "vtab database" (dbv)
  8777. ** will contain a virtual table corresponding to each real table in
  8778. ** the user database schema, and a copy of each view. It is used to
  8779. ** collect information regarding the WHERE, ORDER BY and other clauses
  8780. ** of the user's query.
  8781. */
  8782. if( rc==SQLITE_OK ){
  8783. pNew->db = db;
  8784. pNew->iSample = 100;
  8785. rc = sqlite3_open(":memory:", &pNew->dbv);
  8786. }
  8787. if( rc==SQLITE_OK ){
  8788. rc = sqlite3_open(":memory:", &pNew->dbm);
  8789. if( rc==SQLITE_OK ){
  8790. sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
  8791. }
  8792. }
  8793. /* Copy the entire schema of database [db] into [dbm]. */
  8794. if( rc==SQLITE_OK ){
  8795. sqlite3_stmt *pSql;
  8796. rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
  8797. "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
  8798. " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
  8799. );
  8800. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  8801. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  8802. rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
  8803. }
  8804. idxFinalize(&rc, pSql);
  8805. }
  8806. /* Create the vtab schema */
  8807. if( rc==SQLITE_OK ){
  8808. rc = idxCreateVtabSchema(pNew, pzErrmsg);
  8809. }
  8810. /* Register the auth callback with dbv */
  8811. if( rc==SQLITE_OK ){
  8812. sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
  8813. }
  8814. /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
  8815. ** return the new sqlite3expert handle. */
  8816. if( rc!=SQLITE_OK ){
  8817. sqlite3_expert_destroy(pNew);
  8818. pNew = 0;
  8819. }
  8820. return pNew;
  8821. }
  8822. /*
  8823. ** Configure an sqlite3expert object.
  8824. */
  8825. int sqlite3_expert_config(sqlite3expert *p, int op, ...){
  8826. int rc = SQLITE_OK;
  8827. va_list ap;
  8828. va_start(ap, op);
  8829. switch( op ){
  8830. case EXPERT_CONFIG_SAMPLE: {
  8831. int iVal = va_arg(ap, int);
  8832. if( iVal<0 ) iVal = 0;
  8833. if( iVal>100 ) iVal = 100;
  8834. p->iSample = iVal;
  8835. break;
  8836. }
  8837. default:
  8838. rc = SQLITE_NOTFOUND;
  8839. break;
  8840. }
  8841. va_end(ap);
  8842. return rc;
  8843. }
  8844. /*
  8845. ** Add an SQL statement to the analysis.
  8846. */
  8847. int sqlite3_expert_sql(
  8848. sqlite3expert *p, /* From sqlite3_expert_new() */
  8849. const char *zSql, /* SQL statement to add */
  8850. char **pzErr /* OUT: Error message (if any) */
  8851. ){
  8852. IdxScan *pScanOrig = p->pScan;
  8853. IdxStatement *pStmtOrig = p->pStatement;
  8854. int rc = SQLITE_OK;
  8855. const char *zStmt = zSql;
  8856. if( p->bRun ) return SQLITE_MISUSE;
  8857. while( rc==SQLITE_OK && zStmt && zStmt[0] ){
  8858. sqlite3_stmt *pStmt = 0;
  8859. rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
  8860. if( rc==SQLITE_OK ){
  8861. if( pStmt ){
  8862. IdxStatement *pNew;
  8863. const char *z = sqlite3_sql(pStmt);
  8864. int n = STRLEN(z);
  8865. pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
  8866. if( rc==SQLITE_OK ){
  8867. pNew->zSql = (char*)&pNew[1];
  8868. memcpy(pNew->zSql, z, n+1);
  8869. pNew->pNext = p->pStatement;
  8870. if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
  8871. p->pStatement = pNew;
  8872. }
  8873. sqlite3_finalize(pStmt);
  8874. }
  8875. }else{
  8876. idxDatabaseError(p->dbv, pzErr);
  8877. }
  8878. }
  8879. if( rc!=SQLITE_OK ){
  8880. idxScanFree(p->pScan, pScanOrig);
  8881. idxStatementFree(p->pStatement, pStmtOrig);
  8882. p->pScan = pScanOrig;
  8883. p->pStatement = pStmtOrig;
  8884. }
  8885. return rc;
  8886. }
  8887. int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
  8888. int rc;
  8889. IdxHashEntry *pEntry;
  8890. /* Do trigger processing to collect any extra IdxScan structures */
  8891. rc = idxProcessTriggers(p, pzErr);
  8892. /* Create candidate indexes within the in-memory database file */
  8893. if( rc==SQLITE_OK ){
  8894. rc = idxCreateCandidates(p);
  8895. }
  8896. /* Generate the stat1 data */
  8897. if( rc==SQLITE_OK ){
  8898. rc = idxPopulateStat1(p, pzErr);
  8899. }
  8900. /* Formulate the EXPERT_REPORT_CANDIDATES text */
  8901. for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
  8902. p->zCandidates = idxAppendText(&rc, p->zCandidates,
  8903. "%s;%s%s\n", pEntry->zVal,
  8904. pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
  8905. );
  8906. }
  8907. /* Figure out which of the candidate indexes are preferred by the query
  8908. ** planner and report the results to the user. */
  8909. if( rc==SQLITE_OK ){
  8910. rc = idxFindIndexes(p, pzErr);
  8911. }
  8912. if( rc==SQLITE_OK ){
  8913. p->bRun = 1;
  8914. }
  8915. return rc;
  8916. }
  8917. /*
  8918. ** Return the total number of statements that have been added to this
  8919. ** sqlite3expert using sqlite3_expert_sql().
  8920. */
  8921. int sqlite3_expert_count(sqlite3expert *p){
  8922. int nRet = 0;
  8923. if( p->pStatement ) nRet = p->pStatement->iId+1;
  8924. return nRet;
  8925. }
  8926. /*
  8927. ** Return a component of the report.
  8928. */
  8929. const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
  8930. const char *zRet = 0;
  8931. IdxStatement *pStmt;
  8932. if( p->bRun==0 ) return 0;
  8933. for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
  8934. switch( eReport ){
  8935. case EXPERT_REPORT_SQL:
  8936. if( pStmt ) zRet = pStmt->zSql;
  8937. break;
  8938. case EXPERT_REPORT_INDEXES:
  8939. if( pStmt ) zRet = pStmt->zIdx;
  8940. break;
  8941. case EXPERT_REPORT_PLAN:
  8942. if( pStmt ) zRet = pStmt->zEQP;
  8943. break;
  8944. case EXPERT_REPORT_CANDIDATES:
  8945. zRet = p->zCandidates;
  8946. break;
  8947. }
  8948. return zRet;
  8949. }
  8950. /*
  8951. ** Free an sqlite3expert object.
  8952. */
  8953. void sqlite3_expert_destroy(sqlite3expert *p){
  8954. if( p ){
  8955. sqlite3_close(p->dbm);
  8956. sqlite3_close(p->dbv);
  8957. idxScanFree(p->pScan, 0);
  8958. idxStatementFree(p->pStatement, 0);
  8959. idxTableFree(p->pTable);
  8960. idxWriteFree(p->pWrite);
  8961. idxHashClear(&p->hIdx);
  8962. sqlite3_free(p->zCandidates);
  8963. sqlite3_free(p);
  8964. }
  8965. }
  8966. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  8967. /************************* End ../ext/expert/sqlite3expert.c ********************/
  8968. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
  8969. /************************* Begin ../ext/misc/dbdata.c ******************/
  8970. /*
  8971. ** 2019-04-17
  8972. **
  8973. ** The author disclaims copyright to this source code. In place of
  8974. ** a legal notice, here is a blessing:
  8975. **
  8976. ** May you do good and not evil.
  8977. ** May you find forgiveness for yourself and forgive others.
  8978. ** May you share freely, never taking more than you give.
  8979. **
  8980. ******************************************************************************
  8981. **
  8982. ** This file contains an implementation of two eponymous virtual tables,
  8983. ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
  8984. ** "sqlite_dbpage" eponymous virtual table be available.
  8985. **
  8986. ** SQLITE_DBDATA:
  8987. ** sqlite_dbdata is used to extract data directly from a database b-tree
  8988. ** page and its associated overflow pages, bypassing the b-tree layer.
  8989. ** The table schema is equivalent to:
  8990. **
  8991. ** CREATE TABLE sqlite_dbdata(
  8992. ** pgno INTEGER,
  8993. ** cell INTEGER,
  8994. ** field INTEGER,
  8995. ** value ANY,
  8996. ** schema TEXT HIDDEN
  8997. ** );
  8998. **
  8999. ** IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
  9000. ** FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
  9001. ** "schema".
  9002. **
  9003. ** Each page of the database is inspected. If it cannot be interpreted as
  9004. ** a b-tree page, or if it is a b-tree page containing 0 entries, the
  9005. ** sqlite_dbdata table contains no rows for that page. Otherwise, the
  9006. ** table contains one row for each field in the record associated with
  9007. ** each cell on the page. For intkey b-trees, the key value is stored in
  9008. ** field -1.
  9009. **
  9010. ** For example, for the database:
  9011. **
  9012. ** CREATE TABLE t1(a, b); -- root page is page 2
  9013. ** INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
  9014. ** INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
  9015. **
  9016. ** the sqlite_dbdata table contains, as well as from entries related to
  9017. ** page 1, content equivalent to:
  9018. **
  9019. ** INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
  9020. ** (2, 0, -1, 5 ),
  9021. ** (2, 0, 0, 'v' ),
  9022. ** (2, 0, 1, 'five'),
  9023. ** (2, 1, -1, 10 ),
  9024. ** (2, 1, 0, 'x' ),
  9025. ** (2, 1, 1, 'ten' );
  9026. **
  9027. ** If database corruption is encountered, this module does not report an
  9028. ** error. Instead, it attempts to extract as much data as possible and
  9029. ** ignores the corruption.
  9030. **
  9031. ** SQLITE_DBPTR:
  9032. ** The sqlite_dbptr table has the following schema:
  9033. **
  9034. ** CREATE TABLE sqlite_dbptr(
  9035. ** pgno INTEGER,
  9036. ** child INTEGER,
  9037. ** schema TEXT HIDDEN
  9038. ** );
  9039. **
  9040. ** It contains one entry for each b-tree pointer between a parent and
  9041. ** child page in the database.
  9042. */
  9043. #if !defined(SQLITEINT_H)
  9044. /* #include "sqlite3ext.h" */
  9045. /* typedef unsigned char u8; */
  9046. #endif
  9047. SQLITE_EXTENSION_INIT1
  9048. #include <string.h>
  9049. #include <assert.h>
  9050. #define DBDATA_PADDING_BYTES 100
  9051. typedef struct DbdataTable DbdataTable;
  9052. typedef struct DbdataCursor DbdataCursor;
  9053. /* Cursor object */
  9054. struct DbdataCursor {
  9055. sqlite3_vtab_cursor base; /* Base class. Must be first */
  9056. sqlite3_stmt *pStmt; /* For fetching database pages */
  9057. int iPgno; /* Current page number */
  9058. u8 *aPage; /* Buffer containing page */
  9059. int nPage; /* Size of aPage[] in bytes */
  9060. int nCell; /* Number of cells on aPage[] */
  9061. int iCell; /* Current cell number */
  9062. int bOnePage; /* True to stop after one page */
  9063. int szDb;
  9064. sqlite3_int64 iRowid;
  9065. /* Only for the sqlite_dbdata table */
  9066. u8 *pRec; /* Buffer containing current record */
  9067. int nRec; /* Size of pRec[] in bytes */
  9068. int nHdr; /* Size of header in bytes */
  9069. int iField; /* Current field number */
  9070. u8 *pHdrPtr;
  9071. u8 *pPtr;
  9072. sqlite3_int64 iIntkey; /* Integer key value */
  9073. };
  9074. /* Table object */
  9075. struct DbdataTable {
  9076. sqlite3_vtab base; /* Base class. Must be first */
  9077. sqlite3 *db; /* The database connection */
  9078. sqlite3_stmt *pStmt; /* For fetching database pages */
  9079. int bPtr; /* True for sqlite3_dbptr table */
  9080. };
  9081. /* Column and schema definitions for sqlite_dbdata */
  9082. #define DBDATA_COLUMN_PGNO 0
  9083. #define DBDATA_COLUMN_CELL 1
  9084. #define DBDATA_COLUMN_FIELD 2
  9085. #define DBDATA_COLUMN_VALUE 3
  9086. #define DBDATA_COLUMN_SCHEMA 4
  9087. #define DBDATA_SCHEMA \
  9088. "CREATE TABLE x(" \
  9089. " pgno INTEGER," \
  9090. " cell INTEGER," \
  9091. " field INTEGER," \
  9092. " value ANY," \
  9093. " schema TEXT HIDDEN" \
  9094. ")"
  9095. /* Column and schema definitions for sqlite_dbptr */
  9096. #define DBPTR_COLUMN_PGNO 0
  9097. #define DBPTR_COLUMN_CHILD 1
  9098. #define DBPTR_COLUMN_SCHEMA 2
  9099. #define DBPTR_SCHEMA \
  9100. "CREATE TABLE x(" \
  9101. " pgno INTEGER," \
  9102. " child INTEGER," \
  9103. " schema TEXT HIDDEN" \
  9104. ")"
  9105. /*
  9106. ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
  9107. ** table.
  9108. */
  9109. static int dbdataConnect(
  9110. sqlite3 *db,
  9111. void *pAux,
  9112. int argc, const char *const*argv,
  9113. sqlite3_vtab **ppVtab,
  9114. char **pzErr
  9115. ){
  9116. DbdataTable *pTab = 0;
  9117. int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
  9118. if( rc==SQLITE_OK ){
  9119. pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
  9120. if( pTab==0 ){
  9121. rc = SQLITE_NOMEM;
  9122. }else{
  9123. memset(pTab, 0, sizeof(DbdataTable));
  9124. pTab->db = db;
  9125. pTab->bPtr = (pAux!=0);
  9126. }
  9127. }
  9128. *ppVtab = (sqlite3_vtab*)pTab;
  9129. return rc;
  9130. }
  9131. /*
  9132. ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
  9133. */
  9134. static int dbdataDisconnect(sqlite3_vtab *pVtab){
  9135. DbdataTable *pTab = (DbdataTable*)pVtab;
  9136. if( pTab ){
  9137. sqlite3_finalize(pTab->pStmt);
  9138. sqlite3_free(pVtab);
  9139. }
  9140. return SQLITE_OK;
  9141. }
  9142. /*
  9143. ** This function interprets two types of constraints:
  9144. **
  9145. ** schema=?
  9146. ** pgno=?
  9147. **
  9148. ** If neither are present, idxNum is set to 0. If schema=? is present,
  9149. ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
  9150. ** in idxNum is set.
  9151. **
  9152. ** If both parameters are present, schema is in position 0 and pgno in
  9153. ** position 1.
  9154. */
  9155. static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
  9156. DbdataTable *pTab = (DbdataTable*)tab;
  9157. int i;
  9158. int iSchema = -1;
  9159. int iPgno = -1;
  9160. int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
  9161. for(i=0; i<pIdx->nConstraint; i++){
  9162. struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
  9163. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  9164. if( p->iColumn==colSchema ){
  9165. if( p->usable==0 ) return SQLITE_CONSTRAINT;
  9166. iSchema = i;
  9167. }
  9168. if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
  9169. iPgno = i;
  9170. }
  9171. }
  9172. }
  9173. if( iSchema>=0 ){
  9174. pIdx->aConstraintUsage[iSchema].argvIndex = 1;
  9175. pIdx->aConstraintUsage[iSchema].omit = 1;
  9176. }
  9177. if( iPgno>=0 ){
  9178. pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
  9179. pIdx->aConstraintUsage[iPgno].omit = 1;
  9180. pIdx->estimatedCost = 100;
  9181. pIdx->estimatedRows = 50;
  9182. if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
  9183. int iCol = pIdx->aOrderBy[0].iColumn;
  9184. if( pIdx->nOrderBy==1 ){
  9185. pIdx->orderByConsumed = (iCol==0 || iCol==1);
  9186. }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
  9187. pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
  9188. }
  9189. }
  9190. }else{
  9191. pIdx->estimatedCost = 100000000;
  9192. pIdx->estimatedRows = 1000000000;
  9193. }
  9194. pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
  9195. return SQLITE_OK;
  9196. }
  9197. /*
  9198. ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
  9199. */
  9200. static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  9201. DbdataCursor *pCsr;
  9202. pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
  9203. if( pCsr==0 ){
  9204. return SQLITE_NOMEM;
  9205. }else{
  9206. memset(pCsr, 0, sizeof(DbdataCursor));
  9207. pCsr->base.pVtab = pVTab;
  9208. }
  9209. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  9210. return SQLITE_OK;
  9211. }
  9212. /*
  9213. ** Restore a cursor object to the state it was in when first allocated
  9214. ** by dbdataOpen().
  9215. */
  9216. static void dbdataResetCursor(DbdataCursor *pCsr){
  9217. DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
  9218. if( pTab->pStmt==0 ){
  9219. pTab->pStmt = pCsr->pStmt;
  9220. }else{
  9221. sqlite3_finalize(pCsr->pStmt);
  9222. }
  9223. pCsr->pStmt = 0;
  9224. pCsr->iPgno = 1;
  9225. pCsr->iCell = 0;
  9226. pCsr->iField = 0;
  9227. pCsr->bOnePage = 0;
  9228. sqlite3_free(pCsr->aPage);
  9229. sqlite3_free(pCsr->pRec);
  9230. pCsr->pRec = 0;
  9231. pCsr->aPage = 0;
  9232. }
  9233. /*
  9234. ** Close an sqlite_dbdata or sqlite_dbptr cursor.
  9235. */
  9236. static int dbdataClose(sqlite3_vtab_cursor *pCursor){
  9237. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  9238. dbdataResetCursor(pCsr);
  9239. sqlite3_free(pCsr);
  9240. return SQLITE_OK;
  9241. }
  9242. /*
  9243. ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
  9244. */
  9245. static unsigned int get_uint16(unsigned char *a){
  9246. return (a[0]<<8)|a[1];
  9247. }
  9248. static unsigned int get_uint32(unsigned char *a){
  9249. return ((unsigned int)a[0]<<24)
  9250. | ((unsigned int)a[1]<<16)
  9251. | ((unsigned int)a[2]<<8)
  9252. | ((unsigned int)a[3]);
  9253. }
  9254. /*
  9255. ** Load page pgno from the database via the sqlite_dbpage virtual table.
  9256. ** If successful, set (*ppPage) to point to a buffer containing the page
  9257. ** data, (*pnPage) to the size of that buffer in bytes and return
  9258. ** SQLITE_OK. In this case it is the responsibility of the caller to
  9259. ** eventually free the buffer using sqlite3_free().
  9260. **
  9261. ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
  9262. ** return an SQLite error code.
  9263. */
  9264. static int dbdataLoadPage(
  9265. DbdataCursor *pCsr, /* Cursor object */
  9266. unsigned int pgno, /* Page number of page to load */
  9267. u8 **ppPage, /* OUT: pointer to page buffer */
  9268. int *pnPage /* OUT: Size of (*ppPage) in bytes */
  9269. ){
  9270. int rc2;
  9271. int rc = SQLITE_OK;
  9272. sqlite3_stmt *pStmt = pCsr->pStmt;
  9273. *ppPage = 0;
  9274. *pnPage = 0;
  9275. sqlite3_bind_int64(pStmt, 2, pgno);
  9276. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  9277. int nCopy = sqlite3_column_bytes(pStmt, 0);
  9278. if( nCopy>0 ){
  9279. u8 *pPage;
  9280. pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
  9281. if( pPage==0 ){
  9282. rc = SQLITE_NOMEM;
  9283. }else{
  9284. const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
  9285. memcpy(pPage, pCopy, nCopy);
  9286. memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
  9287. }
  9288. *ppPage = pPage;
  9289. *pnPage = nCopy;
  9290. }
  9291. }
  9292. rc2 = sqlite3_reset(pStmt);
  9293. if( rc==SQLITE_OK ) rc = rc2;
  9294. return rc;
  9295. }
  9296. /*
  9297. ** Read a varint. Put the value in *pVal and return the number of bytes.
  9298. */
  9299. static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
  9300. sqlite3_int64 v = 0;
  9301. int i;
  9302. for(i=0; i<8; i++){
  9303. v = (v<<7) + (z[i]&0x7f);
  9304. if( (z[i]&0x80)==0 ){ *pVal = v; return i+1; }
  9305. }
  9306. v = (v<<8) + (z[i]&0xff);
  9307. *pVal = v;
  9308. return 9;
  9309. }
  9310. /*
  9311. ** Return the number of bytes of space used by an SQLite value of type
  9312. ** eType.
  9313. */
  9314. static int dbdataValueBytes(int eType){
  9315. switch( eType ){
  9316. case 0: case 8: case 9:
  9317. case 10: case 11:
  9318. return 0;
  9319. case 1:
  9320. return 1;
  9321. case 2:
  9322. return 2;
  9323. case 3:
  9324. return 3;
  9325. case 4:
  9326. return 4;
  9327. case 5:
  9328. return 6;
  9329. case 6:
  9330. case 7:
  9331. return 8;
  9332. default:
  9333. if( eType>0 ){
  9334. return ((eType-12) / 2);
  9335. }
  9336. return 0;
  9337. }
  9338. }
  9339. /*
  9340. ** Load a value of type eType from buffer pData and use it to set the
  9341. ** result of context object pCtx.
  9342. */
  9343. static void dbdataValue(
  9344. sqlite3_context *pCtx,
  9345. int eType,
  9346. u8 *pData,
  9347. int nData
  9348. ){
  9349. if( eType>=0 && dbdataValueBytes(eType)<=nData ){
  9350. switch( eType ){
  9351. case 0:
  9352. case 10:
  9353. case 11:
  9354. sqlite3_result_null(pCtx);
  9355. break;
  9356. case 8:
  9357. sqlite3_result_int(pCtx, 0);
  9358. break;
  9359. case 9:
  9360. sqlite3_result_int(pCtx, 1);
  9361. break;
  9362. case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
  9363. sqlite3_uint64 v = (signed char)pData[0];
  9364. pData++;
  9365. switch( eType ){
  9366. case 7:
  9367. case 6: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2;
  9368. case 5: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2;
  9369. case 4: v = (v<<8) + pData[0]; pData++;
  9370. case 3: v = (v<<8) + pData[0]; pData++;
  9371. case 2: v = (v<<8) + pData[0]; pData++;
  9372. }
  9373. if( eType==7 ){
  9374. double r;
  9375. memcpy(&r, &v, sizeof(r));
  9376. sqlite3_result_double(pCtx, r);
  9377. }else{
  9378. sqlite3_result_int64(pCtx, (sqlite3_int64)v);
  9379. }
  9380. break;
  9381. }
  9382. default: {
  9383. int n = ((eType-12) / 2);
  9384. if( eType % 2 ){
  9385. sqlite3_result_text(pCtx, (const char*)pData, n, SQLITE_TRANSIENT);
  9386. }else{
  9387. sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
  9388. }
  9389. }
  9390. }
  9391. }
  9392. }
  9393. /*
  9394. ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
  9395. */
  9396. static int dbdataNext(sqlite3_vtab_cursor *pCursor){
  9397. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  9398. DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
  9399. pCsr->iRowid++;
  9400. while( 1 ){
  9401. int rc;
  9402. int iOff = (pCsr->iPgno==1 ? 100 : 0);
  9403. int bNextPage = 0;
  9404. if( pCsr->aPage==0 ){
  9405. while( 1 ){
  9406. if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
  9407. rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
  9408. if( rc!=SQLITE_OK ) return rc;
  9409. if( pCsr->aPage ) break;
  9410. pCsr->iPgno++;
  9411. }
  9412. pCsr->iCell = pTab->bPtr ? -2 : 0;
  9413. pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
  9414. }
  9415. if( pTab->bPtr ){
  9416. if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
  9417. pCsr->iCell = pCsr->nCell;
  9418. }
  9419. pCsr->iCell++;
  9420. if( pCsr->iCell>=pCsr->nCell ){
  9421. sqlite3_free(pCsr->aPage);
  9422. pCsr->aPage = 0;
  9423. if( pCsr->bOnePage ) return SQLITE_OK;
  9424. pCsr->iPgno++;
  9425. }else{
  9426. return SQLITE_OK;
  9427. }
  9428. }else{
  9429. /* If there is no record loaded, load it now. */
  9430. if( pCsr->pRec==0 ){
  9431. int bHasRowid = 0;
  9432. int nPointer = 0;
  9433. sqlite3_int64 nPayload = 0;
  9434. sqlite3_int64 nHdr = 0;
  9435. int iHdr;
  9436. int U, X;
  9437. int nLocal;
  9438. switch( pCsr->aPage[iOff] ){
  9439. case 0x02:
  9440. nPointer = 4;
  9441. break;
  9442. case 0x0a:
  9443. break;
  9444. case 0x0d:
  9445. bHasRowid = 1;
  9446. break;
  9447. default:
  9448. /* This is not a b-tree page with records on it. Continue. */
  9449. pCsr->iCell = pCsr->nCell;
  9450. break;
  9451. }
  9452. if( pCsr->iCell>=pCsr->nCell ){
  9453. bNextPage = 1;
  9454. }else{
  9455. iOff += 8 + nPointer + pCsr->iCell*2;
  9456. if( iOff>pCsr->nPage ){
  9457. bNextPage = 1;
  9458. }else{
  9459. iOff = get_uint16(&pCsr->aPage[iOff]);
  9460. }
  9461. /* For an interior node cell, skip past the child-page number */
  9462. iOff += nPointer;
  9463. /* Load the "byte of payload including overflow" field */
  9464. if( bNextPage || iOff>pCsr->nPage ){
  9465. bNextPage = 1;
  9466. }else{
  9467. iOff += dbdataGetVarint(&pCsr->aPage[iOff], &nPayload);
  9468. }
  9469. /* If this is a leaf intkey cell, load the rowid */
  9470. if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
  9471. iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
  9472. }
  9473. /* Figure out how much data to read from the local page */
  9474. U = pCsr->nPage;
  9475. if( bHasRowid ){
  9476. X = U-35;
  9477. }else{
  9478. X = ((U-12)*64/255)-23;
  9479. }
  9480. if( nPayload<=X ){
  9481. nLocal = nPayload;
  9482. }else{
  9483. int M, K;
  9484. M = ((U-12)*32/255)-23;
  9485. K = M+((nPayload-M)%(U-4));
  9486. if( K<=X ){
  9487. nLocal = K;
  9488. }else{
  9489. nLocal = M;
  9490. }
  9491. }
  9492. if( bNextPage || nLocal+iOff>pCsr->nPage ){
  9493. bNextPage = 1;
  9494. }else{
  9495. /* Allocate space for payload. And a bit more to catch small buffer
  9496. ** overruns caused by attempting to read a varint or similar from
  9497. ** near the end of a corrupt record. */
  9498. pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
  9499. if( pCsr->pRec==0 ) return SQLITE_NOMEM;
  9500. memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
  9501. pCsr->nRec = nPayload;
  9502. /* Load the nLocal bytes of payload */
  9503. memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
  9504. iOff += nLocal;
  9505. /* Load content from overflow pages */
  9506. if( nPayload>nLocal ){
  9507. sqlite3_int64 nRem = nPayload - nLocal;
  9508. unsigned int pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
  9509. while( nRem>0 ){
  9510. u8 *aOvfl = 0;
  9511. int nOvfl = 0;
  9512. int nCopy;
  9513. rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
  9514. assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
  9515. if( rc!=SQLITE_OK ) return rc;
  9516. if( aOvfl==0 ) break;
  9517. nCopy = U-4;
  9518. if( nCopy>nRem ) nCopy = nRem;
  9519. memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
  9520. nRem -= nCopy;
  9521. pgnoOvfl = get_uint32(aOvfl);
  9522. sqlite3_free(aOvfl);
  9523. }
  9524. }
  9525. iHdr = dbdataGetVarint(pCsr->pRec, &nHdr);
  9526. pCsr->nHdr = nHdr;
  9527. pCsr->pHdrPtr = &pCsr->pRec[iHdr];
  9528. pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
  9529. pCsr->iField = (bHasRowid ? -1 : 0);
  9530. }
  9531. }
  9532. }else{
  9533. pCsr->iField++;
  9534. if( pCsr->iField>0 ){
  9535. sqlite3_int64 iType;
  9536. if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
  9537. bNextPage = 1;
  9538. }else{
  9539. pCsr->pHdrPtr += dbdataGetVarint(pCsr->pHdrPtr, &iType);
  9540. pCsr->pPtr += dbdataValueBytes(iType);
  9541. }
  9542. }
  9543. }
  9544. if( bNextPage ){
  9545. sqlite3_free(pCsr->aPage);
  9546. sqlite3_free(pCsr->pRec);
  9547. pCsr->aPage = 0;
  9548. pCsr->pRec = 0;
  9549. if( pCsr->bOnePage ) return SQLITE_OK;
  9550. pCsr->iPgno++;
  9551. }else{
  9552. if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
  9553. return SQLITE_OK;
  9554. }
  9555. /* Advance to the next cell. The next iteration of the loop will load
  9556. ** the record and so on. */
  9557. sqlite3_free(pCsr->pRec);
  9558. pCsr->pRec = 0;
  9559. pCsr->iCell++;
  9560. }
  9561. }
  9562. }
  9563. assert( !"can't get here" );
  9564. return SQLITE_OK;
  9565. }
  9566. /*
  9567. ** Return true if the cursor is at EOF.
  9568. */
  9569. static int dbdataEof(sqlite3_vtab_cursor *pCursor){
  9570. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  9571. return pCsr->aPage==0;
  9572. }
  9573. /*
  9574. ** Determine the size in pages of database zSchema (where zSchema is
  9575. ** "main", "temp" or the name of an attached database) and set
  9576. ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
  9577. ** an SQLite error code.
  9578. */
  9579. static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
  9580. DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
  9581. char *zSql = 0;
  9582. int rc, rc2;
  9583. sqlite3_stmt *pStmt = 0;
  9584. zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
  9585. if( zSql==0 ) return SQLITE_NOMEM;
  9586. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  9587. sqlite3_free(zSql);
  9588. if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
  9589. pCsr->szDb = sqlite3_column_int(pStmt, 0);
  9590. }
  9591. rc2 = sqlite3_finalize(pStmt);
  9592. if( rc==SQLITE_OK ) rc = rc2;
  9593. return rc;
  9594. }
  9595. /*
  9596. ** xFilter method for sqlite_dbdata and sqlite_dbptr.
  9597. */
  9598. static int dbdataFilter(
  9599. sqlite3_vtab_cursor *pCursor,
  9600. int idxNum, const char *idxStr,
  9601. int argc, sqlite3_value **argv
  9602. ){
  9603. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  9604. DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
  9605. int rc = SQLITE_OK;
  9606. const char *zSchema = "main";
  9607. dbdataResetCursor(pCsr);
  9608. assert( pCsr->iPgno==1 );
  9609. if( idxNum & 0x01 ){
  9610. zSchema = (const char*)sqlite3_value_text(argv[0]);
  9611. }
  9612. if( idxNum & 0x02 ){
  9613. pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
  9614. pCsr->bOnePage = 1;
  9615. }else{
  9616. pCsr->nPage = dbdataDbsize(pCsr, zSchema);
  9617. rc = dbdataDbsize(pCsr, zSchema);
  9618. }
  9619. if( rc==SQLITE_OK ){
  9620. if( pTab->pStmt ){
  9621. pCsr->pStmt = pTab->pStmt;
  9622. pTab->pStmt = 0;
  9623. }else{
  9624. rc = sqlite3_prepare_v2(pTab->db,
  9625. "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
  9626. &pCsr->pStmt, 0
  9627. );
  9628. }
  9629. }
  9630. if( rc==SQLITE_OK ){
  9631. rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
  9632. }else{
  9633. pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
  9634. }
  9635. if( rc==SQLITE_OK ){
  9636. rc = dbdataNext(pCursor);
  9637. }
  9638. return rc;
  9639. }
  9640. /*
  9641. ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
  9642. */
  9643. static int dbdataColumn(
  9644. sqlite3_vtab_cursor *pCursor,
  9645. sqlite3_context *ctx,
  9646. int i
  9647. ){
  9648. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  9649. DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
  9650. if( pTab->bPtr ){
  9651. switch( i ){
  9652. case DBPTR_COLUMN_PGNO:
  9653. sqlite3_result_int64(ctx, pCsr->iPgno);
  9654. break;
  9655. case DBPTR_COLUMN_CHILD: {
  9656. int iOff = pCsr->iPgno==1 ? 100 : 0;
  9657. if( pCsr->iCell<0 ){
  9658. iOff += 8;
  9659. }else{
  9660. iOff += 12 + pCsr->iCell*2;
  9661. if( iOff>pCsr->nPage ) return SQLITE_OK;
  9662. iOff = get_uint16(&pCsr->aPage[iOff]);
  9663. }
  9664. if( iOff<=pCsr->nPage ){
  9665. sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
  9666. }
  9667. break;
  9668. }
  9669. }
  9670. }else{
  9671. switch( i ){
  9672. case DBDATA_COLUMN_PGNO:
  9673. sqlite3_result_int64(ctx, pCsr->iPgno);
  9674. break;
  9675. case DBDATA_COLUMN_CELL:
  9676. sqlite3_result_int(ctx, pCsr->iCell);
  9677. break;
  9678. case DBDATA_COLUMN_FIELD:
  9679. sqlite3_result_int(ctx, pCsr->iField);
  9680. break;
  9681. case DBDATA_COLUMN_VALUE: {
  9682. if( pCsr->iField<0 ){
  9683. sqlite3_result_int64(ctx, pCsr->iIntkey);
  9684. }else{
  9685. sqlite3_int64 iType;
  9686. dbdataGetVarint(pCsr->pHdrPtr, &iType);
  9687. dbdataValue(
  9688. ctx, iType, pCsr->pPtr, &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
  9689. );
  9690. }
  9691. break;
  9692. }
  9693. }
  9694. }
  9695. return SQLITE_OK;
  9696. }
  9697. /*
  9698. ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
  9699. */
  9700. static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  9701. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  9702. *pRowid = pCsr->iRowid;
  9703. return SQLITE_OK;
  9704. }
  9705. /*
  9706. ** Invoke this routine to register the "sqlite_dbdata" virtual table module
  9707. */
  9708. static int sqlite3DbdataRegister(sqlite3 *db){
  9709. static sqlite3_module dbdata_module = {
  9710. 0, /* iVersion */
  9711. 0, /* xCreate */
  9712. dbdataConnect, /* xConnect */
  9713. dbdataBestIndex, /* xBestIndex */
  9714. dbdataDisconnect, /* xDisconnect */
  9715. 0, /* xDestroy */
  9716. dbdataOpen, /* xOpen - open a cursor */
  9717. dbdataClose, /* xClose - close a cursor */
  9718. dbdataFilter, /* xFilter - configure scan constraints */
  9719. dbdataNext, /* xNext - advance a cursor */
  9720. dbdataEof, /* xEof - check for end of scan */
  9721. dbdataColumn, /* xColumn - read data */
  9722. dbdataRowid, /* xRowid - read data */
  9723. 0, /* xUpdate */
  9724. 0, /* xBegin */
  9725. 0, /* xSync */
  9726. 0, /* xCommit */
  9727. 0, /* xRollback */
  9728. 0, /* xFindMethod */
  9729. 0, /* xRename */
  9730. 0, /* xSavepoint */
  9731. 0, /* xRelease */
  9732. 0, /* xRollbackTo */
  9733. 0 /* xShadowName */
  9734. };
  9735. int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
  9736. if( rc==SQLITE_OK ){
  9737. rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
  9738. }
  9739. return rc;
  9740. }
  9741. #ifdef _WIN32
  9742. #endif
  9743. int sqlite3_dbdata_init(
  9744. sqlite3 *db,
  9745. char **pzErrMsg,
  9746. const sqlite3_api_routines *pApi
  9747. ){
  9748. SQLITE_EXTENSION_INIT2(pApi);
  9749. return sqlite3DbdataRegister(db);
  9750. }
  9751. /************************* End ../ext/misc/dbdata.c ********************/
  9752. #endif
  9753. #if defined(SQLITE_ENABLE_SESSION)
  9754. /*
  9755. ** State information for a single open session
  9756. */
  9757. typedef struct OpenSession OpenSession;
  9758. struct OpenSession {
  9759. char *zName; /* Symbolic name for this session */
  9760. int nFilter; /* Number of xFilter rejection GLOB patterns */
  9761. char **azFilter; /* Array of xFilter rejection GLOB patterns */
  9762. sqlite3_session *p; /* The open session */
  9763. };
  9764. #endif
  9765. typedef struct ExpertInfo ExpertInfo;
  9766. struct ExpertInfo {
  9767. sqlite3expert *pExpert;
  9768. int bVerbose;
  9769. };
  9770. /* A single line in the EQP output */
  9771. typedef struct EQPGraphRow EQPGraphRow;
  9772. struct EQPGraphRow {
  9773. int iEqpId; /* ID for this row */
  9774. int iParentId; /* ID of the parent row */
  9775. EQPGraphRow *pNext; /* Next row in sequence */
  9776. char zText[1]; /* Text to display for this row */
  9777. };
  9778. /* All EQP output is collected into an instance of the following */
  9779. typedef struct EQPGraph EQPGraph;
  9780. struct EQPGraph {
  9781. EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
  9782. EQPGraphRow *pLast; /* Last element of the pRow list */
  9783. char zPrefix[100]; /* Graph prefix */
  9784. };
  9785. /*
  9786. ** State information about the database connection is contained in an
  9787. ** instance of the following structure.
  9788. */
  9789. typedef struct ShellState ShellState;
  9790. struct ShellState {
  9791. sqlite3 *db; /* The database */
  9792. u8 autoExplain; /* Automatically turn on .explain mode */
  9793. u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
  9794. u8 autoEQPtest; /* autoEQP is in test mode */
  9795. u8 autoEQPtrace; /* autoEQP is in trace mode */
  9796. u8 statsOn; /* True to display memory stats before each finalize */
  9797. u8 scanstatsOn; /* True to display scan stats before each finalize */
  9798. u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
  9799. u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
  9800. u8 nEqpLevel; /* Depth of the EQP output graph */
  9801. u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
  9802. unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
  9803. int outCount; /* Revert to stdout when reaching zero */
  9804. int cnt; /* Number of records displayed so far */
  9805. int lineno; /* Line number of last line read from in */
  9806. int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
  9807. FILE *in; /* Read commands from this stream */
  9808. FILE *out; /* Write results here */
  9809. FILE *traceOut; /* Output for sqlite3_trace() */
  9810. int nErr; /* Number of errors seen */
  9811. int mode; /* An output mode setting */
  9812. int modePrior; /* Saved mode */
  9813. int cMode; /* temporary output mode for the current query */
  9814. int normalMode; /* Output mode before ".explain on" */
  9815. int writableSchema; /* True if PRAGMA writable_schema=ON */
  9816. int showHeader; /* True to show column names in List or Column mode */
  9817. int nCheck; /* Number of ".check" commands run */
  9818. unsigned nProgress; /* Number of progress callbacks encountered */
  9819. unsigned mxProgress; /* Maximum progress callbacks before failing */
  9820. unsigned flgProgress; /* Flags for the progress callback */
  9821. unsigned shellFlgs; /* Various flags */
  9822. unsigned priorShFlgs; /* Saved copy of flags */
  9823. sqlite3_int64 szMax; /* --maxsize argument to .open */
  9824. char *zDestTable; /* Name of destination table when MODE_Insert */
  9825. char *zTempFile; /* Temporary file that might need deleting */
  9826. char zTestcase[30]; /* Name of current test case */
  9827. char colSeparator[20]; /* Column separator character for several modes */
  9828. char rowSeparator[20]; /* Row separator character for MODE_Ascii */
  9829. char colSepPrior[20]; /* Saved column separator */
  9830. char rowSepPrior[20]; /* Saved row separator */
  9831. int *colWidth; /* Requested width of each column in columnar modes */
  9832. int *actualWidth; /* Actual width of each column */
  9833. int nWidth; /* Number of slots in colWidth[] and actualWidth[] */
  9834. char nullValue[20]; /* The text to print when a NULL comes back from
  9835. ** the database */
  9836. char outfile[FILENAME_MAX]; /* Filename for *out */
  9837. const char *zDbFilename; /* name of the database file */
  9838. char *zFreeOnClose; /* Filename to free when closing */
  9839. const char *zVfs; /* Name of VFS to use */
  9840. sqlite3_stmt *pStmt; /* Current statement if any. */
  9841. FILE *pLog; /* Write log output here */
  9842. int *aiIndent; /* Array of indents used in MODE_Explain */
  9843. int nIndent; /* Size of array aiIndent[] */
  9844. int iIndent; /* Index of current op in aiIndent[] */
  9845. EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
  9846. #if defined(SQLITE_ENABLE_SESSION)
  9847. int nSession; /* Number of active sessions */
  9848. OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
  9849. #endif
  9850. ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
  9851. };
  9852. /* Allowed values for ShellState.autoEQP
  9853. */
  9854. #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
  9855. #define AUTOEQP_on 1 /* Automatic EQP is on */
  9856. #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
  9857. #define AUTOEQP_full 3 /* Show full EXPLAIN */
  9858. /* Allowed values for ShellState.openMode
  9859. */
  9860. #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
  9861. #define SHELL_OPEN_NORMAL 1 /* Normal database file */
  9862. #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
  9863. #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
  9864. #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
  9865. #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
  9866. #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
  9867. /* Allowed values for ShellState.eTraceType
  9868. */
  9869. #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
  9870. #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
  9871. #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
  9872. /* Bits in the ShellState.flgProgress variable */
  9873. #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
  9874. #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
  9875. ** callback limit is reached, and for each
  9876. ** top-level SQL statement */
  9877. #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
  9878. /*
  9879. ** These are the allowed shellFlgs values
  9880. */
  9881. #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
  9882. #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
  9883. #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
  9884. #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
  9885. #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
  9886. #define SHFLG_CountChanges 0x00000020 /* .changes setting */
  9887. #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
  9888. #define SHFLG_HeaderSet 0x00000080 /* .header has been used */
  9889. /*
  9890. ** Macros for testing and setting shellFlgs
  9891. */
  9892. #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
  9893. #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
  9894. #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
  9895. /*
  9896. ** These are the allowed modes.
  9897. */
  9898. #define MODE_Line 0 /* One column per line. Blank line between records */
  9899. #define MODE_Column 1 /* One record per line in neat columns */
  9900. #define MODE_List 2 /* One record per line with a separator */
  9901. #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
  9902. #define MODE_Html 4 /* Generate an XHTML table */
  9903. #define MODE_Insert 5 /* Generate SQL "insert" statements */
  9904. #define MODE_Quote 6 /* Quote values as for SQL */
  9905. #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
  9906. #define MODE_Csv 8 /* Quote strings, numbers are plain */
  9907. #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
  9908. #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
  9909. #define MODE_Pretty 11 /* Pretty-print schemas */
  9910. #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
  9911. #define MODE_Json 13 /* Output JSON */
  9912. #define MODE_Markdown 14 /* Markdown formatting */
  9913. #define MODE_Table 15 /* MySQL-style table formatting */
  9914. #define MODE_Box 16 /* Unicode box-drawing characters */
  9915. static const char *modeDescr[] = {
  9916. "line",
  9917. "column",
  9918. "list",
  9919. "semi",
  9920. "html",
  9921. "insert",
  9922. "quote",
  9923. "tcl",
  9924. "csv",
  9925. "explain",
  9926. "ascii",
  9927. "prettyprint",
  9928. "eqp",
  9929. "json",
  9930. "markdown",
  9931. "table",
  9932. "box"
  9933. };
  9934. /*
  9935. ** These are the column/row/line separators used by the various
  9936. ** import/export modes.
  9937. */
  9938. #define SEP_Column "|"
  9939. #define SEP_Row "\n"
  9940. #define SEP_Tab "\t"
  9941. #define SEP_Space " "
  9942. #define SEP_Comma ","
  9943. #define SEP_CrLf "\r\n"
  9944. #define SEP_Unit "\x1F"
  9945. #define SEP_Record "\x1E"
  9946. /*
  9947. ** A callback for the sqlite3_log() interface.
  9948. */
  9949. static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  9950. ShellState *p = (ShellState*)pArg;
  9951. if( p->pLog==0 ) return;
  9952. utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  9953. fflush(p->pLog);
  9954. }
  9955. /*
  9956. ** SQL function: shell_putsnl(X)
  9957. **
  9958. ** Write the text X to the screen (or whatever output is being directed)
  9959. ** adding a newline at the end, and then return X.
  9960. */
  9961. static void shellPutsFunc(
  9962. sqlite3_context *pCtx,
  9963. int nVal,
  9964. sqlite3_value **apVal
  9965. ){
  9966. ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
  9967. (void)nVal;
  9968. utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
  9969. sqlite3_result_value(pCtx, apVal[0]);
  9970. }
  9971. /*
  9972. ** SQL function: edit(VALUE)
  9973. ** edit(VALUE,EDITOR)
  9974. **
  9975. ** These steps:
  9976. **
  9977. ** (1) Write VALUE into a temporary file.
  9978. ** (2) Run program EDITOR on that temporary file.
  9979. ** (3) Read the temporary file back and return its content as the result.
  9980. ** (4) Delete the temporary file
  9981. **
  9982. ** If the EDITOR argument is omitted, use the value in the VISUAL
  9983. ** environment variable. If still there is no EDITOR, through an error.
  9984. **
  9985. ** Also throw an error if the EDITOR program returns a non-zero exit code.
  9986. */
  9987. #ifndef SQLITE_NOHAVE_SYSTEM
  9988. static void editFunc(
  9989. sqlite3_context *context,
  9990. int argc,
  9991. sqlite3_value **argv
  9992. ){
  9993. const char *zEditor;
  9994. char *zTempFile = 0;
  9995. sqlite3 *db;
  9996. char *zCmd = 0;
  9997. int bBin;
  9998. int rc;
  9999. int hasCRNL = 0;
  10000. FILE *f = 0;
  10001. sqlite3_int64 sz;
  10002. sqlite3_int64 x;
  10003. unsigned char *p = 0;
  10004. if( argc==2 ){
  10005. zEditor = (const char*)sqlite3_value_text(argv[1]);
  10006. }else{
  10007. zEditor = getenv("VISUAL");
  10008. }
  10009. if( zEditor==0 ){
  10010. sqlite3_result_error(context, "no editor for edit()", -1);
  10011. return;
  10012. }
  10013. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  10014. sqlite3_result_error(context, "NULL input to edit()", -1);
  10015. return;
  10016. }
  10017. db = sqlite3_context_db_handle(context);
  10018. zTempFile = 0;
  10019. sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
  10020. if( zTempFile==0 ){
  10021. sqlite3_uint64 r = 0;
  10022. sqlite3_randomness(sizeof(r), &r);
  10023. zTempFile = sqlite3_mprintf("temp%llx", r);
  10024. if( zTempFile==0 ){
  10025. sqlite3_result_error_nomem(context);
  10026. return;
  10027. }
  10028. }
  10029. bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
  10030. /* When writing the file to be edited, do \n to \r\n conversions on systems
  10031. ** that want \r\n line endings */
  10032. f = fopen(zTempFile, bBin ? "wb" : "w");
  10033. if( f==0 ){
  10034. sqlite3_result_error(context, "edit() cannot open temp file", -1);
  10035. goto edit_func_end;
  10036. }
  10037. sz = sqlite3_value_bytes(argv[0]);
  10038. if( bBin ){
  10039. x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
  10040. }else{
  10041. const char *z = (const char*)sqlite3_value_text(argv[0]);
  10042. /* Remember whether or not the value originally contained \r\n */
  10043. if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
  10044. x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
  10045. }
  10046. fclose(f);
  10047. f = 0;
  10048. if( x!=sz ){
  10049. sqlite3_result_error(context, "edit() could not write the whole file", -1);
  10050. goto edit_func_end;
  10051. }
  10052. zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
  10053. if( zCmd==0 ){
  10054. sqlite3_result_error_nomem(context);
  10055. goto edit_func_end;
  10056. }
  10057. rc = system(zCmd);
  10058. sqlite3_free(zCmd);
  10059. if( rc ){
  10060. sqlite3_result_error(context, "EDITOR returned non-zero", -1);
  10061. goto edit_func_end;
  10062. }
  10063. f = fopen(zTempFile, "rb");
  10064. if( f==0 ){
  10065. sqlite3_result_error(context,
  10066. "edit() cannot reopen temp file after edit", -1);
  10067. goto edit_func_end;
  10068. }
  10069. fseek(f, 0, SEEK_END);
  10070. sz = ftell(f);
  10071. rewind(f);
  10072. p = sqlite3_malloc64( sz+1 );
  10073. if( p==0 ){
  10074. sqlite3_result_error_nomem(context);
  10075. goto edit_func_end;
  10076. }
  10077. x = fread(p, 1, (size_t)sz, f);
  10078. fclose(f);
  10079. f = 0;
  10080. if( x!=sz ){
  10081. sqlite3_result_error(context, "could not read back the whole file", -1);
  10082. goto edit_func_end;
  10083. }
  10084. if( bBin ){
  10085. sqlite3_result_blob64(context, p, sz, sqlite3_free);
  10086. }else{
  10087. sqlite3_int64 i, j;
  10088. if( hasCRNL ){
  10089. /* If the original contains \r\n then do no conversions back to \n */
  10090. j = sz;
  10091. }else{
  10092. /* If the file did not originally contain \r\n then convert any new
  10093. ** \r\n back into \n */
  10094. for(i=j=0; i<sz; i++){
  10095. if( p[i]=='\r' && p[i+1]=='\n' ) i++;
  10096. p[j++] = p[i];
  10097. }
  10098. sz = j;
  10099. p[sz] = 0;
  10100. }
  10101. sqlite3_result_text64(context, (const char*)p, sz,
  10102. sqlite3_free, SQLITE_UTF8);
  10103. }
  10104. p = 0;
  10105. edit_func_end:
  10106. if( f ) fclose(f);
  10107. unlink(zTempFile);
  10108. sqlite3_free(zTempFile);
  10109. sqlite3_free(p);
  10110. }
  10111. #endif /* SQLITE_NOHAVE_SYSTEM */
  10112. /*
  10113. ** Save or restore the current output mode
  10114. */
  10115. static void outputModePush(ShellState *p){
  10116. p->modePrior = p->mode;
  10117. p->priorShFlgs = p->shellFlgs;
  10118. memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
  10119. memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
  10120. }
  10121. static void outputModePop(ShellState *p){
  10122. p->mode = p->modePrior;
  10123. p->shellFlgs = p->priorShFlgs;
  10124. memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
  10125. memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
  10126. }
  10127. /*
  10128. ** Output the given string as a hex-encoded blob (eg. X'1234' )
  10129. */
  10130. static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  10131. int i;
  10132. char *zBlob = (char *)pBlob;
  10133. raw_printf(out,"X'");
  10134. for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
  10135. raw_printf(out,"'");
  10136. }
  10137. /*
  10138. ** Find a string that is not found anywhere in z[]. Return a pointer
  10139. ** to that string.
  10140. **
  10141. ** Try to use zA and zB first. If both of those are already found in z[]
  10142. ** then make up some string and store it in the buffer zBuf.
  10143. */
  10144. static const char *unused_string(
  10145. const char *z, /* Result must not appear anywhere in z */
  10146. const char *zA, const char *zB, /* Try these first */
  10147. char *zBuf /* Space to store a generated string */
  10148. ){
  10149. unsigned i = 0;
  10150. if( strstr(z, zA)==0 ) return zA;
  10151. if( strstr(z, zB)==0 ) return zB;
  10152. do{
  10153. sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
  10154. }while( strstr(z,zBuf)!=0 );
  10155. return zBuf;
  10156. }
  10157. /*
  10158. ** Output the given string as a quoted string using SQL quoting conventions.
  10159. **
  10160. ** See also: output_quoted_escaped_string()
  10161. */
  10162. static void output_quoted_string(FILE *out, const char *z){
  10163. int i;
  10164. char c;
  10165. setBinaryMode(out, 1);
  10166. for(i=0; (c = z[i])!=0 && c!='\''; i++){}
  10167. if( c==0 ){
  10168. utf8_printf(out,"'%s'",z);
  10169. }else{
  10170. raw_printf(out, "'");
  10171. while( *z ){
  10172. for(i=0; (c = z[i])!=0 && c!='\''; i++){}
  10173. if( c=='\'' ) i++;
  10174. if( i ){
  10175. utf8_printf(out, "%.*s", i, z);
  10176. z += i;
  10177. }
  10178. if( c=='\'' ){
  10179. raw_printf(out, "'");
  10180. continue;
  10181. }
  10182. if( c==0 ){
  10183. break;
  10184. }
  10185. z++;
  10186. }
  10187. raw_printf(out, "'");
  10188. }
  10189. setTextMode(out, 1);
  10190. }
  10191. /*
  10192. ** Output the given string as a quoted string using SQL quoting conventions.
  10193. ** Additionallly , escape the "\n" and "\r" characters so that they do not
  10194. ** get corrupted by end-of-line translation facilities in some operating
  10195. ** systems.
  10196. **
  10197. ** This is like output_quoted_string() but with the addition of the \r\n
  10198. ** escape mechanism.
  10199. */
  10200. static void output_quoted_escaped_string(FILE *out, const char *z){
  10201. int i;
  10202. char c;
  10203. setBinaryMode(out, 1);
  10204. for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
  10205. if( c==0 ){
  10206. utf8_printf(out,"'%s'",z);
  10207. }else{
  10208. const char *zNL = 0;
  10209. const char *zCR = 0;
  10210. int nNL = 0;
  10211. int nCR = 0;
  10212. char zBuf1[20], zBuf2[20];
  10213. for(i=0; z[i]; i++){
  10214. if( z[i]=='\n' ) nNL++;
  10215. if( z[i]=='\r' ) nCR++;
  10216. }
  10217. if( nNL ){
  10218. raw_printf(out, "replace(");
  10219. zNL = unused_string(z, "\\n", "\\012", zBuf1);
  10220. }
  10221. if( nCR ){
  10222. raw_printf(out, "replace(");
  10223. zCR = unused_string(z, "\\r", "\\015", zBuf2);
  10224. }
  10225. raw_printf(out, "'");
  10226. while( *z ){
  10227. for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
  10228. if( c=='\'' ) i++;
  10229. if( i ){
  10230. utf8_printf(out, "%.*s", i, z);
  10231. z += i;
  10232. }
  10233. if( c=='\'' ){
  10234. raw_printf(out, "'");
  10235. continue;
  10236. }
  10237. if( c==0 ){
  10238. break;
  10239. }
  10240. z++;
  10241. if( c=='\n' ){
  10242. raw_printf(out, "%s", zNL);
  10243. continue;
  10244. }
  10245. raw_printf(out, "%s", zCR);
  10246. }
  10247. raw_printf(out, "'");
  10248. if( nCR ){
  10249. raw_printf(out, ",'%s',char(13))", zCR);
  10250. }
  10251. if( nNL ){
  10252. raw_printf(out, ",'%s',char(10))", zNL);
  10253. }
  10254. }
  10255. setTextMode(out, 1);
  10256. }
  10257. /*
  10258. ** Output the given string as a quoted according to C or TCL quoting rules.
  10259. */
  10260. static void output_c_string(FILE *out, const char *z){
  10261. unsigned int c;
  10262. fputc('"', out);
  10263. while( (c = *(z++))!=0 ){
  10264. if( c=='\\' ){
  10265. fputc(c, out);
  10266. fputc(c, out);
  10267. }else if( c=='"' ){
  10268. fputc('\\', out);
  10269. fputc('"', out);
  10270. }else if( c=='\t' ){
  10271. fputc('\\', out);
  10272. fputc('t', out);
  10273. }else if( c=='\n' ){
  10274. fputc('\\', out);
  10275. fputc('n', out);
  10276. }else if( c=='\r' ){
  10277. fputc('\\', out);
  10278. fputc('r', out);
  10279. }else if( !isprint(c&0xff) ){
  10280. raw_printf(out, "\\%03o", c&0xff);
  10281. }else{
  10282. fputc(c, out);
  10283. }
  10284. }
  10285. fputc('"', out);
  10286. }
  10287. /*
  10288. ** Output the given string as a quoted according to JSON quoting rules.
  10289. */
  10290. static void output_json_string(FILE *out, const char *z, int n){
  10291. unsigned int c;
  10292. if( n<0 ) n = (int)strlen(z);
  10293. fputc('"', out);
  10294. while( n-- ){
  10295. c = *(z++);
  10296. if( c=='\\' || c=='"' ){
  10297. fputc('\\', out);
  10298. fputc(c, out);
  10299. }else if( c<=0x1f ){
  10300. fputc('\\', out);
  10301. if( c=='\b' ){
  10302. fputc('b', out);
  10303. }else if( c=='\f' ){
  10304. fputc('f', out);
  10305. }else if( c=='\n' ){
  10306. fputc('n', out);
  10307. }else if( c=='\r' ){
  10308. fputc('r', out);
  10309. }else if( c=='\t' ){
  10310. fputc('t', out);
  10311. }else{
  10312. raw_printf(out, "u%04x",c);
  10313. }
  10314. }else{
  10315. fputc(c, out);
  10316. }
  10317. }
  10318. fputc('"', out);
  10319. }
  10320. /*
  10321. ** Output the given string with characters that are special to
  10322. ** HTML escaped.
  10323. */
  10324. static void output_html_string(FILE *out, const char *z){
  10325. int i;
  10326. if( z==0 ) z = "";
  10327. while( *z ){
  10328. for(i=0; z[i]
  10329. && z[i]!='<'
  10330. && z[i]!='&'
  10331. && z[i]!='>'
  10332. && z[i]!='\"'
  10333. && z[i]!='\'';
  10334. i++){}
  10335. if( i>0 ){
  10336. utf8_printf(out,"%.*s",i,z);
  10337. }
  10338. if( z[i]=='<' ){
  10339. raw_printf(out,"&lt;");
  10340. }else if( z[i]=='&' ){
  10341. raw_printf(out,"&amp;");
  10342. }else if( z[i]=='>' ){
  10343. raw_printf(out,"&gt;");
  10344. }else if( z[i]=='\"' ){
  10345. raw_printf(out,"&quot;");
  10346. }else if( z[i]=='\'' ){
  10347. raw_printf(out,"&#39;");
  10348. }else{
  10349. break;
  10350. }
  10351. z += i + 1;
  10352. }
  10353. }
  10354. /*
  10355. ** If a field contains any character identified by a 1 in the following
  10356. ** array, then the string must be quoted for CSV.
  10357. */
  10358. static const char needCsvQuote[] = {
  10359. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  10360. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  10361. 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  10362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  10363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  10364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  10365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  10366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  10367. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  10368. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  10369. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  10370. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  10371. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  10372. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  10373. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  10374. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  10375. };
  10376. /*
  10377. ** Output a single term of CSV. Actually, p->colSeparator is used for
  10378. ** the separator, which may or may not be a comma. p->nullValue is
  10379. ** the null value. Strings are quoted if necessary. The separator
  10380. ** is only issued if bSep is true.
  10381. */
  10382. static void output_csv(ShellState *p, const char *z, int bSep){
  10383. FILE *out = p->out;
  10384. if( z==0 ){
  10385. utf8_printf(out,"%s",p->nullValue);
  10386. }else{
  10387. int i;
  10388. int nSep = strlen30(p->colSeparator);
  10389. for(i=0; z[i]; i++){
  10390. if( needCsvQuote[((unsigned char*)z)[i]]
  10391. || (z[i]==p->colSeparator[0] &&
  10392. (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
  10393. i = 0;
  10394. break;
  10395. }
  10396. }
  10397. if( i==0 ){
  10398. char *zQuoted = sqlite3_mprintf("\"%w\"", z);
  10399. utf8_printf(out, "%s", zQuoted);
  10400. sqlite3_free(zQuoted);
  10401. }else{
  10402. utf8_printf(out, "%s", z);
  10403. }
  10404. }
  10405. if( bSep ){
  10406. utf8_printf(p->out, "%s", p->colSeparator);
  10407. }
  10408. }
  10409. /*
  10410. ** This routine runs when the user presses Ctrl-C
  10411. */
  10412. static void interrupt_handler(int NotUsed){
  10413. UNUSED_PARAMETER(NotUsed);
  10414. seenInterrupt++;
  10415. if( seenInterrupt>2 ) exit(1);
  10416. if( globalDb ) sqlite3_interrupt(globalDb);
  10417. }
  10418. #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
  10419. /*
  10420. ** This routine runs for console events (e.g. Ctrl-C) on Win32
  10421. */
  10422. static BOOL WINAPI ConsoleCtrlHandler(
  10423. DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
  10424. ){
  10425. if( dwCtrlType==CTRL_C_EVENT ){
  10426. interrupt_handler(0);
  10427. return TRUE;
  10428. }
  10429. return FALSE;
  10430. }
  10431. #endif
  10432. #ifndef SQLITE_OMIT_AUTHORIZATION
  10433. /*
  10434. ** When the ".auth ON" is set, the following authorizer callback is
  10435. ** invoked. It always returns SQLITE_OK.
  10436. */
  10437. static int shellAuth(
  10438. void *pClientData,
  10439. int op,
  10440. const char *zA1,
  10441. const char *zA2,
  10442. const char *zA3,
  10443. const char *zA4
  10444. ){
  10445. ShellState *p = (ShellState*)pClientData;
  10446. static const char *azAction[] = { 0,
  10447. "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
  10448. "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
  10449. "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
  10450. "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
  10451. "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
  10452. "DROP_TRIGGER", "DROP_VIEW", "INSERT",
  10453. "PRAGMA", "READ", "SELECT",
  10454. "TRANSACTION", "UPDATE", "ATTACH",
  10455. "DETACH", "ALTER_TABLE", "REINDEX",
  10456. "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
  10457. "FUNCTION", "SAVEPOINT", "RECURSIVE"
  10458. };
  10459. int i;
  10460. const char *az[4];
  10461. az[0] = zA1;
  10462. az[1] = zA2;
  10463. az[2] = zA3;
  10464. az[3] = zA4;
  10465. utf8_printf(p->out, "authorizer: %s", azAction[op]);
  10466. for(i=0; i<4; i++){
  10467. raw_printf(p->out, " ");
  10468. if( az[i] ){
  10469. output_c_string(p->out, az[i]);
  10470. }else{
  10471. raw_printf(p->out, "NULL");
  10472. }
  10473. }
  10474. raw_printf(p->out, "\n");
  10475. return SQLITE_OK;
  10476. }
  10477. #endif
  10478. /*
  10479. ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
  10480. **
  10481. ** This routine converts some CREATE TABLE statements for shadow tables
  10482. ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
  10483. */
  10484. static void printSchemaLine(FILE *out, const char *z, const char *zTail){
  10485. if( z==0 ) return;
  10486. if( zTail==0 ) return;
  10487. if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
  10488. utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
  10489. }else{
  10490. utf8_printf(out, "%s%s", z, zTail);
  10491. }
  10492. }
  10493. static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
  10494. char c = z[n];
  10495. z[n] = 0;
  10496. printSchemaLine(out, z, zTail);
  10497. z[n] = c;
  10498. }
  10499. /*
  10500. ** Return true if string z[] has nothing but whitespace and comments to the
  10501. ** end of the first line.
  10502. */
  10503. static int wsToEol(const char *z){
  10504. int i;
  10505. for(i=0; z[i]; i++){
  10506. if( z[i]=='\n' ) return 1;
  10507. if( IsSpace(z[i]) ) continue;
  10508. if( z[i]=='-' && z[i+1]=='-' ) return 1;
  10509. return 0;
  10510. }
  10511. return 1;
  10512. }
  10513. /*
  10514. ** Add a new entry to the EXPLAIN QUERY PLAN data
  10515. */
  10516. static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
  10517. EQPGraphRow *pNew;
  10518. int nText = strlen30(zText);
  10519. if( p->autoEQPtest ){
  10520. utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
  10521. }
  10522. pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
  10523. if( pNew==0 ) shell_out_of_memory();
  10524. pNew->iEqpId = iEqpId;
  10525. pNew->iParentId = p2;
  10526. memcpy(pNew->zText, zText, nText+1);
  10527. pNew->pNext = 0;
  10528. if( p->sGraph.pLast ){
  10529. p->sGraph.pLast->pNext = pNew;
  10530. }else{
  10531. p->sGraph.pRow = pNew;
  10532. }
  10533. p->sGraph.pLast = pNew;
  10534. }
  10535. /*
  10536. ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
  10537. ** in p->sGraph.
  10538. */
  10539. static void eqp_reset(ShellState *p){
  10540. EQPGraphRow *pRow, *pNext;
  10541. for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
  10542. pNext = pRow->pNext;
  10543. sqlite3_free(pRow);
  10544. }
  10545. memset(&p->sGraph, 0, sizeof(p->sGraph));
  10546. }
  10547. /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
  10548. ** pOld, or return the first such line if pOld is NULL
  10549. */
  10550. static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
  10551. EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
  10552. while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
  10553. return pRow;
  10554. }
  10555. /* Render a single level of the graph that has iEqpId as its parent. Called
  10556. ** recursively to render sublevels.
  10557. */
  10558. static void eqp_render_level(ShellState *p, int iEqpId){
  10559. EQPGraphRow *pRow, *pNext;
  10560. int n = strlen30(p->sGraph.zPrefix);
  10561. char *z;
  10562. for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
  10563. pNext = eqp_next_row(p, iEqpId, pRow);
  10564. z = pRow->zText;
  10565. utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
  10566. pNext ? "|--" : "`--", z);
  10567. if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
  10568. memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
  10569. eqp_render_level(p, pRow->iEqpId);
  10570. p->sGraph.zPrefix[n] = 0;
  10571. }
  10572. }
  10573. }
  10574. /*
  10575. ** Display and reset the EXPLAIN QUERY PLAN data
  10576. */
  10577. static void eqp_render(ShellState *p){
  10578. EQPGraphRow *pRow = p->sGraph.pRow;
  10579. if( pRow ){
  10580. if( pRow->zText[0]=='-' ){
  10581. if( pRow->pNext==0 ){
  10582. eqp_reset(p);
  10583. return;
  10584. }
  10585. utf8_printf(p->out, "%s\n", pRow->zText+3);
  10586. p->sGraph.pRow = pRow->pNext;
  10587. sqlite3_free(pRow);
  10588. }else{
  10589. utf8_printf(p->out, "QUERY PLAN\n");
  10590. }
  10591. p->sGraph.zPrefix[0] = 0;
  10592. eqp_render_level(p, 0);
  10593. eqp_reset(p);
  10594. }
  10595. }
  10596. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  10597. /*
  10598. ** Progress handler callback.
  10599. */
  10600. static int progress_handler(void *pClientData) {
  10601. ShellState *p = (ShellState*)pClientData;
  10602. p->nProgress++;
  10603. if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
  10604. raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
  10605. if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
  10606. if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
  10607. return 1;
  10608. }
  10609. if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
  10610. raw_printf(p->out, "Progress %u\n", p->nProgress);
  10611. }
  10612. return 0;
  10613. }
  10614. #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
  10615. /*
  10616. ** Print N dashes
  10617. */
  10618. static void print_dashes(FILE *out, int N){
  10619. const char zDash[] = "--------------------------------------------------";
  10620. const int nDash = sizeof(zDash) - 1;
  10621. while( N>nDash ){
  10622. fputs(zDash, out);
  10623. N -= nDash;
  10624. }
  10625. raw_printf(out, "%.*s", N, zDash);
  10626. }
  10627. /*
  10628. ** Print a markdown or table-style row separator using ascii-art
  10629. */
  10630. static void print_row_separator(
  10631. ShellState *p,
  10632. int nArg,
  10633. const char *zSep
  10634. ){
  10635. int i;
  10636. if( nArg>0 ){
  10637. fputs(zSep, p->out);
  10638. print_dashes(p->out, p->actualWidth[0]+2);
  10639. for(i=1; i<nArg; i++){
  10640. fputs(zSep, p->out);
  10641. print_dashes(p->out, p->actualWidth[i]+2);
  10642. }
  10643. fputs(zSep, p->out);
  10644. }
  10645. fputs("\n", p->out);
  10646. }
  10647. /*
  10648. ** This is the callback routine that the shell
  10649. ** invokes for each row of a query result.
  10650. */
  10651. static int shell_callback(
  10652. void *pArg,
  10653. int nArg, /* Number of result columns */
  10654. char **azArg, /* Text of each result column */
  10655. char **azCol, /* Column names */
  10656. int *aiType /* Column types. Might be NULL */
  10657. ){
  10658. int i;
  10659. ShellState *p = (ShellState*)pArg;
  10660. if( azArg==0 ) return 0;
  10661. switch( p->cMode ){
  10662. case MODE_Line: {
  10663. int w = 5;
  10664. if( azArg==0 ) break;
  10665. for(i=0; i<nArg; i++){
  10666. int len = strlen30(azCol[i] ? azCol[i] : "");
  10667. if( len>w ) w = len;
  10668. }
  10669. if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
  10670. for(i=0; i<nArg; i++){
  10671. utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
  10672. azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
  10673. }
  10674. break;
  10675. }
  10676. case MODE_Explain: {
  10677. static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
  10678. if( nArg>ArraySize(aExplainWidth) ){
  10679. nArg = ArraySize(aExplainWidth);
  10680. }
  10681. if( p->cnt++==0 ){
  10682. for(i=0; i<nArg; i++){
  10683. int w = aExplainWidth[i];
  10684. utf8_width_print(p->out, w, azCol[i]);
  10685. fputs(i==nArg-1 ? "\n" : " ", p->out);
  10686. }
  10687. for(i=0; i<nArg; i++){
  10688. int w = aExplainWidth[i];
  10689. print_dashes(p->out, w);
  10690. fputs(i==nArg-1 ? "\n" : " ", p->out);
  10691. }
  10692. }
  10693. if( azArg==0 ) break;
  10694. for(i=0; i<nArg; i++){
  10695. int w = aExplainWidth[i];
  10696. if( azArg[i] && strlenChar(azArg[i])>w ){
  10697. w = strlenChar(azArg[i]);
  10698. }
  10699. if( i==1 && p->aiIndent && p->pStmt ){
  10700. if( p->iIndent<p->nIndent ){
  10701. utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
  10702. }
  10703. p->iIndent++;
  10704. }
  10705. utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
  10706. fputs(i==nArg-1 ? "\n" : " ", p->out);
  10707. }
  10708. break;
  10709. }
  10710. case MODE_Semi: { /* .schema and .fullschema output */
  10711. printSchemaLine(p->out, azArg[0], ";\n");
  10712. break;
  10713. }
  10714. case MODE_Pretty: { /* .schema and .fullschema with --indent */
  10715. char *z;
  10716. int j;
  10717. int nParen = 0;
  10718. char cEnd = 0;
  10719. char c;
  10720. int nLine = 0;
  10721. assert( nArg==1 );
  10722. if( azArg[0]==0 ) break;
  10723. if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
  10724. || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
  10725. ){
  10726. utf8_printf(p->out, "%s;\n", azArg[0]);
  10727. break;
  10728. }
  10729. z = sqlite3_mprintf("%s", azArg[0]);
  10730. j = 0;
  10731. for(i=0; IsSpace(z[i]); i++){}
  10732. for(; (c = z[i])!=0; i++){
  10733. if( IsSpace(c) ){
  10734. if( z[j-1]=='\r' ) z[j-1] = '\n';
  10735. if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
  10736. }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
  10737. j--;
  10738. }
  10739. z[j++] = c;
  10740. }
  10741. while( j>0 && IsSpace(z[j-1]) ){ j--; }
  10742. z[j] = 0;
  10743. if( strlen30(z)>=79 ){
  10744. for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
  10745. if( c==cEnd ){
  10746. cEnd = 0;
  10747. }else if( c=='"' || c=='\'' || c=='`' ){
  10748. cEnd = c;
  10749. }else if( c=='[' ){
  10750. cEnd = ']';
  10751. }else if( c=='-' && z[i+1]=='-' ){
  10752. cEnd = '\n';
  10753. }else if( c=='(' ){
  10754. nParen++;
  10755. }else if( c==')' ){
  10756. nParen--;
  10757. if( nLine>0 && nParen==0 && j>0 ){
  10758. printSchemaLineN(p->out, z, j, "\n");
  10759. j = 0;
  10760. }
  10761. }
  10762. z[j++] = c;
  10763. if( nParen==1 && cEnd==0
  10764. && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
  10765. ){
  10766. if( c=='\n' ) j--;
  10767. printSchemaLineN(p->out, z, j, "\n ");
  10768. j = 0;
  10769. nLine++;
  10770. while( IsSpace(z[i+1]) ){ i++; }
  10771. }
  10772. }
  10773. z[j] = 0;
  10774. }
  10775. printSchemaLine(p->out, z, ";\n");
  10776. sqlite3_free(z);
  10777. break;
  10778. }
  10779. case MODE_List: {
  10780. if( p->cnt++==0 && p->showHeader ){
  10781. for(i=0; i<nArg; i++){
  10782. utf8_printf(p->out,"%s%s",azCol[i],
  10783. i==nArg-1 ? p->rowSeparator : p->colSeparator);
  10784. }
  10785. }
  10786. if( azArg==0 ) break;
  10787. for(i=0; i<nArg; i++){
  10788. char *z = azArg[i];
  10789. if( z==0 ) z = p->nullValue;
  10790. utf8_printf(p->out, "%s", z);
  10791. if( i<nArg-1 ){
  10792. utf8_printf(p->out, "%s", p->colSeparator);
  10793. }else{
  10794. utf8_printf(p->out, "%s", p->rowSeparator);
  10795. }
  10796. }
  10797. break;
  10798. }
  10799. case MODE_Html: {
  10800. if( p->cnt++==0 && p->showHeader ){
  10801. raw_printf(p->out,"<TR>");
  10802. for(i=0; i<nArg; i++){
  10803. raw_printf(p->out,"<TH>");
  10804. output_html_string(p->out, azCol[i]);
  10805. raw_printf(p->out,"</TH>\n");
  10806. }
  10807. raw_printf(p->out,"</TR>\n");
  10808. }
  10809. if( azArg==0 ) break;
  10810. raw_printf(p->out,"<TR>");
  10811. for(i=0; i<nArg; i++){
  10812. raw_printf(p->out,"<TD>");
  10813. output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  10814. raw_printf(p->out,"</TD>\n");
  10815. }
  10816. raw_printf(p->out,"</TR>\n");
  10817. break;
  10818. }
  10819. case MODE_Tcl: {
  10820. if( p->cnt++==0 && p->showHeader ){
  10821. for(i=0; i<nArg; i++){
  10822. output_c_string(p->out,azCol[i] ? azCol[i] : "");
  10823. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  10824. }
  10825. utf8_printf(p->out, "%s", p->rowSeparator);
  10826. }
  10827. if( azArg==0 ) break;
  10828. for(i=0; i<nArg; i++){
  10829. output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  10830. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  10831. }
  10832. utf8_printf(p->out, "%s", p->rowSeparator);
  10833. break;
  10834. }
  10835. case MODE_Csv: {
  10836. setBinaryMode(p->out, 1);
  10837. if( p->cnt++==0 && p->showHeader ){
  10838. for(i=0; i<nArg; i++){
  10839. output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  10840. }
  10841. utf8_printf(p->out, "%s", p->rowSeparator);
  10842. }
  10843. if( nArg>0 ){
  10844. for(i=0; i<nArg; i++){
  10845. output_csv(p, azArg[i], i<nArg-1);
  10846. }
  10847. utf8_printf(p->out, "%s", p->rowSeparator);
  10848. }
  10849. setTextMode(p->out, 1);
  10850. break;
  10851. }
  10852. case MODE_Insert: {
  10853. if( azArg==0 ) break;
  10854. utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
  10855. if( p->showHeader ){
  10856. raw_printf(p->out,"(");
  10857. for(i=0; i<nArg; i++){
  10858. if( i>0 ) raw_printf(p->out, ",");
  10859. if( quoteChar(azCol[i]) ){
  10860. char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
  10861. utf8_printf(p->out, "%s", z);
  10862. sqlite3_free(z);
  10863. }else{
  10864. raw_printf(p->out, "%s", azCol[i]);
  10865. }
  10866. }
  10867. raw_printf(p->out,")");
  10868. }
  10869. p->cnt++;
  10870. for(i=0; i<nArg; i++){
  10871. raw_printf(p->out, i>0 ? "," : " VALUES(");
  10872. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  10873. utf8_printf(p->out,"NULL");
  10874. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  10875. if( ShellHasFlag(p, SHFLG_Newlines) ){
  10876. output_quoted_string(p->out, azArg[i]);
  10877. }else{
  10878. output_quoted_escaped_string(p->out, azArg[i]);
  10879. }
  10880. }else if( aiType && aiType[i]==SQLITE_INTEGER ){
  10881. utf8_printf(p->out,"%s", azArg[i]);
  10882. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  10883. char z[50];
  10884. double r = sqlite3_column_double(p->pStmt, i);
  10885. sqlite3_uint64 ur;
  10886. memcpy(&ur,&r,sizeof(r));
  10887. if( ur==0x7ff0000000000000LL ){
  10888. raw_printf(p->out, "1e999");
  10889. }else if( ur==0xfff0000000000000LL ){
  10890. raw_printf(p->out, "-1e999");
  10891. }else{
  10892. sqlite3_snprintf(50,z,"%!.20g", r);
  10893. raw_printf(p->out, "%s", z);
  10894. }
  10895. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  10896. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  10897. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  10898. output_hex_blob(p->out, pBlob, nBlob);
  10899. }else if( isNumber(azArg[i], 0) ){
  10900. utf8_printf(p->out,"%s", azArg[i]);
  10901. }else if( ShellHasFlag(p, SHFLG_Newlines) ){
  10902. output_quoted_string(p->out, azArg[i]);
  10903. }else{
  10904. output_quoted_escaped_string(p->out, azArg[i]);
  10905. }
  10906. }
  10907. raw_printf(p->out,");\n");
  10908. break;
  10909. }
  10910. case MODE_Json: {
  10911. if( azArg==0 ) break;
  10912. if( p->cnt==0 ){
  10913. fputs("[{", p->out);
  10914. }else{
  10915. fputs(",\n{", p->out);
  10916. }
  10917. p->cnt++;
  10918. for(i=0; i<nArg; i++){
  10919. output_json_string(p->out, azCol[i], -1);
  10920. putc(':', p->out);
  10921. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  10922. fputs("null",p->out);
  10923. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  10924. char z[50];
  10925. double r = sqlite3_column_double(p->pStmt, i);
  10926. sqlite3_uint64 ur;
  10927. memcpy(&ur,&r,sizeof(r));
  10928. if( ur==0x7ff0000000000000LL ){
  10929. raw_printf(p->out, "1e999");
  10930. }else if( ur==0xfff0000000000000LL ){
  10931. raw_printf(p->out, "-1e999");
  10932. }else{
  10933. sqlite3_snprintf(50,z,"%!.20g", r);
  10934. raw_printf(p->out, "%s", z);
  10935. }
  10936. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  10937. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  10938. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  10939. output_json_string(p->out, pBlob, nBlob);
  10940. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  10941. output_json_string(p->out, azArg[i], -1);
  10942. }else{
  10943. utf8_printf(p->out,"%s", azArg[i]);
  10944. }
  10945. if( i<nArg-1 ){
  10946. putc(',', p->out);
  10947. }
  10948. }
  10949. putc('}', p->out);
  10950. break;
  10951. }
  10952. case MODE_Quote: {
  10953. if( azArg==0 ) break;
  10954. if( p->cnt==0 && p->showHeader ){
  10955. for(i=0; i<nArg; i++){
  10956. if( i>0 ) fputs(p->colSeparator, p->out);
  10957. output_quoted_string(p->out, azCol[i]);
  10958. }
  10959. fputs(p->rowSeparator, p->out);
  10960. }
  10961. p->cnt++;
  10962. for(i=0; i<nArg; i++){
  10963. if( i>0 ) fputs(p->colSeparator, p->out);
  10964. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  10965. utf8_printf(p->out,"NULL");
  10966. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  10967. output_quoted_string(p->out, azArg[i]);
  10968. }else if( aiType && aiType[i]==SQLITE_INTEGER ){
  10969. utf8_printf(p->out,"%s", azArg[i]);
  10970. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  10971. char z[50];
  10972. double r = sqlite3_column_double(p->pStmt, i);
  10973. sqlite3_snprintf(50,z,"%!.20g", r);
  10974. raw_printf(p->out, "%s", z);
  10975. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  10976. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  10977. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  10978. output_hex_blob(p->out, pBlob, nBlob);
  10979. }else if( isNumber(azArg[i], 0) ){
  10980. utf8_printf(p->out,"%s", azArg[i]);
  10981. }else{
  10982. output_quoted_string(p->out, azArg[i]);
  10983. }
  10984. }
  10985. fputs(p->rowSeparator, p->out);
  10986. break;
  10987. }
  10988. case MODE_Ascii: {
  10989. if( p->cnt++==0 && p->showHeader ){
  10990. for(i=0; i<nArg; i++){
  10991. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  10992. utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
  10993. }
  10994. utf8_printf(p->out, "%s", p->rowSeparator);
  10995. }
  10996. if( azArg==0 ) break;
  10997. for(i=0; i<nArg; i++){
  10998. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  10999. utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
  11000. }
  11001. utf8_printf(p->out, "%s", p->rowSeparator);
  11002. break;
  11003. }
  11004. case MODE_EQP: {
  11005. eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
  11006. break;
  11007. }
  11008. }
  11009. return 0;
  11010. }
  11011. /*
  11012. ** This is the callback routine that the SQLite library
  11013. ** invokes for each row of a query result.
  11014. */
  11015. static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  11016. /* since we don't have type info, call the shell_callback with a NULL value */
  11017. return shell_callback(pArg, nArg, azArg, azCol, NULL);
  11018. }
  11019. /*
  11020. ** This is the callback routine from sqlite3_exec() that appends all
  11021. ** output onto the end of a ShellText object.
  11022. */
  11023. static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
  11024. ShellText *p = (ShellText*)pArg;
  11025. int i;
  11026. UNUSED_PARAMETER(az);
  11027. if( azArg==0 ) return 0;
  11028. if( p->n ) appendText(p, "|", 0);
  11029. for(i=0; i<nArg; i++){
  11030. if( i ) appendText(p, ",", 0);
  11031. if( azArg[i] ) appendText(p, azArg[i], 0);
  11032. }
  11033. return 0;
  11034. }
  11035. /*
  11036. ** Generate an appropriate SELFTEST table in the main database.
  11037. */
  11038. static void createSelftestTable(ShellState *p){
  11039. char *zErrMsg = 0;
  11040. sqlite3_exec(p->db,
  11041. "SAVEPOINT selftest_init;\n"
  11042. "CREATE TABLE IF NOT EXISTS selftest(\n"
  11043. " tno INTEGER PRIMARY KEY,\n" /* Test number */
  11044. " op TEXT,\n" /* Operator: memo run */
  11045. " cmd TEXT,\n" /* Command text */
  11046. " ans TEXT\n" /* Desired answer */
  11047. ");"
  11048. "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
  11049. "INSERT INTO [_shell$self](rowid,op,cmd)\n"
  11050. " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
  11051. " 'memo','Tests generated by --init');\n"
  11052. "INSERT INTO [_shell$self]\n"
  11053. " SELECT 'run',\n"
  11054. " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
  11055. "FROM sqlite_schema ORDER BY 2'',224))',\n"
  11056. " hex(sha3_query('SELECT type,name,tbl_name,sql "
  11057. "FROM sqlite_schema ORDER BY 2',224));\n"
  11058. "INSERT INTO [_shell$self]\n"
  11059. " SELECT 'run',"
  11060. " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
  11061. " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
  11062. " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
  11063. " FROM (\n"
  11064. " SELECT name FROM sqlite_schema\n"
  11065. " WHERE type='table'\n"
  11066. " AND name<>'selftest'\n"
  11067. " AND coalesce(rootpage,0)>0\n"
  11068. " )\n"
  11069. " ORDER BY name;\n"
  11070. "INSERT INTO [_shell$self]\n"
  11071. " VALUES('run','PRAGMA integrity_check','ok');\n"
  11072. "INSERT INTO selftest(tno,op,cmd,ans)"
  11073. " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
  11074. "DROP TABLE [_shell$self];"
  11075. ,0,0,&zErrMsg);
  11076. if( zErrMsg ){
  11077. utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
  11078. sqlite3_free(zErrMsg);
  11079. }
  11080. sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
  11081. }
  11082. /*
  11083. ** Set the destination table field of the ShellState structure to
  11084. ** the name of the table given. Escape any quote characters in the
  11085. ** table name.
  11086. */
  11087. static void set_table_name(ShellState *p, const char *zName){
  11088. int i, n;
  11089. char cQuote;
  11090. char *z;
  11091. if( p->zDestTable ){
  11092. free(p->zDestTable);
  11093. p->zDestTable = 0;
  11094. }
  11095. if( zName==0 ) return;
  11096. cQuote = quoteChar(zName);
  11097. n = strlen30(zName);
  11098. if( cQuote ) n += n+2;
  11099. z = p->zDestTable = malloc( n+1 );
  11100. if( z==0 ) shell_out_of_memory();
  11101. n = 0;
  11102. if( cQuote ) z[n++] = cQuote;
  11103. for(i=0; zName[i]; i++){
  11104. z[n++] = zName[i];
  11105. if( zName[i]==cQuote ) z[n++] = cQuote;
  11106. }
  11107. if( cQuote ) z[n++] = cQuote;
  11108. z[n] = 0;
  11109. }
  11110. /*
  11111. ** Execute a query statement that will generate SQL output. Print
  11112. ** the result columns, comma-separated, on a line and then add a
  11113. ** semicolon terminator to the end of that line.
  11114. **
  11115. ** If the number of columns is 1 and that column contains text "--"
  11116. ** then write the semicolon on a separate line. That way, if a
  11117. ** "--" comment occurs at the end of the statement, the comment
  11118. ** won't consume the semicolon terminator.
  11119. */
  11120. static int run_table_dump_query(
  11121. ShellState *p, /* Query context */
  11122. const char *zSelect /* SELECT statement to extract content */
  11123. ){
  11124. sqlite3_stmt *pSelect;
  11125. int rc;
  11126. int nResult;
  11127. int i;
  11128. const char *z;
  11129. rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
  11130. if( rc!=SQLITE_OK || !pSelect ){
  11131. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  11132. sqlite3_errmsg(p->db));
  11133. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  11134. return rc;
  11135. }
  11136. rc = sqlite3_step(pSelect);
  11137. nResult = sqlite3_column_count(pSelect);
  11138. while( rc==SQLITE_ROW ){
  11139. z = (const char*)sqlite3_column_text(pSelect, 0);
  11140. utf8_printf(p->out, "%s", z);
  11141. for(i=1; i<nResult; i++){
  11142. utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
  11143. }
  11144. if( z==0 ) z = "";
  11145. while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
  11146. if( z[0] ){
  11147. raw_printf(p->out, "\n;\n");
  11148. }else{
  11149. raw_printf(p->out, ";\n");
  11150. }
  11151. rc = sqlite3_step(pSelect);
  11152. }
  11153. rc = sqlite3_finalize(pSelect);
  11154. if( rc!=SQLITE_OK ){
  11155. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  11156. sqlite3_errmsg(p->db));
  11157. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  11158. }
  11159. return rc;
  11160. }
  11161. /*
  11162. ** Allocate space and save off current error string.
  11163. */
  11164. static char *save_err_msg(
  11165. sqlite3 *db /* Database to query */
  11166. ){
  11167. int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
  11168. char *zErrMsg = sqlite3_malloc64(nErrMsg);
  11169. if( zErrMsg ){
  11170. memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
  11171. }
  11172. return zErrMsg;
  11173. }
  11174. #ifdef __linux__
  11175. /*
  11176. ** Attempt to display I/O stats on Linux using /proc/PID/io
  11177. */
  11178. static void displayLinuxIoStats(FILE *out){
  11179. FILE *in;
  11180. char z[200];
  11181. sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
  11182. in = fopen(z, "rb");
  11183. if( in==0 ) return;
  11184. while( fgets(z, sizeof(z), in)!=0 ){
  11185. static const struct {
  11186. const char *zPattern;
  11187. const char *zDesc;
  11188. } aTrans[] = {
  11189. { "rchar: ", "Bytes received by read():" },
  11190. { "wchar: ", "Bytes sent to write():" },
  11191. { "syscr: ", "Read() system calls:" },
  11192. { "syscw: ", "Write() system calls:" },
  11193. { "read_bytes: ", "Bytes read from storage:" },
  11194. { "write_bytes: ", "Bytes written to storage:" },
  11195. { "cancelled_write_bytes: ", "Cancelled write bytes:" },
  11196. };
  11197. int i;
  11198. for(i=0; i<ArraySize(aTrans); i++){
  11199. int n = strlen30(aTrans[i].zPattern);
  11200. if( strncmp(aTrans[i].zPattern, z, n)==0 ){
  11201. utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
  11202. break;
  11203. }
  11204. }
  11205. }
  11206. fclose(in);
  11207. }
  11208. #endif
  11209. /*
  11210. ** Display a single line of status using 64-bit values.
  11211. */
  11212. static void displayStatLine(
  11213. ShellState *p, /* The shell context */
  11214. char *zLabel, /* Label for this one line */
  11215. char *zFormat, /* Format for the result */
  11216. int iStatusCtrl, /* Which status to display */
  11217. int bReset /* True to reset the stats */
  11218. ){
  11219. sqlite3_int64 iCur = -1;
  11220. sqlite3_int64 iHiwtr = -1;
  11221. int i, nPercent;
  11222. char zLine[200];
  11223. sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
  11224. for(i=0, nPercent=0; zFormat[i]; i++){
  11225. if( zFormat[i]=='%' ) nPercent++;
  11226. }
  11227. if( nPercent>1 ){
  11228. sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
  11229. }else{
  11230. sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
  11231. }
  11232. raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
  11233. }
  11234. /*
  11235. ** Display memory stats.
  11236. */
  11237. static int display_stats(
  11238. sqlite3 *db, /* Database to query */
  11239. ShellState *pArg, /* Pointer to ShellState */
  11240. int bReset /* True to reset the stats */
  11241. ){
  11242. int iCur;
  11243. int iHiwtr;
  11244. FILE *out;
  11245. if( pArg==0 || pArg->out==0 ) return 0;
  11246. out = pArg->out;
  11247. if( pArg->pStmt && (pArg->statsOn & 2) ){
  11248. int nCol, i, x;
  11249. sqlite3_stmt *pStmt = pArg->pStmt;
  11250. char z[100];
  11251. nCol = sqlite3_column_count(pStmt);
  11252. raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
  11253. for(i=0; i<nCol; i++){
  11254. sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
  11255. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
  11256. #ifndef SQLITE_OMIT_DECLTYPE
  11257. sqlite3_snprintf(30, z+x, "declared type:");
  11258. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
  11259. #endif
  11260. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  11261. sqlite3_snprintf(30, z+x, "database name:");
  11262. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
  11263. sqlite3_snprintf(30, z+x, "table name:");
  11264. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
  11265. sqlite3_snprintf(30, z+x, "origin name:");
  11266. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
  11267. #endif
  11268. }
  11269. }
  11270. displayStatLine(pArg, "Memory Used:",
  11271. "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
  11272. displayStatLine(pArg, "Number of Outstanding Allocations:",
  11273. "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
  11274. if( pArg->shellFlgs & SHFLG_Pagecache ){
  11275. displayStatLine(pArg, "Number of Pcache Pages Used:",
  11276. "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
  11277. }
  11278. displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
  11279. "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
  11280. displayStatLine(pArg, "Largest Allocation:",
  11281. "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
  11282. displayStatLine(pArg, "Largest Pcache Allocation:",
  11283. "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
  11284. #ifdef YYTRACKMAXSTACKDEPTH
  11285. displayStatLine(pArg, "Deepest Parser Stack:",
  11286. "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
  11287. #endif
  11288. if( db ){
  11289. if( pArg->shellFlgs & SHFLG_Lookaside ){
  11290. iHiwtr = iCur = -1;
  11291. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
  11292. &iCur, &iHiwtr, bReset);
  11293. raw_printf(pArg->out,
  11294. "Lookaside Slots Used: %d (max %d)\n",
  11295. iCur, iHiwtr);
  11296. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
  11297. &iCur, &iHiwtr, bReset);
  11298. raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
  11299. iHiwtr);
  11300. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
  11301. &iCur, &iHiwtr, bReset);
  11302. raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
  11303. iHiwtr);
  11304. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
  11305. &iCur, &iHiwtr, bReset);
  11306. raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
  11307. iHiwtr);
  11308. }
  11309. iHiwtr = iCur = -1;
  11310. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
  11311. raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
  11312. iCur);
  11313. iHiwtr = iCur = -1;
  11314. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
  11315. raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
  11316. iHiwtr = iCur = -1;
  11317. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
  11318. raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
  11319. iHiwtr = iCur = -1;
  11320. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
  11321. raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
  11322. iHiwtr = iCur = -1;
  11323. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
  11324. raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
  11325. iHiwtr = iCur = -1;
  11326. sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
  11327. raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
  11328. iCur);
  11329. iHiwtr = iCur = -1;
  11330. sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
  11331. raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
  11332. iCur);
  11333. }
  11334. if( pArg->pStmt ){
  11335. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
  11336. bReset);
  11337. raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
  11338. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
  11339. raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
  11340. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
  11341. raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
  11342. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
  11343. raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
  11344. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
  11345. raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
  11346. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
  11347. raw_printf(pArg->out, "Number of times run: %d\n", iCur);
  11348. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
  11349. raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
  11350. }
  11351. #ifdef __linux__
  11352. displayLinuxIoStats(pArg->out);
  11353. #endif
  11354. /* Do not remove this machine readable comment: extra-stats-output-here */
  11355. return 0;
  11356. }
  11357. /*
  11358. ** Display scan stats.
  11359. */
  11360. static void display_scanstats(
  11361. sqlite3 *db, /* Database to query */
  11362. ShellState *pArg /* Pointer to ShellState */
  11363. ){
  11364. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  11365. UNUSED_PARAMETER(db);
  11366. UNUSED_PARAMETER(pArg);
  11367. #else
  11368. int i, k, n, mx;
  11369. raw_printf(pArg->out, "-------- scanstats --------\n");
  11370. mx = 0;
  11371. for(k=0; k<=mx; k++){
  11372. double rEstLoop = 1.0;
  11373. for(i=n=0; 1; i++){
  11374. sqlite3_stmt *p = pArg->pStmt;
  11375. sqlite3_int64 nLoop, nVisit;
  11376. double rEst;
  11377. int iSid;
  11378. const char *zExplain;
  11379. if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
  11380. break;
  11381. }
  11382. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
  11383. if( iSid>mx ) mx = iSid;
  11384. if( iSid!=k ) continue;
  11385. if( n==0 ){
  11386. rEstLoop = (double)nLoop;
  11387. if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
  11388. }
  11389. n++;
  11390. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
  11391. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
  11392. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
  11393. utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
  11394. rEstLoop *= rEst;
  11395. raw_printf(pArg->out,
  11396. " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
  11397. nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
  11398. );
  11399. }
  11400. }
  11401. raw_printf(pArg->out, "---------------------------\n");
  11402. #endif
  11403. }
  11404. /*
  11405. ** Parameter azArray points to a zero-terminated array of strings. zStr
  11406. ** points to a single nul-terminated string. Return non-zero if zStr
  11407. ** is equal, according to strcmp(), to any of the strings in the array.
  11408. ** Otherwise, return zero.
  11409. */
  11410. static int str_in_array(const char *zStr, const char **azArray){
  11411. int i;
  11412. for(i=0; azArray[i]; i++){
  11413. if( 0==strcmp(zStr, azArray[i]) ) return 1;
  11414. }
  11415. return 0;
  11416. }
  11417. /*
  11418. ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
  11419. ** and populate the ShellState.aiIndent[] array with the number of
  11420. ** spaces each opcode should be indented before it is output.
  11421. **
  11422. ** The indenting rules are:
  11423. **
  11424. ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
  11425. ** all opcodes that occur between the p2 jump destination and the opcode
  11426. ** itself by 2 spaces.
  11427. **
  11428. ** * For each "Goto", if the jump destination is earlier in the program
  11429. ** and ends on one of:
  11430. ** Yield SeekGt SeekLt RowSetRead Rewind
  11431. ** or if the P1 parameter is one instead of zero,
  11432. ** then indent all opcodes between the earlier instruction
  11433. ** and "Goto" by 2 spaces.
  11434. */
  11435. static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
  11436. const char *zSql; /* The text of the SQL statement */
  11437. const char *z; /* Used to check if this is an EXPLAIN */
  11438. int *abYield = 0; /* True if op is an OP_Yield */
  11439. int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
  11440. int iOp; /* Index of operation in p->aiIndent[] */
  11441. const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
  11442. const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
  11443. "Rewind", 0 };
  11444. const char *azGoto[] = { "Goto", 0 };
  11445. /* Try to figure out if this is really an EXPLAIN statement. If this
  11446. ** cannot be verified, return early. */
  11447. if( sqlite3_column_count(pSql)!=8 ){
  11448. p->cMode = p->mode;
  11449. return;
  11450. }
  11451. zSql = sqlite3_sql(pSql);
  11452. if( zSql==0 ) return;
  11453. for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
  11454. if( sqlite3_strnicmp(z, "explain", 7) ){
  11455. p->cMode = p->mode;
  11456. return;
  11457. }
  11458. for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
  11459. int i;
  11460. int iAddr = sqlite3_column_int(pSql, 0);
  11461. const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
  11462. /* Set p2 to the P2 field of the current opcode. Then, assuming that
  11463. ** p2 is an instruction address, set variable p2op to the index of that
  11464. ** instruction in the aiIndent[] array. p2 and p2op may be different if
  11465. ** the current instruction is part of a sub-program generated by an
  11466. ** SQL trigger or foreign key. */
  11467. int p2 = sqlite3_column_int(pSql, 3);
  11468. int p2op = (p2 + (iOp-iAddr));
  11469. /* Grow the p->aiIndent array as required */
  11470. if( iOp>=nAlloc ){
  11471. if( iOp==0 ){
  11472. /* Do further verfication that this is explain output. Abort if
  11473. ** it is not */
  11474. static const char *explainCols[] = {
  11475. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
  11476. int jj;
  11477. for(jj=0; jj<ArraySize(explainCols); jj++){
  11478. if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
  11479. p->cMode = p->mode;
  11480. sqlite3_reset(pSql);
  11481. return;
  11482. }
  11483. }
  11484. }
  11485. nAlloc += 100;
  11486. p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
  11487. if( p->aiIndent==0 ) shell_out_of_memory();
  11488. abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
  11489. if( abYield==0 ) shell_out_of_memory();
  11490. }
  11491. abYield[iOp] = str_in_array(zOp, azYield);
  11492. p->aiIndent[iOp] = 0;
  11493. p->nIndent = iOp+1;
  11494. if( str_in_array(zOp, azNext) ){
  11495. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  11496. }
  11497. if( str_in_array(zOp, azGoto) && p2op<p->nIndent
  11498. && (abYield[p2op] || sqlite3_column_int(pSql, 2))
  11499. ){
  11500. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  11501. }
  11502. }
  11503. p->iIndent = 0;
  11504. sqlite3_free(abYield);
  11505. sqlite3_reset(pSql);
  11506. }
  11507. /*
  11508. ** Free the array allocated by explain_data_prepare().
  11509. */
  11510. static void explain_data_delete(ShellState *p){
  11511. sqlite3_free(p->aiIndent);
  11512. p->aiIndent = 0;
  11513. p->nIndent = 0;
  11514. p->iIndent = 0;
  11515. }
  11516. /*
  11517. ** Disable and restore .wheretrace and .selecttrace settings.
  11518. */
  11519. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  11520. extern unsigned int sqlite3_unsupported_selecttrace;
  11521. static int savedSelectTrace;
  11522. #endif
  11523. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  11524. extern int sqlite3WhereTrace;
  11525. static int savedWhereTrace;
  11526. #endif
  11527. static void disable_debug_trace_modes(void){
  11528. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  11529. savedSelectTrace = sqlite3_unsupported_selecttrace;
  11530. sqlite3_unsupported_selecttrace = 0;
  11531. #endif
  11532. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  11533. savedWhereTrace = sqlite3WhereTrace;
  11534. sqlite3WhereTrace = 0;
  11535. #endif
  11536. }
  11537. static void restore_debug_trace_modes(void){
  11538. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  11539. sqlite3_unsupported_selecttrace = savedSelectTrace;
  11540. #endif
  11541. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  11542. sqlite3WhereTrace = savedWhereTrace;
  11543. #endif
  11544. }
  11545. /* Create the TEMP table used to store parameter bindings */
  11546. static void bind_table_init(ShellState *p){
  11547. int wrSchema = 0;
  11548. int defensiveMode = 0;
  11549. sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
  11550. sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
  11551. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
  11552. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
  11553. sqlite3_exec(p->db,
  11554. "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
  11555. " key TEXT PRIMARY KEY,\n"
  11556. " value ANY\n"
  11557. ") WITHOUT ROWID;",
  11558. 0, 0, 0);
  11559. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
  11560. sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
  11561. }
  11562. /*
  11563. ** Bind parameters on a prepared statement.
  11564. **
  11565. ** Parameter bindings are taken from a TEMP table of the form:
  11566. **
  11567. ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
  11568. ** WITHOUT ROWID;
  11569. **
  11570. ** No bindings occur if this table does not exist. The name of the table
  11571. ** begins with "sqlite_" so that it will not collide with ordinary application
  11572. ** tables. The table must be in the TEMP schema.
  11573. */
  11574. static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
  11575. int nVar;
  11576. int i;
  11577. int rc;
  11578. sqlite3_stmt *pQ = 0;
  11579. nVar = sqlite3_bind_parameter_count(pStmt);
  11580. if( nVar==0 ) return; /* Nothing to do */
  11581. if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
  11582. "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
  11583. return; /* Parameter table does not exist */
  11584. }
  11585. rc = sqlite3_prepare_v2(pArg->db,
  11586. "SELECT value FROM temp.sqlite_parameters"
  11587. " WHERE key=?1", -1, &pQ, 0);
  11588. if( rc || pQ==0 ) return;
  11589. for(i=1; i<=nVar; i++){
  11590. char zNum[30];
  11591. const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
  11592. if( zVar==0 ){
  11593. sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
  11594. zVar = zNum;
  11595. }
  11596. sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
  11597. if( sqlite3_step(pQ)==SQLITE_ROW ){
  11598. sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
  11599. }else{
  11600. sqlite3_bind_null(pStmt, i);
  11601. }
  11602. sqlite3_reset(pQ);
  11603. }
  11604. sqlite3_finalize(pQ);
  11605. }
  11606. /*
  11607. ** UTF8 box-drawing characters. Imagine box lines like this:
  11608. **
  11609. ** 1
  11610. ** |
  11611. ** 4 --+-- 2
  11612. ** |
  11613. ** 3
  11614. **
  11615. ** Each box characters has between 2 and 4 of the lines leading from
  11616. ** the center. The characters are here identified by the numbers of
  11617. ** their corresponding lines.
  11618. */
  11619. #define BOX_24 "\342\224\200" /* U+2500 --- */
  11620. #define BOX_13 "\342\224\202" /* U+2502 | */
  11621. #define BOX_23 "\342\224\214" /* U+250c ,- */
  11622. #define BOX_34 "\342\224\220" /* U+2510 -, */
  11623. #define BOX_12 "\342\224\224" /* U+2514 '- */
  11624. #define BOX_14 "\342\224\230" /* U+2518 -' */
  11625. #define BOX_123 "\342\224\234" /* U+251c |- */
  11626. #define BOX_134 "\342\224\244" /* U+2524 -| */
  11627. #define BOX_234 "\342\224\254" /* U+252c -,- */
  11628. #define BOX_124 "\342\224\264" /* U+2534 -'- */
  11629. #define BOX_1234 "\342\224\274" /* U+253c -|- */
  11630. /* Draw horizontal line N characters long using unicode box
  11631. ** characters
  11632. */
  11633. static void print_box_line(FILE *out, int N){
  11634. const char zDash[] =
  11635. BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
  11636. BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
  11637. const int nDash = sizeof(zDash) - 1;
  11638. N *= 3;
  11639. while( N>nDash ){
  11640. utf8_printf(out, zDash);
  11641. N -= nDash;
  11642. }
  11643. utf8_printf(out, "%.*s", N, zDash);
  11644. }
  11645. /*
  11646. ** Draw a horizontal separator for a MODE_Box table.
  11647. */
  11648. static void print_box_row_separator(
  11649. ShellState *p,
  11650. int nArg,
  11651. const char *zSep1,
  11652. const char *zSep2,
  11653. const char *zSep3
  11654. ){
  11655. int i;
  11656. if( nArg>0 ){
  11657. utf8_printf(p->out, "%s", zSep1);
  11658. print_box_line(p->out, p->actualWidth[0]+2);
  11659. for(i=1; i<nArg; i++){
  11660. utf8_printf(p->out, "%s", zSep2);
  11661. print_box_line(p->out, p->actualWidth[i]+2);
  11662. }
  11663. utf8_printf(p->out, "%s", zSep3);
  11664. }
  11665. fputs("\n", p->out);
  11666. }
  11667. /*
  11668. ** Run a prepared statement and output the result in one of the
  11669. ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
  11670. ** or MODE_Box.
  11671. **
  11672. ** This is different from ordinary exec_prepared_stmt() in that
  11673. ** it has to run the entire query and gather the results into memory
  11674. ** first, in order to determine column widths, before providing
  11675. ** any output.
  11676. */
  11677. static void exec_prepared_stmt_columnar(
  11678. ShellState *p, /* Pointer to ShellState */
  11679. sqlite3_stmt *pStmt /* Statment to run */
  11680. ){
  11681. sqlite3_int64 nRow = 0;
  11682. int nColumn = 0;
  11683. char **azData = 0;
  11684. sqlite3_int64 nAlloc = 0;
  11685. const char *z;
  11686. int rc;
  11687. sqlite3_int64 i, nData;
  11688. int j, nTotal, w, n;
  11689. const char *colSep = 0;
  11690. const char *rowSep = 0;
  11691. rc = sqlite3_step(pStmt);
  11692. if( rc!=SQLITE_ROW ) return;
  11693. nColumn = sqlite3_column_count(pStmt);
  11694. nAlloc = nColumn*4;
  11695. azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
  11696. if( azData==0 ) shell_out_of_memory();
  11697. for(i=0; i<nColumn; i++){
  11698. azData[i] = strdup(sqlite3_column_name(pStmt,i));
  11699. }
  11700. do{
  11701. if( (nRow+2)*nColumn >= nAlloc ){
  11702. nAlloc *= 2;
  11703. azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
  11704. if( azData==0 ) shell_out_of_memory();
  11705. }
  11706. nRow++;
  11707. for(i=0; i<nColumn; i++){
  11708. z = (const char*)sqlite3_column_text(pStmt,i);
  11709. azData[nRow*nColumn + i] = z ? strdup(z) : 0;
  11710. }
  11711. }while( (rc = sqlite3_step(pStmt))==SQLITE_ROW );
  11712. if( nColumn>p->nWidth ){
  11713. p->colWidth = realloc(p->colWidth, nColumn*2*sizeof(int));
  11714. if( p->colWidth==0 ) shell_out_of_memory();
  11715. for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
  11716. p->nWidth = nColumn;
  11717. p->actualWidth = &p->colWidth[nColumn];
  11718. }
  11719. memset(p->actualWidth, 0, nColumn*sizeof(int));
  11720. for(i=0; i<nColumn; i++){
  11721. w = p->colWidth[i];
  11722. if( w<0 ) w = -w;
  11723. p->actualWidth[i] = w;
  11724. }
  11725. nTotal = nColumn*(nRow+1);
  11726. for(i=0; i<nTotal; i++){
  11727. z = azData[i];
  11728. if( z==0 ) z = p->nullValue;
  11729. n = strlenChar(z);
  11730. j = i%nColumn;
  11731. if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
  11732. }
  11733. if( seenInterrupt ) goto columnar_end;
  11734. switch( p->cMode ){
  11735. case MODE_Column: {
  11736. colSep = " ";
  11737. rowSep = "\n";
  11738. if( p->showHeader ){
  11739. for(i=0; i<nColumn; i++){
  11740. w = p->actualWidth[i];
  11741. if( p->colWidth[i]<0 ) w = -w;
  11742. utf8_width_print(p->out, w, azData[i]);
  11743. fputs(i==nColumn-1?"\n":" ", p->out);
  11744. }
  11745. for(i=0; i<nColumn; i++){
  11746. print_dashes(p->out, p->actualWidth[i]);
  11747. fputs(i==nColumn-1?"\n":" ", p->out);
  11748. }
  11749. }
  11750. break;
  11751. }
  11752. case MODE_Table: {
  11753. colSep = " | ";
  11754. rowSep = " |\n";
  11755. print_row_separator(p, nColumn, "+");
  11756. fputs("| ", p->out);
  11757. for(i=0; i<nColumn; i++){
  11758. w = p->actualWidth[i];
  11759. n = strlenChar(azData[i]);
  11760. utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
  11761. fputs(i==nColumn-1?" |\n":" | ", p->out);
  11762. }
  11763. print_row_separator(p, nColumn, "+");
  11764. break;
  11765. }
  11766. case MODE_Markdown: {
  11767. colSep = " | ";
  11768. rowSep = " |\n";
  11769. fputs("| ", p->out);
  11770. for(i=0; i<nColumn; i++){
  11771. w = p->actualWidth[i];
  11772. n = strlenChar(azData[i]);
  11773. utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
  11774. fputs(i==nColumn-1?" |\n":" | ", p->out);
  11775. }
  11776. print_row_separator(p, nColumn, "|");
  11777. break;
  11778. }
  11779. case MODE_Box: {
  11780. colSep = " " BOX_13 " ";
  11781. rowSep = " " BOX_13 "\n";
  11782. print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
  11783. utf8_printf(p->out, BOX_13 " ");
  11784. for(i=0; i<nColumn; i++){
  11785. w = p->actualWidth[i];
  11786. n = strlenChar(azData[i]);
  11787. utf8_printf(p->out, "%*s%s%*s%s",
  11788. (w-n)/2, "", azData[i], (w-n+1)/2, "",
  11789. i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
  11790. }
  11791. print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
  11792. break;
  11793. }
  11794. }
  11795. for(i=nColumn, j=0; i<nTotal; i++, j++){
  11796. if( j==0 && p->cMode!=MODE_Column ){
  11797. utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
  11798. }
  11799. z = azData[i];
  11800. if( z==0 ) z = p->nullValue;
  11801. w = p->actualWidth[j];
  11802. if( p->colWidth[j]<0 ) w = -w;
  11803. utf8_width_print(p->out, w, z);
  11804. if( j==nColumn-1 ){
  11805. utf8_printf(p->out, "%s", rowSep);
  11806. j = -1;
  11807. if( seenInterrupt ) goto columnar_end;
  11808. }else{
  11809. utf8_printf(p->out, "%s", colSep);
  11810. }
  11811. }
  11812. if( p->cMode==MODE_Table ){
  11813. print_row_separator(p, nColumn, "+");
  11814. }else if( p->cMode==MODE_Box ){
  11815. print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
  11816. }
  11817. columnar_end:
  11818. if( seenInterrupt ){
  11819. utf8_printf(p->out, "Interrupt\n");
  11820. }
  11821. nData = (nRow+1)*nColumn;
  11822. for(i=0; i<nData; i++) free(azData[i]);
  11823. sqlite3_free(azData);
  11824. }
  11825. /*
  11826. ** Run a prepared statement
  11827. */
  11828. static void exec_prepared_stmt(
  11829. ShellState *pArg, /* Pointer to ShellState */
  11830. sqlite3_stmt *pStmt /* Statment to run */
  11831. ){
  11832. int rc;
  11833. if( pArg->cMode==MODE_Column
  11834. || pArg->cMode==MODE_Table
  11835. || pArg->cMode==MODE_Box
  11836. || pArg->cMode==MODE_Markdown
  11837. ){
  11838. exec_prepared_stmt_columnar(pArg, pStmt);
  11839. return;
  11840. }
  11841. /* perform the first step. this will tell us if we
  11842. ** have a result set or not and how wide it is.
  11843. */
  11844. rc = sqlite3_step(pStmt);
  11845. /* if we have a result set... */
  11846. if( SQLITE_ROW == rc ){
  11847. /* allocate space for col name ptr, value ptr, and type */
  11848. int nCol = sqlite3_column_count(pStmt);
  11849. void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
  11850. if( !pData ){
  11851. rc = SQLITE_NOMEM;
  11852. }else{
  11853. char **azCols = (char **)pData; /* Names of result columns */
  11854. char **azVals = &azCols[nCol]; /* Results */
  11855. int *aiTypes = (int *)&azVals[nCol]; /* Result types */
  11856. int i, x;
  11857. assert(sizeof(int) <= sizeof(char *));
  11858. /* save off ptrs to column names */
  11859. for(i=0; i<nCol; i++){
  11860. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  11861. }
  11862. do{
  11863. /* extract the data and data types */
  11864. for(i=0; i<nCol; i++){
  11865. aiTypes[i] = x = sqlite3_column_type(pStmt, i);
  11866. if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
  11867. azVals[i] = "";
  11868. }else{
  11869. azVals[i] = (char*)sqlite3_column_text(pStmt, i);
  11870. }
  11871. if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
  11872. rc = SQLITE_NOMEM;
  11873. break; /* from for */
  11874. }
  11875. } /* end for */
  11876. /* if data and types extracted successfully... */
  11877. if( SQLITE_ROW == rc ){
  11878. /* call the supplied callback with the result row data */
  11879. if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
  11880. rc = SQLITE_ABORT;
  11881. }else{
  11882. rc = sqlite3_step(pStmt);
  11883. }
  11884. }
  11885. } while( SQLITE_ROW == rc );
  11886. sqlite3_free(pData);
  11887. if( pArg->cMode==MODE_Json ){
  11888. fputs("]\n", pArg->out);
  11889. }
  11890. }
  11891. }
  11892. }
  11893. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11894. /*
  11895. ** This function is called to process SQL if the previous shell command
  11896. ** was ".expert". It passes the SQL in the second argument directly to
  11897. ** the sqlite3expert object.
  11898. **
  11899. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
  11900. ** code. In this case, (*pzErr) may be set to point to a buffer containing
  11901. ** an English language error message. It is the responsibility of the
  11902. ** caller to eventually free this buffer using sqlite3_free().
  11903. */
  11904. static int expertHandleSQL(
  11905. ShellState *pState,
  11906. const char *zSql,
  11907. char **pzErr
  11908. ){
  11909. assert( pState->expert.pExpert );
  11910. assert( pzErr==0 || *pzErr==0 );
  11911. return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
  11912. }
  11913. /*
  11914. ** This function is called either to silently clean up the object
  11915. ** created by the ".expert" command (if bCancel==1), or to generate a
  11916. ** report from it and then clean it up (if bCancel==0).
  11917. **
  11918. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
  11919. ** code. In this case, (*pzErr) may be set to point to a buffer containing
  11920. ** an English language error message. It is the responsibility of the
  11921. ** caller to eventually free this buffer using sqlite3_free().
  11922. */
  11923. static int expertFinish(
  11924. ShellState *pState,
  11925. int bCancel,
  11926. char **pzErr
  11927. ){
  11928. int rc = SQLITE_OK;
  11929. sqlite3expert *p = pState->expert.pExpert;
  11930. assert( p );
  11931. assert( bCancel || pzErr==0 || *pzErr==0 );
  11932. if( bCancel==0 ){
  11933. FILE *out = pState->out;
  11934. int bVerbose = pState->expert.bVerbose;
  11935. rc = sqlite3_expert_analyze(p, pzErr);
  11936. if( rc==SQLITE_OK ){
  11937. int nQuery = sqlite3_expert_count(p);
  11938. int i;
  11939. if( bVerbose ){
  11940. const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
  11941. raw_printf(out, "-- Candidates -----------------------------\n");
  11942. raw_printf(out, "%s\n", zCand);
  11943. }
  11944. for(i=0; i<nQuery; i++){
  11945. const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
  11946. const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
  11947. const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
  11948. if( zIdx==0 ) zIdx = "(no new indexes)\n";
  11949. if( bVerbose ){
  11950. raw_printf(out, "-- Query %d --------------------------------\n",i+1);
  11951. raw_printf(out, "%s\n\n", zSql);
  11952. }
  11953. raw_printf(out, "%s\n", zIdx);
  11954. raw_printf(out, "%s\n", zEQP);
  11955. }
  11956. }
  11957. }
  11958. sqlite3_expert_destroy(p);
  11959. pState->expert.pExpert = 0;
  11960. return rc;
  11961. }
  11962. /*
  11963. ** Implementation of ".expert" dot command.
  11964. */
  11965. static int expertDotCommand(
  11966. ShellState *pState, /* Current shell tool state */
  11967. char **azArg, /* Array of arguments passed to dot command */
  11968. int nArg /* Number of entries in azArg[] */
  11969. ){
  11970. int rc = SQLITE_OK;
  11971. char *zErr = 0;
  11972. int i;
  11973. int iSample = 0;
  11974. assert( pState->expert.pExpert==0 );
  11975. memset(&pState->expert, 0, sizeof(ExpertInfo));
  11976. for(i=1; rc==SQLITE_OK && i<nArg; i++){
  11977. char *z = azArg[i];
  11978. int n;
  11979. if( z[0]=='-' && z[1]=='-' ) z++;
  11980. n = strlen30(z);
  11981. if( n>=2 && 0==strncmp(z, "-verbose", n) ){
  11982. pState->expert.bVerbose = 1;
  11983. }
  11984. else if( n>=2 && 0==strncmp(z, "-sample", n) ){
  11985. if( i==(nArg-1) ){
  11986. raw_printf(stderr, "option requires an argument: %s\n", z);
  11987. rc = SQLITE_ERROR;
  11988. }else{
  11989. iSample = (int)integerValue(azArg[++i]);
  11990. if( iSample<0 || iSample>100 ){
  11991. raw_printf(stderr, "value out of range: %s\n", azArg[i]);
  11992. rc = SQLITE_ERROR;
  11993. }
  11994. }
  11995. }
  11996. else{
  11997. raw_printf(stderr, "unknown option: %s\n", z);
  11998. rc = SQLITE_ERROR;
  11999. }
  12000. }
  12001. if( rc==SQLITE_OK ){
  12002. pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
  12003. if( pState->expert.pExpert==0 ){
  12004. raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
  12005. rc = SQLITE_ERROR;
  12006. }else{
  12007. sqlite3_expert_config(
  12008. pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
  12009. );
  12010. }
  12011. }
  12012. return rc;
  12013. }
  12014. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  12015. /*
  12016. ** Execute a statement or set of statements. Print
  12017. ** any result rows/columns depending on the current mode
  12018. ** set via the supplied callback.
  12019. **
  12020. ** This is very similar to SQLite's built-in sqlite3_exec()
  12021. ** function except it takes a slightly different callback
  12022. ** and callback data argument.
  12023. */
  12024. static int shell_exec(
  12025. ShellState *pArg, /* Pointer to ShellState */
  12026. const char *zSql, /* SQL to be evaluated */
  12027. char **pzErrMsg /* Error msg written here */
  12028. ){
  12029. sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
  12030. int rc = SQLITE_OK; /* Return Code */
  12031. int rc2;
  12032. const char *zLeftover; /* Tail of unprocessed SQL */
  12033. sqlite3 *db = pArg->db;
  12034. if( pzErrMsg ){
  12035. *pzErrMsg = NULL;
  12036. }
  12037. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12038. if( pArg->expert.pExpert ){
  12039. rc = expertHandleSQL(pArg, zSql, pzErrMsg);
  12040. return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
  12041. }
  12042. #endif
  12043. while( zSql[0] && (SQLITE_OK == rc) ){
  12044. static const char *zStmtSql;
  12045. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  12046. if( SQLITE_OK != rc ){
  12047. if( pzErrMsg ){
  12048. *pzErrMsg = save_err_msg(db);
  12049. }
  12050. }else{
  12051. if( !pStmt ){
  12052. /* this happens for a comment or white-space */
  12053. zSql = zLeftover;
  12054. while( IsSpace(zSql[0]) ) zSql++;
  12055. continue;
  12056. }
  12057. zStmtSql = sqlite3_sql(pStmt);
  12058. if( zStmtSql==0 ) zStmtSql = "";
  12059. while( IsSpace(zStmtSql[0]) ) zStmtSql++;
  12060. /* save off the prepared statment handle and reset row count */
  12061. if( pArg ){
  12062. pArg->pStmt = pStmt;
  12063. pArg->cnt = 0;
  12064. }
  12065. /* echo the sql statement if echo on */
  12066. if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
  12067. utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  12068. }
  12069. /* Show the EXPLAIN QUERY PLAN if .eqp is on */
  12070. if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
  12071. sqlite3_stmt *pExplain;
  12072. char *zEQP;
  12073. int triggerEQP = 0;
  12074. disable_debug_trace_modes();
  12075. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
  12076. if( pArg->autoEQP>=AUTOEQP_trigger ){
  12077. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
  12078. }
  12079. zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
  12080. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  12081. if( rc==SQLITE_OK ){
  12082. while( sqlite3_step(pExplain)==SQLITE_ROW ){
  12083. const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
  12084. int iEqpId = sqlite3_column_int(pExplain, 0);
  12085. int iParentId = sqlite3_column_int(pExplain, 1);
  12086. if( zEQPLine==0 ) zEQPLine = "";
  12087. if( zEQPLine[0]=='-' ) eqp_render(pArg);
  12088. eqp_append(pArg, iEqpId, iParentId, zEQPLine);
  12089. }
  12090. eqp_render(pArg);
  12091. }
  12092. sqlite3_finalize(pExplain);
  12093. sqlite3_free(zEQP);
  12094. if( pArg->autoEQP>=AUTOEQP_full ){
  12095. /* Also do an EXPLAIN for ".eqp full" mode */
  12096. zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
  12097. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  12098. if( rc==SQLITE_OK ){
  12099. pArg->cMode = MODE_Explain;
  12100. explain_data_prepare(pArg, pExplain);
  12101. exec_prepared_stmt(pArg, pExplain);
  12102. explain_data_delete(pArg);
  12103. }
  12104. sqlite3_finalize(pExplain);
  12105. sqlite3_free(zEQP);
  12106. }
  12107. if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
  12108. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
  12109. /* Reprepare pStmt before reactiving trace modes */
  12110. sqlite3_finalize(pStmt);
  12111. sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  12112. if( pArg ) pArg->pStmt = pStmt;
  12113. }
  12114. restore_debug_trace_modes();
  12115. }
  12116. if( pArg ){
  12117. pArg->cMode = pArg->mode;
  12118. if( pArg->autoExplain ){
  12119. if( sqlite3_stmt_isexplain(pStmt)==1 ){
  12120. pArg->cMode = MODE_Explain;
  12121. }
  12122. if( sqlite3_stmt_isexplain(pStmt)==2 ){
  12123. pArg->cMode = MODE_EQP;
  12124. }
  12125. }
  12126. /* If the shell is currently in ".explain" mode, gather the extra
  12127. ** data required to add indents to the output.*/
  12128. if( pArg->cMode==MODE_Explain ){
  12129. explain_data_prepare(pArg, pStmt);
  12130. }
  12131. }
  12132. bind_prepared_stmt(pArg, pStmt);
  12133. exec_prepared_stmt(pArg, pStmt);
  12134. explain_data_delete(pArg);
  12135. eqp_render(pArg);
  12136. /* print usage stats if stats on */
  12137. if( pArg && pArg->statsOn ){
  12138. display_stats(db, pArg, 0);
  12139. }
  12140. /* print loop-counters if required */
  12141. if( pArg && pArg->scanstatsOn ){
  12142. display_scanstats(db, pArg);
  12143. }
  12144. /* Finalize the statement just executed. If this fails, save a
  12145. ** copy of the error message. Otherwise, set zSql to point to the
  12146. ** next statement to execute. */
  12147. rc2 = sqlite3_finalize(pStmt);
  12148. if( rc!=SQLITE_NOMEM ) rc = rc2;
  12149. if( rc==SQLITE_OK ){
  12150. zSql = zLeftover;
  12151. while( IsSpace(zSql[0]) ) zSql++;
  12152. }else if( pzErrMsg ){
  12153. *pzErrMsg = save_err_msg(db);
  12154. }
  12155. /* clear saved stmt handle */
  12156. if( pArg ){
  12157. pArg->pStmt = NULL;
  12158. }
  12159. }
  12160. } /* end while */
  12161. return rc;
  12162. }
  12163. /*
  12164. ** Release memory previously allocated by tableColumnList().
  12165. */
  12166. static void freeColumnList(char **azCol){
  12167. int i;
  12168. for(i=1; azCol[i]; i++){
  12169. sqlite3_free(azCol[i]);
  12170. }
  12171. /* azCol[0] is a static string */
  12172. sqlite3_free(azCol);
  12173. }
  12174. /*
  12175. ** Return a list of pointers to strings which are the names of all
  12176. ** columns in table zTab. The memory to hold the names is dynamically
  12177. ** allocated and must be released by the caller using a subsequent call
  12178. ** to freeColumnList().
  12179. **
  12180. ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
  12181. ** value that needs to be preserved, then azCol[0] is filled in with the
  12182. ** name of the rowid column.
  12183. **
  12184. ** The first regular column in the table is azCol[1]. The list is terminated
  12185. ** by an entry with azCol[i]==0.
  12186. */
  12187. static char **tableColumnList(ShellState *p, const char *zTab){
  12188. char **azCol = 0;
  12189. sqlite3_stmt *pStmt;
  12190. char *zSql;
  12191. int nCol = 0;
  12192. int nAlloc = 0;
  12193. int nPK = 0; /* Number of PRIMARY KEY columns seen */
  12194. int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
  12195. int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
  12196. int rc;
  12197. zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
  12198. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  12199. sqlite3_free(zSql);
  12200. if( rc ) return 0;
  12201. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  12202. if( nCol>=nAlloc-2 ){
  12203. nAlloc = nAlloc*2 + nCol + 10;
  12204. azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
  12205. if( azCol==0 ) shell_out_of_memory();
  12206. }
  12207. azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
  12208. if( sqlite3_column_int(pStmt, 5) ){
  12209. nPK++;
  12210. if( nPK==1
  12211. && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
  12212. "INTEGER")==0
  12213. ){
  12214. isIPK = 1;
  12215. }else{
  12216. isIPK = 0;
  12217. }
  12218. }
  12219. }
  12220. sqlite3_finalize(pStmt);
  12221. if( azCol==0 ) return 0;
  12222. azCol[0] = 0;
  12223. azCol[nCol+1] = 0;
  12224. /* The decision of whether or not a rowid really needs to be preserved
  12225. ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
  12226. ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
  12227. ** rowids on tables where the rowid is inaccessible because there are other
  12228. ** columns in the table named "rowid", "_rowid_", and "oid".
  12229. */
  12230. if( preserveRowid && isIPK ){
  12231. /* If a single PRIMARY KEY column with type INTEGER was seen, then it
  12232. ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
  12233. ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
  12234. ** ROWID aliases. To distinguish these cases, check to see if
  12235. ** there is a "pk" entry in "PRAGMA index_list". There will be
  12236. ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
  12237. */
  12238. zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
  12239. " WHERE origin='pk'", zTab);
  12240. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  12241. sqlite3_free(zSql);
  12242. if( rc ){
  12243. freeColumnList(azCol);
  12244. return 0;
  12245. }
  12246. rc = sqlite3_step(pStmt);
  12247. sqlite3_finalize(pStmt);
  12248. preserveRowid = rc==SQLITE_ROW;
  12249. }
  12250. if( preserveRowid ){
  12251. /* Only preserve the rowid if we can find a name to use for the
  12252. ** rowid */
  12253. static char *azRowid[] = { "rowid", "_rowid_", "oid" };
  12254. int i, j;
  12255. for(j=0; j<3; j++){
  12256. for(i=1; i<=nCol; i++){
  12257. if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
  12258. }
  12259. if( i>nCol ){
  12260. /* At this point, we know that azRowid[j] is not the name of any
  12261. ** ordinary column in the table. Verify that azRowid[j] is a valid
  12262. ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
  12263. ** tables will fail this last check */
  12264. rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
  12265. if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
  12266. break;
  12267. }
  12268. }
  12269. }
  12270. return azCol;
  12271. }
  12272. /*
  12273. ** Toggle the reverse_unordered_selects setting.
  12274. */
  12275. static void toggleSelectOrder(sqlite3 *db){
  12276. sqlite3_stmt *pStmt = 0;
  12277. int iSetting = 0;
  12278. char zStmt[100];
  12279. sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
  12280. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  12281. iSetting = sqlite3_column_int(pStmt, 0);
  12282. }
  12283. sqlite3_finalize(pStmt);
  12284. sqlite3_snprintf(sizeof(zStmt), zStmt,
  12285. "PRAGMA reverse_unordered_selects(%d)", !iSetting);
  12286. sqlite3_exec(db, zStmt, 0, 0, 0);
  12287. }
  12288. /*
  12289. ** This is a different callback routine used for dumping the database.
  12290. ** Each row received by this callback consists of a table name,
  12291. ** the table type ("index" or "table") and SQL to create the table.
  12292. ** This routine should print text sufficient to recreate the table.
  12293. */
  12294. static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
  12295. int rc;
  12296. const char *zTable;
  12297. const char *zType;
  12298. const char *zSql;
  12299. ShellState *p = (ShellState *)pArg;
  12300. UNUSED_PARAMETER(azNotUsed);
  12301. if( nArg!=3 || azArg==0 ) return 0;
  12302. zTable = azArg[0];
  12303. zType = azArg[1];
  12304. zSql = azArg[2];
  12305. if( strcmp(zTable, "sqlite_sequence")==0 ){
  12306. raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
  12307. }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
  12308. raw_printf(p->out, "ANALYZE sqlite_schema;\n");
  12309. }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  12310. return 0;
  12311. }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  12312. char *zIns;
  12313. if( !p->writableSchema ){
  12314. raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
  12315. p->writableSchema = 1;
  12316. }
  12317. zIns = sqlite3_mprintf(
  12318. "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
  12319. "VALUES('table','%q','%q',0,'%q');",
  12320. zTable, zTable, zSql);
  12321. utf8_printf(p->out, "%s\n", zIns);
  12322. sqlite3_free(zIns);
  12323. return 0;
  12324. }else{
  12325. printSchemaLine(p->out, zSql, ";\n");
  12326. }
  12327. if( strcmp(zType, "table")==0 ){
  12328. ShellText sSelect;
  12329. ShellText sTable;
  12330. char **azCol;
  12331. int i;
  12332. char *savedDestTable;
  12333. int savedMode;
  12334. azCol = tableColumnList(p, zTable);
  12335. if( azCol==0 ){
  12336. p->nErr++;
  12337. return 0;
  12338. }
  12339. /* Always quote the table name, even if it appears to be pure ascii,
  12340. ** in case it is a keyword. Ex: INSERT INTO "table" ... */
  12341. initText(&sTable);
  12342. appendText(&sTable, zTable, quoteChar(zTable));
  12343. /* If preserving the rowid, add a column list after the table name.
  12344. ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
  12345. ** instead of the usual "INSERT INTO tab VALUES(...)".
  12346. */
  12347. if( azCol[0] ){
  12348. appendText(&sTable, "(", 0);
  12349. appendText(&sTable, azCol[0], 0);
  12350. for(i=1; azCol[i]; i++){
  12351. appendText(&sTable, ",", 0);
  12352. appendText(&sTable, azCol[i], quoteChar(azCol[i]));
  12353. }
  12354. appendText(&sTable, ")", 0);
  12355. }
  12356. /* Build an appropriate SELECT statement */
  12357. initText(&sSelect);
  12358. appendText(&sSelect, "SELECT ", 0);
  12359. if( azCol[0] ){
  12360. appendText(&sSelect, azCol[0], 0);
  12361. appendText(&sSelect, ",", 0);
  12362. }
  12363. for(i=1; azCol[i]; i++){
  12364. appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
  12365. if( azCol[i+1] ){
  12366. appendText(&sSelect, ",", 0);
  12367. }
  12368. }
  12369. freeColumnList(azCol);
  12370. appendText(&sSelect, " FROM ", 0);
  12371. appendText(&sSelect, zTable, quoteChar(zTable));
  12372. savedDestTable = p->zDestTable;
  12373. savedMode = p->mode;
  12374. p->zDestTable = sTable.z;
  12375. p->mode = p->cMode = MODE_Insert;
  12376. rc = shell_exec(p, sSelect.z, 0);
  12377. if( (rc&0xff)==SQLITE_CORRUPT ){
  12378. raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  12379. toggleSelectOrder(p->db);
  12380. shell_exec(p, sSelect.z, 0);
  12381. toggleSelectOrder(p->db);
  12382. }
  12383. p->zDestTable = savedDestTable;
  12384. p->mode = savedMode;
  12385. freeText(&sTable);
  12386. freeText(&sSelect);
  12387. if( rc ) p->nErr++;
  12388. }
  12389. return 0;
  12390. }
  12391. /*
  12392. ** Run zQuery. Use dump_callback() as the callback routine so that
  12393. ** the contents of the query are output as SQL statements.
  12394. **
  12395. ** If we get a SQLITE_CORRUPT error, rerun the query after appending
  12396. ** "ORDER BY rowid DESC" to the end.
  12397. */
  12398. static int run_schema_dump_query(
  12399. ShellState *p,
  12400. const char *zQuery
  12401. ){
  12402. int rc;
  12403. char *zErr = 0;
  12404. rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
  12405. if( rc==SQLITE_CORRUPT ){
  12406. char *zQ2;
  12407. int len = strlen30(zQuery);
  12408. raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  12409. if( zErr ){
  12410. utf8_printf(p->out, "/****** %s ******/\n", zErr);
  12411. sqlite3_free(zErr);
  12412. zErr = 0;
  12413. }
  12414. zQ2 = malloc( len+100 );
  12415. if( zQ2==0 ) return rc;
  12416. sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
  12417. rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
  12418. if( rc ){
  12419. utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
  12420. }else{
  12421. rc = SQLITE_CORRUPT;
  12422. }
  12423. sqlite3_free(zErr);
  12424. free(zQ2);
  12425. }
  12426. return rc;
  12427. }
  12428. /*
  12429. ** Text of help messages.
  12430. **
  12431. ** The help text for each individual command begins with a line that starts
  12432. ** with ".". Subsequent lines are supplimental information.
  12433. **
  12434. ** There must be two or more spaces between the end of the command and the
  12435. ** start of the description of what that command does.
  12436. */
  12437. static const char *(azHelp[]) = {
  12438. #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
  12439. ".archive ... Manage SQL archives",
  12440. " Each command must have exactly one of the following options:",
  12441. " -c, --create Create a new archive",
  12442. " -u, --update Add or update files with changed mtime",
  12443. " -i, --insert Like -u but always add even if unchanged",
  12444. " -t, --list List contents of archive",
  12445. " -x, --extract Extract files from archive",
  12446. " Optional arguments:",
  12447. " -v, --verbose Print each filename as it is processed",
  12448. " -f FILE, --file FILE Use archive FILE (default is current db)",
  12449. " -a FILE, --append FILE Open FILE using the apndvfs VFS",
  12450. " -C DIR, --directory DIR Read/extract files from directory DIR",
  12451. " -n, --dryrun Show the SQL that would have occurred",
  12452. " Examples:",
  12453. " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
  12454. " .ar -tf ARCHIVE # List members of ARCHIVE",
  12455. " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
  12456. " See also:",
  12457. " http://sqlite.org/cli.html#sqlar_archive_support",
  12458. #endif
  12459. #ifndef SQLITE_OMIT_AUTHORIZATION
  12460. ".auth ON|OFF Show authorizer callbacks",
  12461. #endif
  12462. ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
  12463. " --append Use the appendvfs",
  12464. " --async Write to FILE without journal and fsync()",
  12465. ".bail on|off Stop after hitting an error. Default OFF",
  12466. ".binary on|off Turn binary output on or off. Default OFF",
  12467. ".cd DIRECTORY Change the working directory to DIRECTORY",
  12468. ".changes on|off Show number of rows changed by SQL",
  12469. ".check GLOB Fail if output since .testcase does not match",
  12470. ".clone NEWDB Clone data into NEWDB from the existing database",
  12471. ".databases List names and files of attached databases",
  12472. ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
  12473. ".dbinfo ?DB? Show status information about the database",
  12474. ".dump ?TABLE? Render database content as SQL",
  12475. " Options:",
  12476. " --preserve-rowids Include ROWID values in the output",
  12477. " --newlines Allow unescaped newline characters in output",
  12478. " TABLE is a LIKE pattern for the tables to dump",
  12479. " Additional LIKE patterns can be given in subsequent arguments",
  12480. ".echo on|off Turn command echo on or off",
  12481. ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
  12482. " Other Modes:",
  12483. #ifdef SQLITE_DEBUG
  12484. " test Show raw EXPLAIN QUERY PLAN output",
  12485. " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
  12486. #endif
  12487. " trigger Like \"full\" but also show trigger bytecode",
  12488. ".excel Display the output of next command in spreadsheet",
  12489. " --bom Put a UTF8 byte-order mark on intermediate file",
  12490. ".exit ?CODE? Exit this program with return-code CODE",
  12491. ".expert EXPERIMENTAL. Suggest indexes for queries",
  12492. ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
  12493. ".filectrl CMD ... Run various sqlite3_file_control() operations",
  12494. " --schema SCHEMA Use SCHEMA instead of \"main\"",
  12495. " --help Show CMD details",
  12496. ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
  12497. ".headers on|off Turn display of headers on or off",
  12498. ".help ?-all? ?PATTERN? Show help text for PATTERN",
  12499. ".import FILE TABLE Import data from FILE into TABLE",
  12500. " Options:",
  12501. " --ascii Use \\037 and \\036 as column and row separators",
  12502. " --csv Use , and \\n as column and row separators",
  12503. " --skip N Skip the first N rows of input",
  12504. " -v \"Verbose\" - increase auxiliary output",
  12505. " Notes:",
  12506. " * If TABLE does not exist, it is created. The first row of input",
  12507. " determines the column names.",
  12508. " * If neither --csv or --ascii are used, the input mode is derived",
  12509. " from the \".mode\" output mode",
  12510. " * If FILE begins with \"|\" then it is a command that generates the",
  12511. " input text.",
  12512. #ifndef SQLITE_OMIT_TEST_CONTROL
  12513. ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
  12514. #endif
  12515. ".indexes ?TABLE? Show names of indexes",
  12516. " If TABLE is specified, only show indexes for",
  12517. " tables matching TABLE using the LIKE operator.",
  12518. #ifdef SQLITE_ENABLE_IOTRACE
  12519. ".iotrace FILE Enable I/O diagnostic logging to FILE",
  12520. #endif
  12521. ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
  12522. ".lint OPTIONS Report potential schema issues.",
  12523. " Options:",
  12524. " fkey-indexes Find missing foreign key indexes",
  12525. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  12526. ".load FILE ?ENTRY? Load an extension library",
  12527. #endif
  12528. ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
  12529. ".mode MODE ?TABLE? Set output mode",
  12530. " MODE is one of:",
  12531. " ascii Columns/rows delimited by 0x1F and 0x1E",
  12532. " box Tables using unicode box-drawing characters",
  12533. " csv Comma-separated values",
  12534. " column Output in columns. (See .width)",
  12535. " html HTML <table> code",
  12536. " insert SQL insert statements for TABLE",
  12537. " json Results in a JSON array",
  12538. " line One value per line",
  12539. " list Values delimited by \"|\"",
  12540. " markdown Markdown table format",
  12541. " quote Escape answers as for SQL",
  12542. " table ASCII-art table",
  12543. " tabs Tab-separated values",
  12544. " tcl TCL list elements",
  12545. ".nullvalue STRING Use STRING in place of NULL values",
  12546. ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
  12547. " If FILE begins with '|' then open as a pipe",
  12548. " --bom Put a UTF8 byte-order mark at the beginning",
  12549. " -e Send output to the system text editor",
  12550. " -x Send output as CSV to a spreadsheet (same as \".excel\")",
  12551. #ifdef SQLITE_DEBUG
  12552. ".oom ?--repeat M? ?N? Simulate an OOM error on the N-th allocation",
  12553. #endif
  12554. ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
  12555. " Options:",
  12556. " --append Use appendvfs to append database to the end of FILE",
  12557. #ifdef SQLITE_ENABLE_DESERIALIZE
  12558. " --deserialize Load into memory useing sqlite3_deserialize()",
  12559. " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
  12560. " --maxsize N Maximum size for --hexdb or --deserialized database",
  12561. #endif
  12562. " --new Initialize FILE to an empty database",
  12563. " --nofollow Do not follow symbolic links",
  12564. " --readonly Open FILE readonly",
  12565. " --zip FILE is a ZIP archive",
  12566. ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
  12567. " If FILE begins with '|' then open it as a pipe.",
  12568. " Options:",
  12569. " --bom Prefix output with a UTF8 byte-order mark",
  12570. " -e Send output to the system text editor",
  12571. " -x Send output as CSV to a spreadsheet",
  12572. ".parameter CMD ... Manage SQL parameter bindings",
  12573. " clear Erase all bindings",
  12574. " init Initialize the TEMP table that holds bindings",
  12575. " list List the current parameter bindings",
  12576. " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
  12577. " PARAMETER should start with one of: $ : @ ?",
  12578. " unset PARAMETER Remove PARAMETER from the binding table",
  12579. ".print STRING... Print literal STRING",
  12580. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  12581. ".progress N Invoke progress handler after every N opcodes",
  12582. " --limit N Interrupt after N progress callbacks",
  12583. " --once Do no more than one progress interrupt",
  12584. " --quiet|-q No output except at interrupts",
  12585. " --reset Reset the count for each input and interrupt",
  12586. #endif
  12587. ".prompt MAIN CONTINUE Replace the standard prompts",
  12588. ".quit Exit this program",
  12589. ".read FILE Read input from FILE",
  12590. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
  12591. ".recover Recover as much data as possible from corrupt db.",
  12592. " --freelist-corrupt Assume the freelist is corrupt",
  12593. " --recovery-db NAME Store recovery metadata in database file NAME",
  12594. " --lost-and-found TABLE Alternative name for the lost-and-found table",
  12595. " --no-rowids Do not attempt to recover rowid values",
  12596. " that are not also INTEGER PRIMARY KEYs",
  12597. #endif
  12598. ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
  12599. ".save FILE Write in-memory database into FILE",
  12600. ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
  12601. ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
  12602. " Options:",
  12603. " --indent Try to pretty-print the schema",
  12604. ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
  12605. " Options:",
  12606. " --init Create a new SELFTEST table",
  12607. " -v Verbose output",
  12608. ".separator COL ?ROW? Change the column and row separators",
  12609. #if defined(SQLITE_ENABLE_SESSION)
  12610. ".session ?NAME? CMD ... Create or control sessions",
  12611. " Subcommands:",
  12612. " attach TABLE Attach TABLE",
  12613. " changeset FILE Write a changeset into FILE",
  12614. " close Close one session",
  12615. " enable ?BOOLEAN? Set or query the enable bit",
  12616. " filter GLOB... Reject tables matching GLOBs",
  12617. " indirect ?BOOLEAN? Mark or query the indirect status",
  12618. " isempty Query whether the session is empty",
  12619. " list List currently open session names",
  12620. " open DB NAME Open a new session on DB",
  12621. " patchset FILE Write a patchset into FILE",
  12622. " If ?NAME? is omitted, the first defined session is used.",
  12623. #endif
  12624. ".sha3sum ... Compute a SHA3 hash of database content",
  12625. " Options:",
  12626. " --schema Also hash the sqlite_schema table",
  12627. " --sha3-224 Use the sha3-224 algorithm",
  12628. " --sha3-256 Use the sha3-256 algorithm (default)",
  12629. " --sha3-384 Use the sha3-384 algorithm",
  12630. " --sha3-512 Use the sha3-512 algorithm",
  12631. " Any other argument is a LIKE pattern for tables to hash",
  12632. #ifndef SQLITE_NOHAVE_SYSTEM
  12633. ".shell CMD ARGS... Run CMD ARGS... in a system shell",
  12634. #endif
  12635. ".show Show the current values for various settings",
  12636. ".stats ?on|off? Show stats or turn stats on or off",
  12637. #ifndef SQLITE_NOHAVE_SYSTEM
  12638. ".system CMD ARGS... Run CMD ARGS... in a system shell",
  12639. #endif
  12640. ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
  12641. ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
  12642. ".testctrl CMD ... Run various sqlite3_test_control() operations",
  12643. " Run \".testctrl\" with no arguments for details",
  12644. ".timeout MS Try opening locked tables for MS milliseconds",
  12645. ".timer on|off Turn SQL timer on or off",
  12646. #ifndef SQLITE_OMIT_TRACE
  12647. ".trace ?OPTIONS? Output each SQL statement as it is run",
  12648. " FILE Send output to FILE",
  12649. " stdout Send output to stdout",
  12650. " stderr Send output to stderr",
  12651. " off Disable tracing",
  12652. " --expanded Expand query parameters",
  12653. #ifdef SQLITE_ENABLE_NORMALIZE
  12654. " --normalized Normal the SQL statements",
  12655. #endif
  12656. " --plain Show SQL as it is input",
  12657. " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
  12658. " --profile Profile statements (SQLITE_TRACE_PROFILE)",
  12659. " --row Trace each row (SQLITE_TRACE_ROW)",
  12660. " --close Trace connection close (SQLITE_TRACE_CLOSE)",
  12661. #endif /* SQLITE_OMIT_TRACE */
  12662. #ifdef SQLITE_DEBUG
  12663. ".unmodule NAME ... Unregister virtual table modules",
  12664. " --allexcept Unregister everything except those named",
  12665. #endif
  12666. ".vfsinfo ?AUX? Information about the top-level VFS",
  12667. ".vfslist List all available VFSes",
  12668. ".vfsname ?AUX? Print the name of the VFS stack",
  12669. ".width NUM1 NUM2 ... Set minimum column widths for columnar output",
  12670. " Negative values right-justify",
  12671. };
  12672. /*
  12673. ** Output help text.
  12674. **
  12675. ** zPattern describes the set of commands for which help text is provided.
  12676. ** If zPattern is NULL, then show all commands, but only give a one-line
  12677. ** description of each.
  12678. **
  12679. ** Return the number of matches.
  12680. */
  12681. static int showHelp(FILE *out, const char *zPattern){
  12682. int i = 0;
  12683. int j = 0;
  12684. int n = 0;
  12685. char *zPat;
  12686. if( zPattern==0
  12687. || zPattern[0]=='0'
  12688. || strcmp(zPattern,"-a")==0
  12689. || strcmp(zPattern,"-all")==0
  12690. || strcmp(zPattern,"--all")==0
  12691. ){
  12692. /* Show all commands, but only one line per command */
  12693. if( zPattern==0 ) zPattern = "";
  12694. for(i=0; i<ArraySize(azHelp); i++){
  12695. if( azHelp[i][0]=='.' || zPattern[0] ){
  12696. utf8_printf(out, "%s\n", azHelp[i]);
  12697. n++;
  12698. }
  12699. }
  12700. }else{
  12701. /* Look for commands that for which zPattern is an exact prefix */
  12702. zPat = sqlite3_mprintf(".%s*", zPattern);
  12703. for(i=0; i<ArraySize(azHelp); i++){
  12704. if( sqlite3_strglob(zPat, azHelp[i])==0 ){
  12705. utf8_printf(out, "%s\n", azHelp[i]);
  12706. j = i+1;
  12707. n++;
  12708. }
  12709. }
  12710. sqlite3_free(zPat);
  12711. if( n ){
  12712. if( n==1 ){
  12713. /* when zPattern is a prefix of exactly one command, then include the
  12714. ** details of that command, which should begin at offset j */
  12715. while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
  12716. utf8_printf(out, "%s\n", azHelp[j]);
  12717. j++;
  12718. }
  12719. }
  12720. return n;
  12721. }
  12722. /* Look for commands that contain zPattern anywhere. Show the complete
  12723. ** text of all commands that match. */
  12724. zPat = sqlite3_mprintf("%%%s%%", zPattern);
  12725. for(i=0; i<ArraySize(azHelp); i++){
  12726. if( azHelp[i][0]=='.' ) j = i;
  12727. if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
  12728. utf8_printf(out, "%s\n", azHelp[j]);
  12729. while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
  12730. j++;
  12731. utf8_printf(out, "%s\n", azHelp[j]);
  12732. }
  12733. i = j;
  12734. n++;
  12735. }
  12736. }
  12737. sqlite3_free(zPat);
  12738. }
  12739. return n;
  12740. }
  12741. /* Forward reference */
  12742. static int process_input(ShellState *p);
  12743. /*
  12744. ** Read the content of file zName into memory obtained from sqlite3_malloc64()
  12745. ** and return a pointer to the buffer. The caller is responsible for freeing
  12746. ** the memory.
  12747. **
  12748. ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
  12749. ** read.
  12750. **
  12751. ** For convenience, a nul-terminator byte is always appended to the data read
  12752. ** from the file before the buffer is returned. This byte is not included in
  12753. ** the final value of (*pnByte), if applicable.
  12754. **
  12755. ** NULL is returned if any error is encountered. The final value of *pnByte
  12756. ** is undefined in this case.
  12757. */
  12758. static char *readFile(const char *zName, int *pnByte){
  12759. FILE *in = fopen(zName, "rb");
  12760. long nIn;
  12761. size_t nRead;
  12762. char *pBuf;
  12763. if( in==0 ) return 0;
  12764. fseek(in, 0, SEEK_END);
  12765. nIn = ftell(in);
  12766. rewind(in);
  12767. pBuf = sqlite3_malloc64( nIn+1 );
  12768. if( pBuf==0 ){ fclose(in); return 0; }
  12769. nRead = fread(pBuf, nIn, 1, in);
  12770. fclose(in);
  12771. if( nRead!=1 ){
  12772. sqlite3_free(pBuf);
  12773. return 0;
  12774. }
  12775. pBuf[nIn] = 0;
  12776. if( pnByte ) *pnByte = nIn;
  12777. return pBuf;
  12778. }
  12779. #if defined(SQLITE_ENABLE_SESSION)
  12780. /*
  12781. ** Close a single OpenSession object and release all of its associated
  12782. ** resources.
  12783. */
  12784. static void session_close(OpenSession *pSession){
  12785. int i;
  12786. sqlite3session_delete(pSession->p);
  12787. sqlite3_free(pSession->zName);
  12788. for(i=0; i<pSession->nFilter; i++){
  12789. sqlite3_free(pSession->azFilter[i]);
  12790. }
  12791. sqlite3_free(pSession->azFilter);
  12792. memset(pSession, 0, sizeof(OpenSession));
  12793. }
  12794. #endif
  12795. /*
  12796. ** Close all OpenSession objects and release all associated resources.
  12797. */
  12798. #if defined(SQLITE_ENABLE_SESSION)
  12799. static void session_close_all(ShellState *p){
  12800. int i;
  12801. for(i=0; i<p->nSession; i++){
  12802. session_close(&p->aSession[i]);
  12803. }
  12804. p->nSession = 0;
  12805. }
  12806. #else
  12807. # define session_close_all(X)
  12808. #endif
  12809. /*
  12810. ** Implementation of the xFilter function for an open session. Omit
  12811. ** any tables named by ".session filter" but let all other table through.
  12812. */
  12813. #if defined(SQLITE_ENABLE_SESSION)
  12814. static int session_filter(void *pCtx, const char *zTab){
  12815. OpenSession *pSession = (OpenSession*)pCtx;
  12816. int i;
  12817. for(i=0; i<pSession->nFilter; i++){
  12818. if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
  12819. }
  12820. return 1;
  12821. }
  12822. #endif
  12823. /*
  12824. ** Try to deduce the type of file for zName based on its content. Return
  12825. ** one of the SHELL_OPEN_* constants.
  12826. **
  12827. ** If the file does not exist or is empty but its name looks like a ZIP
  12828. ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
  12829. ** Otherwise, assume an ordinary database regardless of the filename if
  12830. ** the type cannot be determined from content.
  12831. */
  12832. int deduceDatabaseType(const char *zName, int dfltZip){
  12833. FILE *f = fopen(zName, "rb");
  12834. size_t n;
  12835. int rc = SHELL_OPEN_UNSPEC;
  12836. char zBuf[100];
  12837. if( f==0 ){
  12838. if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
  12839. return SHELL_OPEN_ZIPFILE;
  12840. }else{
  12841. return SHELL_OPEN_NORMAL;
  12842. }
  12843. }
  12844. n = fread(zBuf, 16, 1, f);
  12845. if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
  12846. fclose(f);
  12847. return SHELL_OPEN_NORMAL;
  12848. }
  12849. fseek(f, -25, SEEK_END);
  12850. n = fread(zBuf, 25, 1, f);
  12851. if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
  12852. rc = SHELL_OPEN_APPENDVFS;
  12853. }else{
  12854. fseek(f, -22, SEEK_END);
  12855. n = fread(zBuf, 22, 1, f);
  12856. if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
  12857. && zBuf[3]==0x06 ){
  12858. rc = SHELL_OPEN_ZIPFILE;
  12859. }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
  12860. rc = SHELL_OPEN_ZIPFILE;
  12861. }
  12862. }
  12863. fclose(f);
  12864. return rc;
  12865. }
  12866. #ifdef SQLITE_ENABLE_DESERIALIZE
  12867. /*
  12868. ** Reconstruct an in-memory database using the output from the "dbtotxt"
  12869. ** program. Read content from the file in p->zDbFilename. If p->zDbFilename
  12870. ** is 0, then read from standard input.
  12871. */
  12872. static unsigned char *readHexDb(ShellState *p, int *pnData){
  12873. unsigned char *a = 0;
  12874. int nLine;
  12875. int n = 0;
  12876. int pgsz = 0;
  12877. int iOffset = 0;
  12878. int j, k;
  12879. int rc;
  12880. FILE *in;
  12881. unsigned int x[16];
  12882. char zLine[1000];
  12883. if( p->zDbFilename ){
  12884. in = fopen(p->zDbFilename, "r");
  12885. if( in==0 ){
  12886. utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
  12887. return 0;
  12888. }
  12889. nLine = 0;
  12890. }else{
  12891. in = p->in;
  12892. nLine = p->lineno;
  12893. if( in==0 ) in = stdin;
  12894. }
  12895. *pnData = 0;
  12896. nLine++;
  12897. if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
  12898. rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
  12899. if( rc!=2 ) goto readHexDb_error;
  12900. if( n<0 ) goto readHexDb_error;
  12901. if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
  12902. n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */
  12903. a = sqlite3_malloc( n ? n : 1 );
  12904. if( a==0 ){
  12905. utf8_printf(stderr, "Out of memory!\n");
  12906. goto readHexDb_error;
  12907. }
  12908. memset(a, 0, n);
  12909. if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
  12910. utf8_printf(stderr, "invalid pagesize\n");
  12911. goto readHexDb_error;
  12912. }
  12913. for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
  12914. rc = sscanf(zLine, "| page %d offset %d", &j, &k);
  12915. if( rc==2 ){
  12916. iOffset = k;
  12917. continue;
  12918. }
  12919. if( strncmp(zLine, "| end ", 6)==0 ){
  12920. break;
  12921. }
  12922. rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
  12923. &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
  12924. &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
  12925. if( rc==17 ){
  12926. k = iOffset+j;
  12927. if( k+16<=n ){
  12928. int ii;
  12929. for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
  12930. }
  12931. }
  12932. }
  12933. *pnData = n;
  12934. if( in!=p->in ){
  12935. fclose(in);
  12936. }else{
  12937. p->lineno = nLine;
  12938. }
  12939. return a;
  12940. readHexDb_error:
  12941. if( in!=p->in ){
  12942. fclose(in);
  12943. }else{
  12944. while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
  12945. nLine++;
  12946. if(strncmp(zLine, "| end ", 6)==0 ) break;
  12947. }
  12948. p->lineno = nLine;
  12949. }
  12950. sqlite3_free(a);
  12951. utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
  12952. return 0;
  12953. }
  12954. #endif /* SQLITE_ENABLE_DESERIALIZE */
  12955. /*
  12956. ** Scalar function "shell_int32". The first argument to this function
  12957. ** must be a blob. The second a non-negative integer. This function
  12958. ** reads and returns a 32-bit big-endian integer from byte
  12959. ** offset (4*<arg2>) of the blob.
  12960. */
  12961. static void shellInt32(
  12962. sqlite3_context *context,
  12963. int argc,
  12964. sqlite3_value **argv
  12965. ){
  12966. const unsigned char *pBlob;
  12967. int nBlob;
  12968. int iInt;
  12969. UNUSED_PARAMETER(argc);
  12970. nBlob = sqlite3_value_bytes(argv[0]);
  12971. pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
  12972. iInt = sqlite3_value_int(argv[1]);
  12973. if( iInt>=0 && (iInt+1)*4<=nBlob ){
  12974. const unsigned char *a = &pBlob[iInt*4];
  12975. sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
  12976. + ((sqlite3_int64)a[1]<<16)
  12977. + ((sqlite3_int64)a[2]<< 8)
  12978. + ((sqlite3_int64)a[3]<< 0);
  12979. sqlite3_result_int64(context, iVal);
  12980. }
  12981. }
  12982. /*
  12983. ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
  12984. ** using "..." with internal double-quote characters doubled.
  12985. */
  12986. static void shellIdQuote(
  12987. sqlite3_context *context,
  12988. int argc,
  12989. sqlite3_value **argv
  12990. ){
  12991. const char *zName = (const char*)sqlite3_value_text(argv[0]);
  12992. UNUSED_PARAMETER(argc);
  12993. if( zName ){
  12994. char *z = sqlite3_mprintf("\"%w\"", zName);
  12995. sqlite3_result_text(context, z, -1, sqlite3_free);
  12996. }
  12997. }
  12998. /*
  12999. ** Scalar function "shell_escape_crnl" used by the .recover command.
  13000. ** The argument passed to this function is the output of built-in
  13001. ** function quote(). If the first character of the input is "'",
  13002. ** indicating that the value passed to quote() was a text value,
  13003. ** then this function searches the input for "\n" and "\r" characters
  13004. ** and adds a wrapper similar to the following:
  13005. **
  13006. ** replace(replace(<input>, '\n', char(10), '\r', char(13));
  13007. **
  13008. ** Or, if the first character of the input is not "'", then a copy
  13009. ** of the input is returned.
  13010. */
  13011. static void shellEscapeCrnl(
  13012. sqlite3_context *context,
  13013. int argc,
  13014. sqlite3_value **argv
  13015. ){
  13016. const char *zText = (const char*)sqlite3_value_text(argv[0]);
  13017. UNUSED_PARAMETER(argc);
  13018. if( zText[0]=='\'' ){
  13019. int nText = sqlite3_value_bytes(argv[0]);
  13020. int i;
  13021. char zBuf1[20];
  13022. char zBuf2[20];
  13023. const char *zNL = 0;
  13024. const char *zCR = 0;
  13025. int nCR = 0;
  13026. int nNL = 0;
  13027. for(i=0; zText[i]; i++){
  13028. if( zNL==0 && zText[i]=='\n' ){
  13029. zNL = unused_string(zText, "\\n", "\\012", zBuf1);
  13030. nNL = (int)strlen(zNL);
  13031. }
  13032. if( zCR==0 && zText[i]=='\r' ){
  13033. zCR = unused_string(zText, "\\r", "\\015", zBuf2);
  13034. nCR = (int)strlen(zCR);
  13035. }
  13036. }
  13037. if( zNL || zCR ){
  13038. int iOut = 0;
  13039. i64 nMax = (nNL > nCR) ? nNL : nCR;
  13040. i64 nAlloc = nMax * nText + (nMax+64)*2;
  13041. char *zOut = (char*)sqlite3_malloc64(nAlloc);
  13042. if( zOut==0 ){
  13043. sqlite3_result_error_nomem(context);
  13044. return;
  13045. }
  13046. if( zNL && zCR ){
  13047. memcpy(&zOut[iOut], "replace(replace(", 16);
  13048. iOut += 16;
  13049. }else{
  13050. memcpy(&zOut[iOut], "replace(", 8);
  13051. iOut += 8;
  13052. }
  13053. for(i=0; zText[i]; i++){
  13054. if( zText[i]=='\n' ){
  13055. memcpy(&zOut[iOut], zNL, nNL);
  13056. iOut += nNL;
  13057. }else if( zText[i]=='\r' ){
  13058. memcpy(&zOut[iOut], zCR, nCR);
  13059. iOut += nCR;
  13060. }else{
  13061. zOut[iOut] = zText[i];
  13062. iOut++;
  13063. }
  13064. }
  13065. if( zNL ){
  13066. memcpy(&zOut[iOut], ",'", 2); iOut += 2;
  13067. memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
  13068. memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
  13069. }
  13070. if( zCR ){
  13071. memcpy(&zOut[iOut], ",'", 2); iOut += 2;
  13072. memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
  13073. memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
  13074. }
  13075. sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
  13076. sqlite3_free(zOut);
  13077. return;
  13078. }
  13079. }
  13080. sqlite3_result_value(context, argv[0]);
  13081. }
  13082. /* Flags for open_db().
  13083. **
  13084. ** The default behavior of open_db() is to exit(1) if the database fails to
  13085. ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
  13086. ** but still returns without calling exit.
  13087. **
  13088. ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
  13089. ** ZIP archive if the file does not exist or is empty and its name matches
  13090. ** the *.zip pattern.
  13091. */
  13092. #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
  13093. #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
  13094. /*
  13095. ** Make sure the database is open. If it is not, then open it. If
  13096. ** the database fails to open, print an error message and exit.
  13097. */
  13098. static void open_db(ShellState *p, int openFlags){
  13099. if( p->db==0 ){
  13100. if( p->openMode==SHELL_OPEN_UNSPEC ){
  13101. if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
  13102. p->openMode = SHELL_OPEN_NORMAL;
  13103. }else{
  13104. p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
  13105. (openFlags & OPEN_DB_ZIPFILE)!=0);
  13106. }
  13107. }
  13108. switch( p->openMode ){
  13109. case SHELL_OPEN_APPENDVFS: {
  13110. sqlite3_open_v2(p->zDbFilename, &p->db,
  13111. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
  13112. break;
  13113. }
  13114. case SHELL_OPEN_HEXDB:
  13115. case SHELL_OPEN_DESERIALIZE: {
  13116. sqlite3_open(0, &p->db);
  13117. break;
  13118. }
  13119. case SHELL_OPEN_ZIPFILE: {
  13120. sqlite3_open(":memory:", &p->db);
  13121. break;
  13122. }
  13123. case SHELL_OPEN_READONLY: {
  13124. sqlite3_open_v2(p->zDbFilename, &p->db,
  13125. SQLITE_OPEN_READONLY|p->openFlags, 0);
  13126. break;
  13127. }
  13128. case SHELL_OPEN_UNSPEC:
  13129. case SHELL_OPEN_NORMAL: {
  13130. sqlite3_open_v2(p->zDbFilename, &p->db,
  13131. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
  13132. break;
  13133. }
  13134. }
  13135. globalDb = p->db;
  13136. if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
  13137. utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
  13138. p->zDbFilename, sqlite3_errmsg(p->db));
  13139. if( openFlags & OPEN_DB_KEEPALIVE ){
  13140. sqlite3_open(":memory:", &p->db);
  13141. return;
  13142. }
  13143. exit(1);
  13144. }
  13145. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  13146. sqlite3_enable_load_extension(p->db, 1);
  13147. #endif
  13148. sqlite3_fileio_init(p->db, 0, 0);
  13149. sqlite3_shathree_init(p->db, 0, 0);
  13150. sqlite3_completion_init(p->db, 0, 0);
  13151. sqlite3_uint_init(p->db, 0, 0);
  13152. sqlite3_decimal_init(p->db, 0, 0);
  13153. sqlite3_ieee_init(p->db, 0, 0);
  13154. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
  13155. sqlite3_dbdata_init(p->db, 0, 0);
  13156. #endif
  13157. #ifdef SQLITE_HAVE_ZLIB
  13158. sqlite3_zipfile_init(p->db, 0, 0);
  13159. sqlite3_sqlar_init(p->db, 0, 0);
  13160. #endif
  13161. sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
  13162. shellAddSchemaName, 0, 0);
  13163. sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
  13164. shellModuleSchema, 0, 0);
  13165. sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
  13166. shellPutsFunc, 0, 0);
  13167. sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
  13168. shellEscapeCrnl, 0, 0);
  13169. sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
  13170. shellInt32, 0, 0);
  13171. sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
  13172. shellIdQuote, 0, 0);
  13173. #ifndef SQLITE_NOHAVE_SYSTEM
  13174. sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
  13175. editFunc, 0, 0);
  13176. sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
  13177. editFunc, 0, 0);
  13178. #endif
  13179. if( p->openMode==SHELL_OPEN_ZIPFILE ){
  13180. char *zSql = sqlite3_mprintf(
  13181. "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
  13182. sqlite3_exec(p->db, zSql, 0, 0, 0);
  13183. sqlite3_free(zSql);
  13184. }
  13185. #ifdef SQLITE_ENABLE_DESERIALIZE
  13186. else
  13187. if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
  13188. int rc;
  13189. int nData = 0;
  13190. unsigned char *aData;
  13191. if( p->openMode==SHELL_OPEN_DESERIALIZE ){
  13192. aData = (unsigned char*)readFile(p->zDbFilename, &nData);
  13193. }else{
  13194. aData = readHexDb(p, &nData);
  13195. if( aData==0 ){
  13196. return;
  13197. }
  13198. }
  13199. rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
  13200. SQLITE_DESERIALIZE_RESIZEABLE |
  13201. SQLITE_DESERIALIZE_FREEONCLOSE);
  13202. if( rc ){
  13203. utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
  13204. }
  13205. if( p->szMax>0 ){
  13206. sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
  13207. }
  13208. }
  13209. #endif
  13210. }
  13211. }
  13212. /*
  13213. ** Attempt to close the databaes connection. Report errors.
  13214. */
  13215. void close_db(sqlite3 *db){
  13216. int rc = sqlite3_close(db);
  13217. if( rc ){
  13218. utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
  13219. rc, sqlite3_errmsg(db));
  13220. }
  13221. }
  13222. #if HAVE_READLINE || HAVE_EDITLINE
  13223. /*
  13224. ** Readline completion callbacks
  13225. */
  13226. static char *readline_completion_generator(const char *text, int state){
  13227. static sqlite3_stmt *pStmt = 0;
  13228. char *zRet;
  13229. if( state==0 ){
  13230. char *zSql;
  13231. sqlite3_finalize(pStmt);
  13232. zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
  13233. " FROM completion(%Q) ORDER BY 1", text);
  13234. sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
  13235. sqlite3_free(zSql);
  13236. }
  13237. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  13238. zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
  13239. }else{
  13240. sqlite3_finalize(pStmt);
  13241. pStmt = 0;
  13242. zRet = 0;
  13243. }
  13244. return zRet;
  13245. }
  13246. static char **readline_completion(const char *zText, int iStart, int iEnd){
  13247. rl_attempted_completion_over = 1;
  13248. return rl_completion_matches(zText, readline_completion_generator);
  13249. }
  13250. #elif HAVE_LINENOISE
  13251. /*
  13252. ** Linenoise completion callback
  13253. */
  13254. static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
  13255. int nLine = strlen30(zLine);
  13256. int i, iStart;
  13257. sqlite3_stmt *pStmt = 0;
  13258. char *zSql;
  13259. char zBuf[1000];
  13260. if( nLine>sizeof(zBuf)-30 ) return;
  13261. if( zLine[0]=='.' || zLine[0]=='#') return;
  13262. for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
  13263. if( i==nLine-1 ) return;
  13264. iStart = i+1;
  13265. memcpy(zBuf, zLine, iStart);
  13266. zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
  13267. " FROM completion(%Q,%Q) ORDER BY 1",
  13268. &zLine[iStart], zLine);
  13269. sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
  13270. sqlite3_free(zSql);
  13271. sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
  13272. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  13273. const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
  13274. int nCompletion = sqlite3_column_bytes(pStmt, 0);
  13275. if( iStart+nCompletion < sizeof(zBuf)-1 ){
  13276. memcpy(zBuf+iStart, zCompletion, nCompletion+1);
  13277. linenoiseAddCompletion(lc, zBuf);
  13278. }
  13279. }
  13280. sqlite3_finalize(pStmt);
  13281. }
  13282. #endif
  13283. /*
  13284. ** Do C-language style dequoting.
  13285. **
  13286. ** \a -> alarm
  13287. ** \b -> backspace
  13288. ** \t -> tab
  13289. ** \n -> newline
  13290. ** \v -> vertical tab
  13291. ** \f -> form feed
  13292. ** \r -> carriage return
  13293. ** \s -> space
  13294. ** \" -> "
  13295. ** \' -> '
  13296. ** \\ -> backslash
  13297. ** \NNN -> ascii character NNN in octal
  13298. */
  13299. static void resolve_backslashes(char *z){
  13300. int i, j;
  13301. char c;
  13302. while( *z && *z!='\\' ) z++;
  13303. for(i=j=0; (c = z[i])!=0; i++, j++){
  13304. if( c=='\\' && z[i+1]!=0 ){
  13305. c = z[++i];
  13306. if( c=='a' ){
  13307. c = '\a';
  13308. }else if( c=='b' ){
  13309. c = '\b';
  13310. }else if( c=='t' ){
  13311. c = '\t';
  13312. }else if( c=='n' ){
  13313. c = '\n';
  13314. }else if( c=='v' ){
  13315. c = '\v';
  13316. }else if( c=='f' ){
  13317. c = '\f';
  13318. }else if( c=='r' ){
  13319. c = '\r';
  13320. }else if( c=='"' ){
  13321. c = '"';
  13322. }else if( c=='\'' ){
  13323. c = '\'';
  13324. }else if( c=='\\' ){
  13325. c = '\\';
  13326. }else if( c>='0' && c<='7' ){
  13327. c -= '0';
  13328. if( z[i+1]>='0' && z[i+1]<='7' ){
  13329. i++;
  13330. c = (c<<3) + z[i] - '0';
  13331. if( z[i+1]>='0' && z[i+1]<='7' ){
  13332. i++;
  13333. c = (c<<3) + z[i] - '0';
  13334. }
  13335. }
  13336. }
  13337. }
  13338. z[j] = c;
  13339. }
  13340. if( j<i ) z[j] = 0;
  13341. }
  13342. /*
  13343. ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
  13344. ** for TRUE and FALSE. Return the integer value if appropriate.
  13345. */
  13346. static int booleanValue(const char *zArg){
  13347. int i;
  13348. if( zArg[0]=='0' && zArg[1]=='x' ){
  13349. for(i=2; hexDigitValue(zArg[i])>=0; i++){}
  13350. }else{
  13351. for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
  13352. }
  13353. if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
  13354. if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
  13355. return 1;
  13356. }
  13357. if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
  13358. return 0;
  13359. }
  13360. utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
  13361. zArg);
  13362. return 0;
  13363. }
  13364. /*
  13365. ** Set or clear a shell flag according to a boolean value.
  13366. */
  13367. static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
  13368. if( booleanValue(zArg) ){
  13369. ShellSetFlag(p, mFlag);
  13370. }else{
  13371. ShellClearFlag(p, mFlag);
  13372. }
  13373. }
  13374. /*
  13375. ** Close an output file, assuming it is not stderr or stdout
  13376. */
  13377. static void output_file_close(FILE *f){
  13378. if( f && f!=stdout && f!=stderr ) fclose(f);
  13379. }
  13380. /*
  13381. ** Try to open an output file. The names "stdout" and "stderr" are
  13382. ** recognized and do the right thing. NULL is returned if the output
  13383. ** filename is "off".
  13384. */
  13385. static FILE *output_file_open(const char *zFile, int bTextMode){
  13386. FILE *f;
  13387. if( strcmp(zFile,"stdout")==0 ){
  13388. f = stdout;
  13389. }else if( strcmp(zFile, "stderr")==0 ){
  13390. f = stderr;
  13391. }else if( strcmp(zFile, "off")==0 ){
  13392. f = 0;
  13393. }else{
  13394. f = fopen(zFile, bTextMode ? "w" : "wb");
  13395. if( f==0 ){
  13396. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  13397. }
  13398. }
  13399. return f;
  13400. }
  13401. #ifndef SQLITE_OMIT_TRACE
  13402. /*
  13403. ** A routine for handling output from sqlite3_trace().
  13404. */
  13405. static int sql_trace_callback(
  13406. unsigned mType, /* The trace type */
  13407. void *pArg, /* The ShellState pointer */
  13408. void *pP, /* Usually a pointer to sqlite_stmt */
  13409. void *pX /* Auxiliary output */
  13410. ){
  13411. ShellState *p = (ShellState*)pArg;
  13412. sqlite3_stmt *pStmt;
  13413. const char *zSql;
  13414. int nSql;
  13415. if( p->traceOut==0 ) return 0;
  13416. if( mType==SQLITE_TRACE_CLOSE ){
  13417. utf8_printf(p->traceOut, "-- closing database connection\n");
  13418. return 0;
  13419. }
  13420. if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
  13421. zSql = (const char*)pX;
  13422. }else{
  13423. pStmt = (sqlite3_stmt*)pP;
  13424. switch( p->eTraceType ){
  13425. case SHELL_TRACE_EXPANDED: {
  13426. zSql = sqlite3_expanded_sql(pStmt);
  13427. break;
  13428. }
  13429. #ifdef SQLITE_ENABLE_NORMALIZE
  13430. case SHELL_TRACE_NORMALIZED: {
  13431. zSql = sqlite3_normalized_sql(pStmt);
  13432. break;
  13433. }
  13434. #endif
  13435. default: {
  13436. zSql = sqlite3_sql(pStmt);
  13437. break;
  13438. }
  13439. }
  13440. }
  13441. if( zSql==0 ) return 0;
  13442. nSql = strlen30(zSql);
  13443. while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
  13444. switch( mType ){
  13445. case SQLITE_TRACE_ROW:
  13446. case SQLITE_TRACE_STMT: {
  13447. utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
  13448. break;
  13449. }
  13450. case SQLITE_TRACE_PROFILE: {
  13451. sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
  13452. utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
  13453. break;
  13454. }
  13455. }
  13456. return 0;
  13457. }
  13458. #endif
  13459. /*
  13460. ** A no-op routine that runs with the ".breakpoint" doc-command. This is
  13461. ** a useful spot to set a debugger breakpoint.
  13462. */
  13463. static void test_breakpoint(void){
  13464. static int nCall = 0;
  13465. nCall++;
  13466. }
  13467. /*
  13468. ** An object used to read a CSV and other files for import.
  13469. */
  13470. typedef struct ImportCtx ImportCtx;
  13471. struct ImportCtx {
  13472. const char *zFile; /* Name of the input file */
  13473. FILE *in; /* Read the CSV text from this input stream */
  13474. int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */
  13475. char *z; /* Accumulated text for a field */
  13476. int n; /* Number of bytes in z */
  13477. int nAlloc; /* Space allocated for z[] */
  13478. int nLine; /* Current line number */
  13479. int nRow; /* Number of rows imported */
  13480. int nErr; /* Number of errors encountered */
  13481. int bNotFirst; /* True if one or more bytes already read */
  13482. int cTerm; /* Character that terminated the most recent field */
  13483. int cColSep; /* The column separator character. (Usually ",") */
  13484. int cRowSep; /* The row separator character. (Usually "\n") */
  13485. };
  13486. /* Clean up resourced used by an ImportCtx */
  13487. static void import_cleanup(ImportCtx *p){
  13488. if( p->in!=0 && p->xCloser!=0 ){
  13489. p->xCloser(p->in);
  13490. p->in = 0;
  13491. }
  13492. sqlite3_free(p->z);
  13493. p->z = 0;
  13494. }
  13495. /* Append a single byte to z[] */
  13496. static void import_append_char(ImportCtx *p, int c){
  13497. if( p->n+1>=p->nAlloc ){
  13498. p->nAlloc += p->nAlloc + 100;
  13499. p->z = sqlite3_realloc64(p->z, p->nAlloc);
  13500. if( p->z==0 ) shell_out_of_memory();
  13501. }
  13502. p->z[p->n++] = (char)c;
  13503. }
  13504. /* Read a single field of CSV text. Compatible with rfc4180 and extended
  13505. ** with the option of having a separator other than ",".
  13506. **
  13507. ** + Input comes from p->in.
  13508. ** + Store results in p->z of length p->n. Space to hold p->z comes
  13509. ** from sqlite3_malloc64().
  13510. ** + Use p->cSep as the column separator. The default is ",".
  13511. ** + Use p->rSep as the row separator. The default is "\n".
  13512. ** + Keep track of the line number in p->nLine.
  13513. ** + Store the character that terminates the field in p->cTerm. Store
  13514. ** EOF on end-of-file.
  13515. ** + Report syntax errors on stderr
  13516. */
  13517. static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
  13518. int c;
  13519. int cSep = p->cColSep;
  13520. int rSep = p->cRowSep;
  13521. p->n = 0;
  13522. c = fgetc(p->in);
  13523. if( c==EOF || seenInterrupt ){
  13524. p->cTerm = EOF;
  13525. return 0;
  13526. }
  13527. if( c=='"' ){
  13528. int pc, ppc;
  13529. int startLine = p->nLine;
  13530. int cQuote = c;
  13531. pc = ppc = 0;
  13532. while( 1 ){
  13533. c = fgetc(p->in);
  13534. if( c==rSep ) p->nLine++;
  13535. if( c==cQuote ){
  13536. if( pc==cQuote ){
  13537. pc = 0;
  13538. continue;
  13539. }
  13540. }
  13541. if( (c==cSep && pc==cQuote)
  13542. || (c==rSep && pc==cQuote)
  13543. || (c==rSep && pc=='\r' && ppc==cQuote)
  13544. || (c==EOF && pc==cQuote)
  13545. ){
  13546. do{ p->n--; }while( p->z[p->n]!=cQuote );
  13547. p->cTerm = c;
  13548. break;
  13549. }
  13550. if( pc==cQuote && c!='\r' ){
  13551. utf8_printf(stderr, "%s:%d: unescaped %c character\n",
  13552. p->zFile, p->nLine, cQuote);
  13553. }
  13554. if( c==EOF ){
  13555. utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
  13556. p->zFile, startLine, cQuote);
  13557. p->cTerm = c;
  13558. break;
  13559. }
  13560. import_append_char(p, c);
  13561. ppc = pc;
  13562. pc = c;
  13563. }
  13564. }else{
  13565. /* If this is the first field being parsed and it begins with the
  13566. ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
  13567. if( (c&0xff)==0xef && p->bNotFirst==0 ){
  13568. import_append_char(p, c);
  13569. c = fgetc(p->in);
  13570. if( (c&0xff)==0xbb ){
  13571. import_append_char(p, c);
  13572. c = fgetc(p->in);
  13573. if( (c&0xff)==0xbf ){
  13574. p->bNotFirst = 1;
  13575. p->n = 0;
  13576. return csv_read_one_field(p);
  13577. }
  13578. }
  13579. }
  13580. while( c!=EOF && c!=cSep && c!=rSep ){
  13581. import_append_char(p, c);
  13582. c = fgetc(p->in);
  13583. }
  13584. if( c==rSep ){
  13585. p->nLine++;
  13586. if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
  13587. }
  13588. p->cTerm = c;
  13589. }
  13590. if( p->z ) p->z[p->n] = 0;
  13591. p->bNotFirst = 1;
  13592. return p->z;
  13593. }
  13594. /* Read a single field of ASCII delimited text.
  13595. **
  13596. ** + Input comes from p->in.
  13597. ** + Store results in p->z of length p->n. Space to hold p->z comes
  13598. ** from sqlite3_malloc64().
  13599. ** + Use p->cSep as the column separator. The default is "\x1F".
  13600. ** + Use p->rSep as the row separator. The default is "\x1E".
  13601. ** + Keep track of the row number in p->nLine.
  13602. ** + Store the character that terminates the field in p->cTerm. Store
  13603. ** EOF on end-of-file.
  13604. ** + Report syntax errors on stderr
  13605. */
  13606. static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
  13607. int c;
  13608. int cSep = p->cColSep;
  13609. int rSep = p->cRowSep;
  13610. p->n = 0;
  13611. c = fgetc(p->in);
  13612. if( c==EOF || seenInterrupt ){
  13613. p->cTerm = EOF;
  13614. return 0;
  13615. }
  13616. while( c!=EOF && c!=cSep && c!=rSep ){
  13617. import_append_char(p, c);
  13618. c = fgetc(p->in);
  13619. }
  13620. if( c==rSep ){
  13621. p->nLine++;
  13622. }
  13623. p->cTerm = c;
  13624. if( p->z ) p->z[p->n] = 0;
  13625. return p->z;
  13626. }
  13627. /*
  13628. ** Try to transfer data for table zTable. If an error is seen while
  13629. ** moving forward, try to go backwards. The backwards movement won't
  13630. ** work for WITHOUT ROWID tables.
  13631. */
  13632. static void tryToCloneData(
  13633. ShellState *p,
  13634. sqlite3 *newDb,
  13635. const char *zTable
  13636. ){
  13637. sqlite3_stmt *pQuery = 0;
  13638. sqlite3_stmt *pInsert = 0;
  13639. char *zQuery = 0;
  13640. char *zInsert = 0;
  13641. int rc;
  13642. int i, j, n;
  13643. int nTable = strlen30(zTable);
  13644. int k = 0;
  13645. int cnt = 0;
  13646. const int spinRate = 10000;
  13647. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
  13648. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  13649. if( rc ){
  13650. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  13651. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  13652. zQuery);
  13653. goto end_data_xfer;
  13654. }
  13655. n = sqlite3_column_count(pQuery);
  13656. zInsert = sqlite3_malloc64(200 + nTable + n*3);
  13657. if( zInsert==0 ) shell_out_of_memory();
  13658. sqlite3_snprintf(200+nTable,zInsert,
  13659. "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
  13660. i = strlen30(zInsert);
  13661. for(j=1; j<n; j++){
  13662. memcpy(zInsert+i, ",?", 2);
  13663. i += 2;
  13664. }
  13665. memcpy(zInsert+i, ");", 3);
  13666. rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
  13667. if( rc ){
  13668. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  13669. sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
  13670. zQuery);
  13671. goto end_data_xfer;
  13672. }
  13673. for(k=0; k<2; k++){
  13674. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  13675. for(i=0; i<n; i++){
  13676. switch( sqlite3_column_type(pQuery, i) ){
  13677. case SQLITE_NULL: {
  13678. sqlite3_bind_null(pInsert, i+1);
  13679. break;
  13680. }
  13681. case SQLITE_INTEGER: {
  13682. sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
  13683. break;
  13684. }
  13685. case SQLITE_FLOAT: {
  13686. sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
  13687. break;
  13688. }
  13689. case SQLITE_TEXT: {
  13690. sqlite3_bind_text(pInsert, i+1,
  13691. (const char*)sqlite3_column_text(pQuery,i),
  13692. -1, SQLITE_STATIC);
  13693. break;
  13694. }
  13695. case SQLITE_BLOB: {
  13696. sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
  13697. sqlite3_column_bytes(pQuery,i),
  13698. SQLITE_STATIC);
  13699. break;
  13700. }
  13701. }
  13702. } /* End for */
  13703. rc = sqlite3_step(pInsert);
  13704. if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  13705. utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
  13706. sqlite3_errmsg(newDb));
  13707. }
  13708. sqlite3_reset(pInsert);
  13709. cnt++;
  13710. if( (cnt%spinRate)==0 ){
  13711. printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
  13712. fflush(stdout);
  13713. }
  13714. } /* End while */
  13715. if( rc==SQLITE_DONE ) break;
  13716. sqlite3_finalize(pQuery);
  13717. sqlite3_free(zQuery);
  13718. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
  13719. zTable);
  13720. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  13721. if( rc ){
  13722. utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
  13723. break;
  13724. }
  13725. } /* End for(k=0...) */
  13726. end_data_xfer:
  13727. sqlite3_finalize(pQuery);
  13728. sqlite3_finalize(pInsert);
  13729. sqlite3_free(zQuery);
  13730. sqlite3_free(zInsert);
  13731. }
  13732. /*
  13733. ** Try to transfer all rows of the schema that match zWhere. For
  13734. ** each row, invoke xForEach() on the object defined by that row.
  13735. ** If an error is encountered while moving forward through the
  13736. ** sqlite_schema table, try again moving backwards.
  13737. */
  13738. static void tryToCloneSchema(
  13739. ShellState *p,
  13740. sqlite3 *newDb,
  13741. const char *zWhere,
  13742. void (*xForEach)(ShellState*,sqlite3*,const char*)
  13743. ){
  13744. sqlite3_stmt *pQuery = 0;
  13745. char *zQuery = 0;
  13746. int rc;
  13747. const unsigned char *zName;
  13748. const unsigned char *zSql;
  13749. char *zErrMsg = 0;
  13750. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
  13751. " WHERE %s", zWhere);
  13752. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  13753. if( rc ){
  13754. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  13755. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  13756. zQuery);
  13757. goto end_schema_xfer;
  13758. }
  13759. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  13760. zName = sqlite3_column_text(pQuery, 0);
  13761. zSql = sqlite3_column_text(pQuery, 1);
  13762. printf("%s... ", zName); fflush(stdout);
  13763. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  13764. if( zErrMsg ){
  13765. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  13766. sqlite3_free(zErrMsg);
  13767. zErrMsg = 0;
  13768. }
  13769. if( xForEach ){
  13770. xForEach(p, newDb, (const char*)zName);
  13771. }
  13772. printf("done\n");
  13773. }
  13774. if( rc!=SQLITE_DONE ){
  13775. sqlite3_finalize(pQuery);
  13776. sqlite3_free(zQuery);
  13777. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
  13778. " WHERE %s ORDER BY rowid DESC", zWhere);
  13779. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  13780. if( rc ){
  13781. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  13782. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  13783. zQuery);
  13784. goto end_schema_xfer;
  13785. }
  13786. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  13787. zName = sqlite3_column_text(pQuery, 0);
  13788. zSql = sqlite3_column_text(pQuery, 1);
  13789. printf("%s... ", zName); fflush(stdout);
  13790. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  13791. if( zErrMsg ){
  13792. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  13793. sqlite3_free(zErrMsg);
  13794. zErrMsg = 0;
  13795. }
  13796. if( xForEach ){
  13797. xForEach(p, newDb, (const char*)zName);
  13798. }
  13799. printf("done\n");
  13800. }
  13801. }
  13802. end_schema_xfer:
  13803. sqlite3_finalize(pQuery);
  13804. sqlite3_free(zQuery);
  13805. }
  13806. /*
  13807. ** Open a new database file named "zNewDb". Try to recover as much information
  13808. ** as possible out of the main database (which might be corrupt) and write it
  13809. ** into zNewDb.
  13810. */
  13811. static void tryToClone(ShellState *p, const char *zNewDb){
  13812. int rc;
  13813. sqlite3 *newDb = 0;
  13814. if( access(zNewDb,0)==0 ){
  13815. utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
  13816. return;
  13817. }
  13818. rc = sqlite3_open(zNewDb, &newDb);
  13819. if( rc ){
  13820. utf8_printf(stderr, "Cannot create output database: %s\n",
  13821. sqlite3_errmsg(newDb));
  13822. }else{
  13823. sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
  13824. sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
  13825. tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
  13826. tryToCloneSchema(p, newDb, "type!='table'", 0);
  13827. sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
  13828. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  13829. }
  13830. close_db(newDb);
  13831. }
  13832. /*
  13833. ** Change the output file back to stdout.
  13834. **
  13835. ** If the p->doXdgOpen flag is set, that means the output was being
  13836. ** redirected to a temporary file named by p->zTempFile. In that case,
  13837. ** launch start/open/xdg-open on that temporary file.
  13838. */
  13839. static void output_reset(ShellState *p){
  13840. if( p->outfile[0]=='|' ){
  13841. #ifndef SQLITE_OMIT_POPEN
  13842. pclose(p->out);
  13843. #endif
  13844. }else{
  13845. output_file_close(p->out);
  13846. #ifndef SQLITE_NOHAVE_SYSTEM
  13847. if( p->doXdgOpen ){
  13848. const char *zXdgOpenCmd =
  13849. #if defined(_WIN32)
  13850. "start";
  13851. #elif defined(__APPLE__)
  13852. "open";
  13853. #else
  13854. "xdg-open";
  13855. #endif
  13856. char *zCmd;
  13857. zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
  13858. if( system(zCmd) ){
  13859. utf8_printf(stderr, "Failed: [%s]\n", zCmd);
  13860. }else{
  13861. /* Give the start/open/xdg-open command some time to get
  13862. ** going before we continue, and potential delete the
  13863. ** p->zTempFile data file out from under it */
  13864. sqlite3_sleep(2000);
  13865. }
  13866. sqlite3_free(zCmd);
  13867. outputModePop(p);
  13868. p->doXdgOpen = 0;
  13869. }
  13870. #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
  13871. }
  13872. p->outfile[0] = 0;
  13873. p->out = stdout;
  13874. }
  13875. /*
  13876. ** Run an SQL command and return the single integer result.
  13877. */
  13878. static int db_int(ShellState *p, const char *zSql){
  13879. sqlite3_stmt *pStmt;
  13880. int res = 0;
  13881. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  13882. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  13883. res = sqlite3_column_int(pStmt,0);
  13884. }
  13885. sqlite3_finalize(pStmt);
  13886. return res;
  13887. }
  13888. /*
  13889. ** Convert a 2-byte or 4-byte big-endian integer into a native integer
  13890. */
  13891. static unsigned int get2byteInt(unsigned char *a){
  13892. return (a[0]<<8) + a[1];
  13893. }
  13894. static unsigned int get4byteInt(unsigned char *a){
  13895. return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
  13896. }
  13897. /*
  13898. ** Implementation of the ".dbinfo" command.
  13899. **
  13900. ** Return 1 on error, 2 to exit, and 0 otherwise.
  13901. */
  13902. static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
  13903. static const struct { const char *zName; int ofst; } aField[] = {
  13904. { "file change counter:", 24 },
  13905. { "database page count:", 28 },
  13906. { "freelist page count:", 36 },
  13907. { "schema cookie:", 40 },
  13908. { "schema format:", 44 },
  13909. { "default cache size:", 48 },
  13910. { "autovacuum top root:", 52 },
  13911. { "incremental vacuum:", 64 },
  13912. { "text encoding:", 56 },
  13913. { "user version:", 60 },
  13914. { "application id:", 68 },
  13915. { "software version:", 96 },
  13916. };
  13917. static const struct { const char *zName; const char *zSql; } aQuery[] = {
  13918. { "number of tables:",
  13919. "SELECT count(*) FROM %s WHERE type='table'" },
  13920. { "number of indexes:",
  13921. "SELECT count(*) FROM %s WHERE type='index'" },
  13922. { "number of triggers:",
  13923. "SELECT count(*) FROM %s WHERE type='trigger'" },
  13924. { "number of views:",
  13925. "SELECT count(*) FROM %s WHERE type='view'" },
  13926. { "schema size:",
  13927. "SELECT total(length(sql)) FROM %s" },
  13928. };
  13929. int i, rc;
  13930. unsigned iDataVersion;
  13931. char *zSchemaTab;
  13932. char *zDb = nArg>=2 ? azArg[1] : "main";
  13933. sqlite3_stmt *pStmt = 0;
  13934. unsigned char aHdr[100];
  13935. open_db(p, 0);
  13936. if( p->db==0 ) return 1;
  13937. rc = sqlite3_prepare_v2(p->db,
  13938. "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
  13939. -1, &pStmt, 0);
  13940. if( rc ){
  13941. utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
  13942. sqlite3_finalize(pStmt);
  13943. return 1;
  13944. }
  13945. sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
  13946. if( sqlite3_step(pStmt)==SQLITE_ROW
  13947. && sqlite3_column_bytes(pStmt,0)>100
  13948. ){
  13949. memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
  13950. sqlite3_finalize(pStmt);
  13951. }else{
  13952. raw_printf(stderr, "unable to read database header\n");
  13953. sqlite3_finalize(pStmt);
  13954. return 1;
  13955. }
  13956. i = get2byteInt(aHdr+16);
  13957. if( i==1 ) i = 65536;
  13958. utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
  13959. utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
  13960. utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
  13961. utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
  13962. for(i=0; i<ArraySize(aField); i++){
  13963. int ofst = aField[i].ofst;
  13964. unsigned int val = get4byteInt(aHdr + ofst);
  13965. utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
  13966. switch( ofst ){
  13967. case 56: {
  13968. if( val==1 ) raw_printf(p->out, " (utf8)");
  13969. if( val==2 ) raw_printf(p->out, " (utf16le)");
  13970. if( val==3 ) raw_printf(p->out, " (utf16be)");
  13971. }
  13972. }
  13973. raw_printf(p->out, "\n");
  13974. }
  13975. if( zDb==0 ){
  13976. zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
  13977. }else if( strcmp(zDb,"temp")==0 ){
  13978. zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
  13979. }else{
  13980. zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
  13981. }
  13982. for(i=0; i<ArraySize(aQuery); i++){
  13983. char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
  13984. int val = db_int(p, zSql);
  13985. sqlite3_free(zSql);
  13986. utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
  13987. }
  13988. sqlite3_free(zSchemaTab);
  13989. sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
  13990. utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
  13991. return 0;
  13992. }
  13993. /*
  13994. ** Print the current sqlite3_errmsg() value to stderr and return 1.
  13995. */
  13996. static int shellDatabaseError(sqlite3 *db){
  13997. const char *zErr = sqlite3_errmsg(db);
  13998. utf8_printf(stderr, "Error: %s\n", zErr);
  13999. return 1;
  14000. }
  14001. /*
  14002. ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
  14003. ** if they match and FALSE (0) if they do not match.
  14004. **
  14005. ** Globbing rules:
  14006. **
  14007. ** '*' Matches any sequence of zero or more characters.
  14008. **
  14009. ** '?' Matches exactly one character.
  14010. **
  14011. ** [...] Matches one character from the enclosed list of
  14012. ** characters.
  14013. **
  14014. ** [^...] Matches one character not in the enclosed list.
  14015. **
  14016. ** '#' Matches any sequence of one or more digits with an
  14017. ** optional + or - sign in front
  14018. **
  14019. ** ' ' Any span of whitespace matches any other span of
  14020. ** whitespace.
  14021. **
  14022. ** Extra whitespace at the end of z[] is ignored.
  14023. */
  14024. static int testcase_glob(const char *zGlob, const char *z){
  14025. int c, c2;
  14026. int invert;
  14027. int seen;
  14028. while( (c = (*(zGlob++)))!=0 ){
  14029. if( IsSpace(c) ){
  14030. if( !IsSpace(*z) ) return 0;
  14031. while( IsSpace(*zGlob) ) zGlob++;
  14032. while( IsSpace(*z) ) z++;
  14033. }else if( c=='*' ){
  14034. while( (c=(*(zGlob++))) == '*' || c=='?' ){
  14035. if( c=='?' && (*(z++))==0 ) return 0;
  14036. }
  14037. if( c==0 ){
  14038. return 1;
  14039. }else if( c=='[' ){
  14040. while( *z && testcase_glob(zGlob-1,z)==0 ){
  14041. z++;
  14042. }
  14043. return (*z)!=0;
  14044. }
  14045. while( (c2 = (*(z++)))!=0 ){
  14046. while( c2!=c ){
  14047. c2 = *(z++);
  14048. if( c2==0 ) return 0;
  14049. }
  14050. if( testcase_glob(zGlob,z) ) return 1;
  14051. }
  14052. return 0;
  14053. }else if( c=='?' ){
  14054. if( (*(z++))==0 ) return 0;
  14055. }else if( c=='[' ){
  14056. int prior_c = 0;
  14057. seen = 0;
  14058. invert = 0;
  14059. c = *(z++);
  14060. if( c==0 ) return 0;
  14061. c2 = *(zGlob++);
  14062. if( c2=='^' ){
  14063. invert = 1;
  14064. c2 = *(zGlob++);
  14065. }
  14066. if( c2==']' ){
  14067. if( c==']' ) seen = 1;
  14068. c2 = *(zGlob++);
  14069. }
  14070. while( c2 && c2!=']' ){
  14071. if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
  14072. c2 = *(zGlob++);
  14073. if( c>=prior_c && c<=c2 ) seen = 1;
  14074. prior_c = 0;
  14075. }else{
  14076. if( c==c2 ){
  14077. seen = 1;
  14078. }
  14079. prior_c = c2;
  14080. }
  14081. c2 = *(zGlob++);
  14082. }
  14083. if( c2==0 || (seen ^ invert)==0 ) return 0;
  14084. }else if( c=='#' ){
  14085. if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
  14086. if( !IsDigit(z[0]) ) return 0;
  14087. z++;
  14088. while( IsDigit(z[0]) ){ z++; }
  14089. }else{
  14090. if( c!=(*(z++)) ) return 0;
  14091. }
  14092. }
  14093. while( IsSpace(*z) ){ z++; }
  14094. return *z==0;
  14095. }
  14096. /*
  14097. ** Compare the string as a command-line option with either one or two
  14098. ** initial "-" characters.
  14099. */
  14100. static int optionMatch(const char *zStr, const char *zOpt){
  14101. if( zStr[0]!='-' ) return 0;
  14102. zStr++;
  14103. if( zStr[0]=='-' ) zStr++;
  14104. return strcmp(zStr, zOpt)==0;
  14105. }
  14106. /*
  14107. ** Delete a file.
  14108. */
  14109. int shellDeleteFile(const char *zFilename){
  14110. int rc;
  14111. #ifdef _WIN32
  14112. wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
  14113. rc = _wunlink(z);
  14114. sqlite3_free(z);
  14115. #else
  14116. rc = unlink(zFilename);
  14117. #endif
  14118. return rc;
  14119. }
  14120. /*
  14121. ** Try to delete the temporary file (if there is one) and free the
  14122. ** memory used to hold the name of the temp file.
  14123. */
  14124. static void clearTempFile(ShellState *p){
  14125. if( p->zTempFile==0 ) return;
  14126. if( p->doXdgOpen ) return;
  14127. if( shellDeleteFile(p->zTempFile) ) return;
  14128. sqlite3_free(p->zTempFile);
  14129. p->zTempFile = 0;
  14130. }
  14131. /*
  14132. ** Create a new temp file name with the given suffix.
  14133. */
  14134. static void newTempFile(ShellState *p, const char *zSuffix){
  14135. clearTempFile(p);
  14136. sqlite3_free(p->zTempFile);
  14137. p->zTempFile = 0;
  14138. if( p->db ){
  14139. sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
  14140. }
  14141. if( p->zTempFile==0 ){
  14142. /* If p->db is an in-memory database then the TEMPFILENAME file-control
  14143. ** will not work and we will need to fallback to guessing */
  14144. char *zTemp;
  14145. sqlite3_uint64 r;
  14146. sqlite3_randomness(sizeof(r), &r);
  14147. zTemp = getenv("TEMP");
  14148. if( zTemp==0 ) zTemp = getenv("TMP");
  14149. if( zTemp==0 ){
  14150. #ifdef _WIN32
  14151. zTemp = "\\tmp";
  14152. #else
  14153. zTemp = "/tmp";
  14154. #endif
  14155. }
  14156. p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
  14157. }else{
  14158. p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
  14159. }
  14160. if( p->zTempFile==0 ){
  14161. raw_printf(stderr, "out of memory\n");
  14162. exit(1);
  14163. }
  14164. }
  14165. /*
  14166. ** The implementation of SQL scalar function fkey_collate_clause(), used
  14167. ** by the ".lint fkey-indexes" command. This scalar function is always
  14168. ** called with four arguments - the parent table name, the parent column name,
  14169. ** the child table name and the child column name.
  14170. **
  14171. ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
  14172. **
  14173. ** If either of the named tables or columns do not exist, this function
  14174. ** returns an empty string. An empty string is also returned if both tables
  14175. ** and columns exist but have the same default collation sequence. Or,
  14176. ** if both exist but the default collation sequences are different, this
  14177. ** function returns the string " COLLATE <parent-collation>", where
  14178. ** <parent-collation> is the default collation sequence of the parent column.
  14179. */
  14180. static void shellFkeyCollateClause(
  14181. sqlite3_context *pCtx,
  14182. int nVal,
  14183. sqlite3_value **apVal
  14184. ){
  14185. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  14186. const char *zParent;
  14187. const char *zParentCol;
  14188. const char *zParentSeq;
  14189. const char *zChild;
  14190. const char *zChildCol;
  14191. const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
  14192. int rc;
  14193. assert( nVal==4 );
  14194. zParent = (const char*)sqlite3_value_text(apVal[0]);
  14195. zParentCol = (const char*)sqlite3_value_text(apVal[1]);
  14196. zChild = (const char*)sqlite3_value_text(apVal[2]);
  14197. zChildCol = (const char*)sqlite3_value_text(apVal[3]);
  14198. sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
  14199. rc = sqlite3_table_column_metadata(
  14200. db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
  14201. );
  14202. if( rc==SQLITE_OK ){
  14203. rc = sqlite3_table_column_metadata(
  14204. db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
  14205. );
  14206. }
  14207. if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
  14208. char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
  14209. sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
  14210. sqlite3_free(z);
  14211. }
  14212. }
  14213. /*
  14214. ** The implementation of dot-command ".lint fkey-indexes".
  14215. */
  14216. static int lintFkeyIndexes(
  14217. ShellState *pState, /* Current shell tool state */
  14218. char **azArg, /* Array of arguments passed to dot command */
  14219. int nArg /* Number of entries in azArg[] */
  14220. ){
  14221. sqlite3 *db = pState->db; /* Database handle to query "main" db of */
  14222. FILE *out = pState->out; /* Stream to write non-error output to */
  14223. int bVerbose = 0; /* If -verbose is present */
  14224. int bGroupByParent = 0; /* If -groupbyparent is present */
  14225. int i; /* To iterate through azArg[] */
  14226. const char *zIndent = ""; /* How much to indent CREATE INDEX by */
  14227. int rc; /* Return code */
  14228. sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
  14229. /*
  14230. ** This SELECT statement returns one row for each foreign key constraint
  14231. ** in the schema of the main database. The column values are:
  14232. **
  14233. ** 0. The text of an SQL statement similar to:
  14234. **
  14235. ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
  14236. **
  14237. ** This SELECT is similar to the one that the foreign keys implementation
  14238. ** needs to run internally on child tables. If there is an index that can
  14239. ** be used to optimize this query, then it can also be used by the FK
  14240. ** implementation to optimize DELETE or UPDATE statements on the parent
  14241. ** table.
  14242. **
  14243. ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
  14244. ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
  14245. ** contains an index that can be used to optimize the query.
  14246. **
  14247. ** 2. Human readable text that describes the child table and columns. e.g.
  14248. **
  14249. ** "child_table(child_key1, child_key2)"
  14250. **
  14251. ** 3. Human readable text that describes the parent table and columns. e.g.
  14252. **
  14253. ** "parent_table(parent_key1, parent_key2)"
  14254. **
  14255. ** 4. A full CREATE INDEX statement for an index that could be used to
  14256. ** optimize DELETE or UPDATE statements on the parent table. e.g.
  14257. **
  14258. ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
  14259. **
  14260. ** 5. The name of the parent table.
  14261. **
  14262. ** These six values are used by the C logic below to generate the report.
  14263. */
  14264. const char *zSql =
  14265. "SELECT "
  14266. " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
  14267. " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
  14268. " || fkey_collate_clause("
  14269. " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
  14270. ", "
  14271. " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
  14272. " || group_concat('*=?', ' AND ') || ')'"
  14273. ", "
  14274. " s.name || '(' || group_concat(f.[from], ', ') || ')'"
  14275. ", "
  14276. " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
  14277. ", "
  14278. " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
  14279. " || ' ON ' || quote(s.name) || '('"
  14280. " || group_concat(quote(f.[from]) ||"
  14281. " fkey_collate_clause("
  14282. " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
  14283. " || ');'"
  14284. ", "
  14285. " f.[table] "
  14286. "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
  14287. "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
  14288. "GROUP BY s.name, f.id "
  14289. "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
  14290. ;
  14291. const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
  14292. for(i=2; i<nArg; i++){
  14293. int n = strlen30(azArg[i]);
  14294. if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
  14295. bVerbose = 1;
  14296. }
  14297. else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
  14298. bGroupByParent = 1;
  14299. zIndent = " ";
  14300. }
  14301. else{
  14302. raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
  14303. azArg[0], azArg[1]
  14304. );
  14305. return SQLITE_ERROR;
  14306. }
  14307. }
  14308. /* Register the fkey_collate_clause() SQL function */
  14309. rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
  14310. 0, shellFkeyCollateClause, 0, 0
  14311. );
  14312. if( rc==SQLITE_OK ){
  14313. rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
  14314. }
  14315. if( rc==SQLITE_OK ){
  14316. sqlite3_bind_int(pSql, 1, bGroupByParent);
  14317. }
  14318. if( rc==SQLITE_OK ){
  14319. int rc2;
  14320. char *zPrev = 0;
  14321. while( SQLITE_ROW==sqlite3_step(pSql) ){
  14322. int res = -1;
  14323. sqlite3_stmt *pExplain = 0;
  14324. const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
  14325. const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
  14326. const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
  14327. const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
  14328. const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
  14329. const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
  14330. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  14331. if( rc!=SQLITE_OK ) break;
  14332. if( SQLITE_ROW==sqlite3_step(pExplain) ){
  14333. const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
  14334. res = (
  14335. 0==sqlite3_strglob(zGlob, zPlan)
  14336. || 0==sqlite3_strglob(zGlobIPK, zPlan)
  14337. );
  14338. }
  14339. rc = sqlite3_finalize(pExplain);
  14340. if( rc!=SQLITE_OK ) break;
  14341. if( res<0 ){
  14342. raw_printf(stderr, "Error: internal error");
  14343. break;
  14344. }else{
  14345. if( bGroupByParent
  14346. && (bVerbose || res==0)
  14347. && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
  14348. ){
  14349. raw_printf(out, "-- Parent table %s\n", zParent);
  14350. sqlite3_free(zPrev);
  14351. zPrev = sqlite3_mprintf("%s", zParent);
  14352. }
  14353. if( res==0 ){
  14354. raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
  14355. }else if( bVerbose ){
  14356. raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
  14357. zIndent, zFrom, zTarget
  14358. );
  14359. }
  14360. }
  14361. }
  14362. sqlite3_free(zPrev);
  14363. if( rc!=SQLITE_OK ){
  14364. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  14365. }
  14366. rc2 = sqlite3_finalize(pSql);
  14367. if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
  14368. rc = rc2;
  14369. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  14370. }
  14371. }else{
  14372. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  14373. }
  14374. return rc;
  14375. }
  14376. /*
  14377. ** Implementation of ".lint" dot command.
  14378. */
  14379. static int lintDotCommand(
  14380. ShellState *pState, /* Current shell tool state */
  14381. char **azArg, /* Array of arguments passed to dot command */
  14382. int nArg /* Number of entries in azArg[] */
  14383. ){
  14384. int n;
  14385. n = (nArg>=2 ? strlen30(azArg[1]) : 0);
  14386. if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
  14387. return lintFkeyIndexes(pState, azArg, nArg);
  14388. usage:
  14389. raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
  14390. raw_printf(stderr, "Where sub-commands are:\n");
  14391. raw_printf(stderr, " fkey-indexes\n");
  14392. return SQLITE_ERROR;
  14393. }
  14394. #if !defined SQLITE_OMIT_VIRTUALTABLE
  14395. static void shellPrepare(
  14396. sqlite3 *db,
  14397. int *pRc,
  14398. const char *zSql,
  14399. sqlite3_stmt **ppStmt
  14400. ){
  14401. *ppStmt = 0;
  14402. if( *pRc==SQLITE_OK ){
  14403. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  14404. if( rc!=SQLITE_OK ){
  14405. raw_printf(stderr, "sql error: %s (%d)\n",
  14406. sqlite3_errmsg(db), sqlite3_errcode(db)
  14407. );
  14408. *pRc = rc;
  14409. }
  14410. }
  14411. }
  14412. /*
  14413. ** Create a prepared statement using printf-style arguments for the SQL.
  14414. **
  14415. ** This routine is could be marked "static". But it is not always used,
  14416. ** depending on compile-time options. By omitting the "static", we avoid
  14417. ** nuisance compiler warnings about "defined but not used".
  14418. */
  14419. void shellPreparePrintf(
  14420. sqlite3 *db,
  14421. int *pRc,
  14422. sqlite3_stmt **ppStmt,
  14423. const char *zFmt,
  14424. ...
  14425. ){
  14426. *ppStmt = 0;
  14427. if( *pRc==SQLITE_OK ){
  14428. va_list ap;
  14429. char *z;
  14430. va_start(ap, zFmt);
  14431. z = sqlite3_vmprintf(zFmt, ap);
  14432. va_end(ap);
  14433. if( z==0 ){
  14434. *pRc = SQLITE_NOMEM;
  14435. }else{
  14436. shellPrepare(db, pRc, z, ppStmt);
  14437. sqlite3_free(z);
  14438. }
  14439. }
  14440. }
  14441. /* Finalize the prepared statement created using shellPreparePrintf().
  14442. **
  14443. ** This routine is could be marked "static". But it is not always used,
  14444. ** depending on compile-time options. By omitting the "static", we avoid
  14445. ** nuisance compiler warnings about "defined but not used".
  14446. */
  14447. void shellFinalize(
  14448. int *pRc,
  14449. sqlite3_stmt *pStmt
  14450. ){
  14451. if( pStmt ){
  14452. sqlite3 *db = sqlite3_db_handle(pStmt);
  14453. int rc = sqlite3_finalize(pStmt);
  14454. if( *pRc==SQLITE_OK ){
  14455. if( rc!=SQLITE_OK ){
  14456. raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
  14457. }
  14458. *pRc = rc;
  14459. }
  14460. }
  14461. }
  14462. /* Reset the prepared statement created using shellPreparePrintf().
  14463. **
  14464. ** This routine is could be marked "static". But it is not always used,
  14465. ** depending on compile-time options. By omitting the "static", we avoid
  14466. ** nuisance compiler warnings about "defined but not used".
  14467. */
  14468. void shellReset(
  14469. int *pRc,
  14470. sqlite3_stmt *pStmt
  14471. ){
  14472. int rc = sqlite3_reset(pStmt);
  14473. if( *pRc==SQLITE_OK ){
  14474. if( rc!=SQLITE_OK ){
  14475. sqlite3 *db = sqlite3_db_handle(pStmt);
  14476. raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
  14477. }
  14478. *pRc = rc;
  14479. }
  14480. }
  14481. #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
  14482. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  14483. /******************************************************************************
  14484. ** The ".archive" or ".ar" command.
  14485. */
  14486. /*
  14487. ** Structure representing a single ".ar" command.
  14488. */
  14489. typedef struct ArCommand ArCommand;
  14490. struct ArCommand {
  14491. u8 eCmd; /* An AR_CMD_* value */
  14492. u8 bVerbose; /* True if --verbose */
  14493. u8 bZip; /* True if the archive is a ZIP */
  14494. u8 bDryRun; /* True if --dry-run */
  14495. u8 bAppend; /* True if --append */
  14496. u8 fromCmdLine; /* Run from -A instead of .archive */
  14497. int nArg; /* Number of command arguments */
  14498. char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
  14499. const char *zFile; /* --file argument, or NULL */
  14500. const char *zDir; /* --directory argument, or NULL */
  14501. char **azArg; /* Array of command arguments */
  14502. ShellState *p; /* Shell state */
  14503. sqlite3 *db; /* Database containing the archive */
  14504. };
  14505. /*
  14506. ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
  14507. */
  14508. static int arUsage(FILE *f){
  14509. showHelp(f,"archive");
  14510. return SQLITE_ERROR;
  14511. }
  14512. /*
  14513. ** Print an error message for the .ar command to stderr and return
  14514. ** SQLITE_ERROR.
  14515. */
  14516. static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
  14517. va_list ap;
  14518. char *z;
  14519. va_start(ap, zFmt);
  14520. z = sqlite3_vmprintf(zFmt, ap);
  14521. va_end(ap);
  14522. utf8_printf(stderr, "Error: %s\n", z);
  14523. if( pAr->fromCmdLine ){
  14524. utf8_printf(stderr, "Use \"-A\" for more help\n");
  14525. }else{
  14526. utf8_printf(stderr, "Use \".archive --help\" for more help\n");
  14527. }
  14528. sqlite3_free(z);
  14529. return SQLITE_ERROR;
  14530. }
  14531. /*
  14532. ** Values for ArCommand.eCmd.
  14533. */
  14534. #define AR_CMD_CREATE 1
  14535. #define AR_CMD_UPDATE 2
  14536. #define AR_CMD_INSERT 3
  14537. #define AR_CMD_EXTRACT 4
  14538. #define AR_CMD_LIST 5
  14539. #define AR_CMD_HELP 6
  14540. /*
  14541. ** Other (non-command) switches.
  14542. */
  14543. #define AR_SWITCH_VERBOSE 7
  14544. #define AR_SWITCH_FILE 8
  14545. #define AR_SWITCH_DIRECTORY 9
  14546. #define AR_SWITCH_APPEND 10
  14547. #define AR_SWITCH_DRYRUN 11
  14548. static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
  14549. switch( eSwitch ){
  14550. case AR_CMD_CREATE:
  14551. case AR_CMD_EXTRACT:
  14552. case AR_CMD_LIST:
  14553. case AR_CMD_UPDATE:
  14554. case AR_CMD_INSERT:
  14555. case AR_CMD_HELP:
  14556. if( pAr->eCmd ){
  14557. return arErrorMsg(pAr, "multiple command options");
  14558. }
  14559. pAr->eCmd = eSwitch;
  14560. break;
  14561. case AR_SWITCH_DRYRUN:
  14562. pAr->bDryRun = 1;
  14563. break;
  14564. case AR_SWITCH_VERBOSE:
  14565. pAr->bVerbose = 1;
  14566. break;
  14567. case AR_SWITCH_APPEND:
  14568. pAr->bAppend = 1;
  14569. /* Fall thru into --file */
  14570. case AR_SWITCH_FILE:
  14571. pAr->zFile = zArg;
  14572. break;
  14573. case AR_SWITCH_DIRECTORY:
  14574. pAr->zDir = zArg;
  14575. break;
  14576. }
  14577. return SQLITE_OK;
  14578. }
  14579. /*
  14580. ** Parse the command line for an ".ar" command. The results are written into
  14581. ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
  14582. ** successfully, otherwise an error message is written to stderr and
  14583. ** SQLITE_ERROR returned.
  14584. */
  14585. static int arParseCommand(
  14586. char **azArg, /* Array of arguments passed to dot command */
  14587. int nArg, /* Number of entries in azArg[] */
  14588. ArCommand *pAr /* Populate this object */
  14589. ){
  14590. struct ArSwitch {
  14591. const char *zLong;
  14592. char cShort;
  14593. u8 eSwitch;
  14594. u8 bArg;
  14595. } aSwitch[] = {
  14596. { "create", 'c', AR_CMD_CREATE, 0 },
  14597. { "extract", 'x', AR_CMD_EXTRACT, 0 },
  14598. { "insert", 'i', AR_CMD_INSERT, 0 },
  14599. { "list", 't', AR_CMD_LIST, 0 },
  14600. { "update", 'u', AR_CMD_UPDATE, 0 },
  14601. { "help", 'h', AR_CMD_HELP, 0 },
  14602. { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
  14603. { "file", 'f', AR_SWITCH_FILE, 1 },
  14604. { "append", 'a', AR_SWITCH_APPEND, 1 },
  14605. { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
  14606. { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
  14607. };
  14608. int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
  14609. struct ArSwitch *pEnd = &aSwitch[nSwitch];
  14610. if( nArg<=1 ){
  14611. utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
  14612. return arUsage(stderr);
  14613. }else{
  14614. char *z = azArg[1];
  14615. if( z[0]!='-' ){
  14616. /* Traditional style [tar] invocation */
  14617. int i;
  14618. int iArg = 2;
  14619. for(i=0; z[i]; i++){
  14620. const char *zArg = 0;
  14621. struct ArSwitch *pOpt;
  14622. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  14623. if( z[i]==pOpt->cShort ) break;
  14624. }
  14625. if( pOpt==pEnd ){
  14626. return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
  14627. }
  14628. if( pOpt->bArg ){
  14629. if( iArg>=nArg ){
  14630. return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
  14631. }
  14632. zArg = azArg[iArg++];
  14633. }
  14634. if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
  14635. }
  14636. pAr->nArg = nArg-iArg;
  14637. if( pAr->nArg>0 ){
  14638. pAr->azArg = &azArg[iArg];
  14639. }
  14640. }else{
  14641. /* Non-traditional invocation */
  14642. int iArg;
  14643. for(iArg=1; iArg<nArg; iArg++){
  14644. int n;
  14645. z = azArg[iArg];
  14646. if( z[0]!='-' ){
  14647. /* All remaining command line words are command arguments. */
  14648. pAr->azArg = &azArg[iArg];
  14649. pAr->nArg = nArg-iArg;
  14650. break;
  14651. }
  14652. n = strlen30(z);
  14653. if( z[1]!='-' ){
  14654. int i;
  14655. /* One or more short options */
  14656. for(i=1; i<n; i++){
  14657. const char *zArg = 0;
  14658. struct ArSwitch *pOpt;
  14659. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  14660. if( z[i]==pOpt->cShort ) break;
  14661. }
  14662. if( pOpt==pEnd ){
  14663. return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
  14664. }
  14665. if( pOpt->bArg ){
  14666. if( i<(n-1) ){
  14667. zArg = &z[i+1];
  14668. i = n;
  14669. }else{
  14670. if( iArg>=(nArg-1) ){
  14671. return arErrorMsg(pAr, "option requires an argument: %c",
  14672. z[i]);
  14673. }
  14674. zArg = azArg[++iArg];
  14675. }
  14676. }
  14677. if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
  14678. }
  14679. }else if( z[2]=='\0' ){
  14680. /* A -- option, indicating that all remaining command line words
  14681. ** are command arguments. */
  14682. pAr->azArg = &azArg[iArg+1];
  14683. pAr->nArg = nArg-iArg-1;
  14684. break;
  14685. }else{
  14686. /* A long option */
  14687. const char *zArg = 0; /* Argument for option, if any */
  14688. struct ArSwitch *pMatch = 0; /* Matching option */
  14689. struct ArSwitch *pOpt; /* Iterator */
  14690. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  14691. const char *zLong = pOpt->zLong;
  14692. if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
  14693. if( pMatch ){
  14694. return arErrorMsg(pAr, "ambiguous option: %s",z);
  14695. }else{
  14696. pMatch = pOpt;
  14697. }
  14698. }
  14699. }
  14700. if( pMatch==0 ){
  14701. return arErrorMsg(pAr, "unrecognized option: %s", z);
  14702. }
  14703. if( pMatch->bArg ){
  14704. if( iArg>=(nArg-1) ){
  14705. return arErrorMsg(pAr, "option requires an argument: %s", z);
  14706. }
  14707. zArg = azArg[++iArg];
  14708. }
  14709. if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
  14710. }
  14711. }
  14712. }
  14713. }
  14714. return SQLITE_OK;
  14715. }
  14716. /*
  14717. ** This function assumes that all arguments within the ArCommand.azArg[]
  14718. ** array refer to archive members, as for the --extract or --list commands.
  14719. ** It checks that each of them are present. If any specified file is not
  14720. ** present in the archive, an error is printed to stderr and an error
  14721. ** code returned. Otherwise, if all specified arguments are present in
  14722. ** the archive, SQLITE_OK is returned.
  14723. **
  14724. ** This function strips any trailing '/' characters from each argument.
  14725. ** This is consistent with the way the [tar] command seems to work on
  14726. ** Linux.
  14727. */
  14728. static int arCheckEntries(ArCommand *pAr){
  14729. int rc = SQLITE_OK;
  14730. if( pAr->nArg ){
  14731. int i, j;
  14732. sqlite3_stmt *pTest = 0;
  14733. shellPreparePrintf(pAr->db, &rc, &pTest,
  14734. "SELECT name FROM %s WHERE name=$name",
  14735. pAr->zSrcTable
  14736. );
  14737. j = sqlite3_bind_parameter_index(pTest, "$name");
  14738. for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
  14739. char *z = pAr->azArg[i];
  14740. int n = strlen30(z);
  14741. int bOk = 0;
  14742. while( n>0 && z[n-1]=='/' ) n--;
  14743. z[n] = '\0';
  14744. sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
  14745. if( SQLITE_ROW==sqlite3_step(pTest) ){
  14746. bOk = 1;
  14747. }
  14748. shellReset(&rc, pTest);
  14749. if( rc==SQLITE_OK && bOk==0 ){
  14750. utf8_printf(stderr, "not found in archive: %s\n", z);
  14751. rc = SQLITE_ERROR;
  14752. }
  14753. }
  14754. shellFinalize(&rc, pTest);
  14755. }
  14756. return rc;
  14757. }
  14758. /*
  14759. ** Format a WHERE clause that can be used against the "sqlar" table to
  14760. ** identify all archive members that match the command arguments held
  14761. ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
  14762. ** The caller is responsible for eventually calling sqlite3_free() on
  14763. ** any non-NULL (*pzWhere) value.
  14764. */
  14765. static void arWhereClause(
  14766. int *pRc,
  14767. ArCommand *pAr,
  14768. char **pzWhere /* OUT: New WHERE clause */
  14769. ){
  14770. char *zWhere = 0;
  14771. if( *pRc==SQLITE_OK ){
  14772. if( pAr->nArg==0 ){
  14773. zWhere = sqlite3_mprintf("1");
  14774. }else{
  14775. int i;
  14776. const char *zSep = "";
  14777. for(i=0; i<pAr->nArg; i++){
  14778. const char *z = pAr->azArg[i];
  14779. zWhere = sqlite3_mprintf(
  14780. "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
  14781. zWhere, zSep, z, strlen30(z)+1, z
  14782. );
  14783. if( zWhere==0 ){
  14784. *pRc = SQLITE_NOMEM;
  14785. break;
  14786. }
  14787. zSep = " OR ";
  14788. }
  14789. }
  14790. }
  14791. *pzWhere = zWhere;
  14792. }
  14793. /*
  14794. ** Implementation of .ar "lisT" command.
  14795. */
  14796. static int arListCommand(ArCommand *pAr){
  14797. const char *zSql = "SELECT %s FROM %s WHERE %s";
  14798. const char *azCols[] = {
  14799. "name",
  14800. "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
  14801. };
  14802. char *zWhere = 0;
  14803. sqlite3_stmt *pSql = 0;
  14804. int rc;
  14805. rc = arCheckEntries(pAr);
  14806. arWhereClause(&rc, pAr, &zWhere);
  14807. shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
  14808. pAr->zSrcTable, zWhere);
  14809. if( pAr->bDryRun ){
  14810. utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
  14811. }else{
  14812. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  14813. if( pAr->bVerbose ){
  14814. utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
  14815. sqlite3_column_text(pSql, 0),
  14816. sqlite3_column_int(pSql, 1),
  14817. sqlite3_column_text(pSql, 2),
  14818. sqlite3_column_text(pSql, 3)
  14819. );
  14820. }else{
  14821. utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
  14822. }
  14823. }
  14824. }
  14825. shellFinalize(&rc, pSql);
  14826. sqlite3_free(zWhere);
  14827. return rc;
  14828. }
  14829. /*
  14830. ** Implementation of .ar "eXtract" command.
  14831. */
  14832. static int arExtractCommand(ArCommand *pAr){
  14833. const char *zSql1 =
  14834. "SELECT "
  14835. " ($dir || name),"
  14836. " writefile(($dir || name), %s, mode, mtime) "
  14837. "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
  14838. " AND name NOT GLOB '*..[/\\]*'";
  14839. const char *azExtraArg[] = {
  14840. "sqlar_uncompress(data, sz)",
  14841. "data"
  14842. };
  14843. sqlite3_stmt *pSql = 0;
  14844. int rc = SQLITE_OK;
  14845. char *zDir = 0;
  14846. char *zWhere = 0;
  14847. int i, j;
  14848. /* If arguments are specified, check that they actually exist within
  14849. ** the archive before proceeding. And formulate a WHERE clause to
  14850. ** match them. */
  14851. rc = arCheckEntries(pAr);
  14852. arWhereClause(&rc, pAr, &zWhere);
  14853. if( rc==SQLITE_OK ){
  14854. if( pAr->zDir ){
  14855. zDir = sqlite3_mprintf("%s/", pAr->zDir);
  14856. }else{
  14857. zDir = sqlite3_mprintf("");
  14858. }
  14859. if( zDir==0 ) rc = SQLITE_NOMEM;
  14860. }
  14861. shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
  14862. azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
  14863. );
  14864. if( rc==SQLITE_OK ){
  14865. j = sqlite3_bind_parameter_index(pSql, "$dir");
  14866. sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
  14867. /* Run the SELECT statement twice. The first time, writefile() is called
  14868. ** for all archive members that should be extracted. The second time,
  14869. ** only for the directories. This is because the timestamps for
  14870. ** extracted directories must be reset after they are populated (as
  14871. ** populating them changes the timestamp). */
  14872. for(i=0; i<2; i++){
  14873. j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
  14874. sqlite3_bind_int(pSql, j, i);
  14875. if( pAr->bDryRun ){
  14876. utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
  14877. }else{
  14878. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  14879. if( i==0 && pAr->bVerbose ){
  14880. utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
  14881. }
  14882. }
  14883. }
  14884. shellReset(&rc, pSql);
  14885. }
  14886. shellFinalize(&rc, pSql);
  14887. }
  14888. sqlite3_free(zDir);
  14889. sqlite3_free(zWhere);
  14890. return rc;
  14891. }
  14892. /*
  14893. ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
  14894. */
  14895. static int arExecSql(ArCommand *pAr, const char *zSql){
  14896. int rc;
  14897. if( pAr->bDryRun ){
  14898. utf8_printf(pAr->p->out, "%s\n", zSql);
  14899. rc = SQLITE_OK;
  14900. }else{
  14901. char *zErr = 0;
  14902. rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
  14903. if( zErr ){
  14904. utf8_printf(stdout, "ERROR: %s\n", zErr);
  14905. sqlite3_free(zErr);
  14906. }
  14907. }
  14908. return rc;
  14909. }
  14910. /*
  14911. ** Implementation of .ar "create", "insert", and "update" commands.
  14912. **
  14913. ** create -> Create a new SQL archive
  14914. ** insert -> Insert or reinsert all files listed
  14915. ** update -> Insert files that have changed or that were not
  14916. ** previously in the archive
  14917. **
  14918. ** Create the "sqlar" table in the database if it does not already exist.
  14919. ** Then add each file in the azFile[] array to the archive. Directories
  14920. ** are added recursively. If argument bVerbose is non-zero, a message is
  14921. ** printed on stdout for each file archived.
  14922. **
  14923. ** The create command is the same as update, except that it drops
  14924. ** any existing "sqlar" table before beginning. The "insert" command
  14925. ** always overwrites every file named on the command-line, where as
  14926. ** "update" only overwrites if the size or mtime or mode has changed.
  14927. */
  14928. static int arCreateOrUpdateCommand(
  14929. ArCommand *pAr, /* Command arguments and options */
  14930. int bUpdate, /* true for a --create. */
  14931. int bOnlyIfChanged /* Only update if file has changed */
  14932. ){
  14933. const char *zCreate =
  14934. "CREATE TABLE IF NOT EXISTS sqlar(\n"
  14935. " name TEXT PRIMARY KEY, -- name of the file\n"
  14936. " mode INT, -- access permissions\n"
  14937. " mtime INT, -- last modification time\n"
  14938. " sz INT, -- original file size\n"
  14939. " data BLOB -- compressed content\n"
  14940. ")";
  14941. const char *zDrop = "DROP TABLE IF EXISTS sqlar";
  14942. const char *zInsertFmt[2] = {
  14943. "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
  14944. " SELECT\n"
  14945. " %s,\n"
  14946. " mode,\n"
  14947. " mtime,\n"
  14948. " CASE substr(lsmode(mode),1,1)\n"
  14949. " WHEN '-' THEN length(data)\n"
  14950. " WHEN 'd' THEN 0\n"
  14951. " ELSE -1 END,\n"
  14952. " sqlar_compress(data)\n"
  14953. " FROM fsdir(%Q,%Q) AS disk\n"
  14954. " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
  14955. ,
  14956. "REPLACE INTO %s(name,mode,mtime,data)\n"
  14957. " SELECT\n"
  14958. " %s,\n"
  14959. " mode,\n"
  14960. " mtime,\n"
  14961. " data\n"
  14962. " FROM fsdir(%Q,%Q) AS disk\n"
  14963. " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
  14964. };
  14965. int i; /* For iterating through azFile[] */
  14966. int rc; /* Return code */
  14967. const char *zTab = 0; /* SQL table into which to insert */
  14968. char *zSql;
  14969. char zTemp[50];
  14970. char *zExists = 0;
  14971. arExecSql(pAr, "PRAGMA page_size=512");
  14972. rc = arExecSql(pAr, "SAVEPOINT ar;");
  14973. if( rc!=SQLITE_OK ) return rc;
  14974. zTemp[0] = 0;
  14975. if( pAr->bZip ){
  14976. /* Initialize the zipfile virtual table, if necessary */
  14977. if( pAr->zFile ){
  14978. sqlite3_uint64 r;
  14979. sqlite3_randomness(sizeof(r),&r);
  14980. sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
  14981. zTab = zTemp;
  14982. zSql = sqlite3_mprintf(
  14983. "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
  14984. zTab, pAr->zFile
  14985. );
  14986. rc = arExecSql(pAr, zSql);
  14987. sqlite3_free(zSql);
  14988. }else{
  14989. zTab = "zip";
  14990. }
  14991. }else{
  14992. /* Initialize the table for an SQLAR */
  14993. zTab = "sqlar";
  14994. if( bUpdate==0 ){
  14995. rc = arExecSql(pAr, zDrop);
  14996. if( rc!=SQLITE_OK ) goto end_ar_transaction;
  14997. }
  14998. rc = arExecSql(pAr, zCreate);
  14999. }
  15000. if( bOnlyIfChanged ){
  15001. zExists = sqlite3_mprintf(
  15002. " AND NOT EXISTS("
  15003. "SELECT 1 FROM %s AS mem"
  15004. " WHERE mem.name=disk.name"
  15005. " AND mem.mtime=disk.mtime"
  15006. " AND mem.mode=disk.mode)", zTab);
  15007. }else{
  15008. zExists = sqlite3_mprintf("");
  15009. }
  15010. if( zExists==0 ) rc = SQLITE_NOMEM;
  15011. for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
  15012. char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
  15013. pAr->bVerbose ? "shell_putsnl(name)" : "name",
  15014. pAr->azArg[i], pAr->zDir, zExists);
  15015. rc = arExecSql(pAr, zSql2);
  15016. sqlite3_free(zSql2);
  15017. }
  15018. end_ar_transaction:
  15019. if( rc!=SQLITE_OK ){
  15020. sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
  15021. }else{
  15022. rc = arExecSql(pAr, "RELEASE ar;");
  15023. if( pAr->bZip && pAr->zFile ){
  15024. zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
  15025. arExecSql(pAr, zSql);
  15026. sqlite3_free(zSql);
  15027. }
  15028. }
  15029. sqlite3_free(zExists);
  15030. return rc;
  15031. }
  15032. /*
  15033. ** Implementation of ".ar" dot command.
  15034. */
  15035. static int arDotCommand(
  15036. ShellState *pState, /* Current shell tool state */
  15037. int fromCmdLine, /* True if -A command-line option, not .ar cmd */
  15038. char **azArg, /* Array of arguments passed to dot command */
  15039. int nArg /* Number of entries in azArg[] */
  15040. ){
  15041. ArCommand cmd;
  15042. int rc;
  15043. memset(&cmd, 0, sizeof(cmd));
  15044. cmd.fromCmdLine = fromCmdLine;
  15045. rc = arParseCommand(azArg, nArg, &cmd);
  15046. if( rc==SQLITE_OK ){
  15047. int eDbType = SHELL_OPEN_UNSPEC;
  15048. cmd.p = pState;
  15049. cmd.db = pState->db;
  15050. if( cmd.zFile ){
  15051. eDbType = deduceDatabaseType(cmd.zFile, 1);
  15052. }else{
  15053. eDbType = pState->openMode;
  15054. }
  15055. if( eDbType==SHELL_OPEN_ZIPFILE ){
  15056. if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
  15057. if( cmd.zFile==0 ){
  15058. cmd.zSrcTable = sqlite3_mprintf("zip");
  15059. }else{
  15060. cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
  15061. }
  15062. }
  15063. cmd.bZip = 1;
  15064. }else if( cmd.zFile ){
  15065. int flags;
  15066. if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
  15067. if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
  15068. || cmd.eCmd==AR_CMD_UPDATE ){
  15069. flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
  15070. }else{
  15071. flags = SQLITE_OPEN_READONLY;
  15072. }
  15073. cmd.db = 0;
  15074. if( cmd.bDryRun ){
  15075. utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
  15076. eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
  15077. }
  15078. rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
  15079. eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
  15080. if( rc!=SQLITE_OK ){
  15081. utf8_printf(stderr, "cannot open file: %s (%s)\n",
  15082. cmd.zFile, sqlite3_errmsg(cmd.db)
  15083. );
  15084. goto end_ar_command;
  15085. }
  15086. sqlite3_fileio_init(cmd.db, 0, 0);
  15087. sqlite3_sqlar_init(cmd.db, 0, 0);
  15088. sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
  15089. shellPutsFunc, 0, 0);
  15090. }
  15091. if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
  15092. if( cmd.eCmd!=AR_CMD_CREATE
  15093. && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
  15094. ){
  15095. utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
  15096. rc = SQLITE_ERROR;
  15097. goto end_ar_command;
  15098. }
  15099. cmd.zSrcTable = sqlite3_mprintf("sqlar");
  15100. }
  15101. switch( cmd.eCmd ){
  15102. case AR_CMD_CREATE:
  15103. rc = arCreateOrUpdateCommand(&cmd, 0, 0);
  15104. break;
  15105. case AR_CMD_EXTRACT:
  15106. rc = arExtractCommand(&cmd);
  15107. break;
  15108. case AR_CMD_LIST:
  15109. rc = arListCommand(&cmd);
  15110. break;
  15111. case AR_CMD_HELP:
  15112. arUsage(pState->out);
  15113. break;
  15114. case AR_CMD_INSERT:
  15115. rc = arCreateOrUpdateCommand(&cmd, 1, 0);
  15116. break;
  15117. default:
  15118. assert( cmd.eCmd==AR_CMD_UPDATE );
  15119. rc = arCreateOrUpdateCommand(&cmd, 1, 1);
  15120. break;
  15121. }
  15122. }
  15123. end_ar_command:
  15124. if( cmd.db!=pState->db ){
  15125. close_db(cmd.db);
  15126. }
  15127. sqlite3_free(cmd.zSrcTable);
  15128. return rc;
  15129. }
  15130. /* End of the ".archive" or ".ar" command logic
  15131. *******************************************************************************/
  15132. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
  15133. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
  15134. /*
  15135. ** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
  15136. ** Otherwise, the SQL statement or statements in zSql are executed using
  15137. ** database connection db and the error code written to *pRc before
  15138. ** this function returns.
  15139. */
  15140. static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
  15141. int rc = *pRc;
  15142. if( rc==SQLITE_OK ){
  15143. char *zErr = 0;
  15144. rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
  15145. if( rc!=SQLITE_OK ){
  15146. raw_printf(stderr, "SQL error: %s\n", zErr);
  15147. }
  15148. *pRc = rc;
  15149. }
  15150. }
  15151. /*
  15152. ** Like shellExec(), except that zFmt is a printf() style format string.
  15153. */
  15154. static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
  15155. char *z = 0;
  15156. if( *pRc==SQLITE_OK ){
  15157. va_list ap;
  15158. va_start(ap, zFmt);
  15159. z = sqlite3_vmprintf(zFmt, ap);
  15160. va_end(ap);
  15161. if( z==0 ){
  15162. *pRc = SQLITE_NOMEM;
  15163. }else{
  15164. shellExec(db, pRc, z);
  15165. }
  15166. sqlite3_free(z);
  15167. }
  15168. }
  15169. /*
  15170. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  15171. ** Otherwise, an attempt is made to allocate, zero and return a pointer
  15172. ** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
  15173. ** to SQLITE_NOMEM and NULL returned.
  15174. */
  15175. static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
  15176. void *pRet = 0;
  15177. if( *pRc==SQLITE_OK ){
  15178. pRet = sqlite3_malloc64(nByte);
  15179. if( pRet==0 ){
  15180. *pRc = SQLITE_NOMEM;
  15181. }else{
  15182. memset(pRet, 0, nByte);
  15183. }
  15184. }
  15185. return pRet;
  15186. }
  15187. /*
  15188. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  15189. ** Otherwise, zFmt is treated as a printf() style string. The result of
  15190. ** formatting it along with any trailing arguments is written into a
  15191. ** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
  15192. ** It is the responsibility of the caller to eventually free this buffer
  15193. ** using a call to sqlite3_free().
  15194. **
  15195. ** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
  15196. ** pointer returned.
  15197. */
  15198. static char *shellMPrintf(int *pRc, const char *zFmt, ...){
  15199. char *z = 0;
  15200. if( *pRc==SQLITE_OK ){
  15201. va_list ap;
  15202. va_start(ap, zFmt);
  15203. z = sqlite3_vmprintf(zFmt, ap);
  15204. va_end(ap);
  15205. if( z==0 ){
  15206. *pRc = SQLITE_NOMEM;
  15207. }
  15208. }
  15209. return z;
  15210. }
  15211. /*
  15212. ** When running the ".recover" command, each output table, and the special
  15213. ** orphaned row table if it is required, is represented by an instance
  15214. ** of the following struct.
  15215. */
  15216. typedef struct RecoverTable RecoverTable;
  15217. struct RecoverTable {
  15218. char *zQuoted; /* Quoted version of table name */
  15219. int nCol; /* Number of columns in table */
  15220. char **azlCol; /* Array of column lists */
  15221. int iPk; /* Index of IPK column */
  15222. };
  15223. /*
  15224. ** Free a RecoverTable object allocated by recoverFindTable() or
  15225. ** recoverOrphanTable().
  15226. */
  15227. static void recoverFreeTable(RecoverTable *pTab){
  15228. if( pTab ){
  15229. sqlite3_free(pTab->zQuoted);
  15230. if( pTab->azlCol ){
  15231. int i;
  15232. for(i=0; i<=pTab->nCol; i++){
  15233. sqlite3_free(pTab->azlCol[i]);
  15234. }
  15235. sqlite3_free(pTab->azlCol);
  15236. }
  15237. sqlite3_free(pTab);
  15238. }
  15239. }
  15240. /*
  15241. ** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
  15242. ** Otherwise, it allocates and returns a RecoverTable object based on the
  15243. ** final four arguments passed to this function. It is the responsibility
  15244. ** of the caller to eventually free the returned object using
  15245. ** recoverFreeTable().
  15246. */
  15247. static RecoverTable *recoverNewTable(
  15248. int *pRc, /* IN/OUT: Error code */
  15249. const char *zName, /* Name of table */
  15250. const char *zSql, /* CREATE TABLE statement */
  15251. int bIntkey,
  15252. int nCol
  15253. ){
  15254. sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */
  15255. int rc = *pRc;
  15256. RecoverTable *pTab = 0;
  15257. pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
  15258. if( rc==SQLITE_OK ){
  15259. int nSqlCol = 0;
  15260. int bSqlIntkey = 0;
  15261. sqlite3_stmt *pStmt = 0;
  15262. rc = sqlite3_open("", &dbtmp);
  15263. if( rc==SQLITE_OK ){
  15264. sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
  15265. shellIdQuote, 0, 0);
  15266. }
  15267. if( rc==SQLITE_OK ){
  15268. rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
  15269. }
  15270. if( rc==SQLITE_OK ){
  15271. rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
  15272. if( rc==SQLITE_ERROR ){
  15273. rc = SQLITE_OK;
  15274. goto finished;
  15275. }
  15276. }
  15277. shellPreparePrintf(dbtmp, &rc, &pStmt,
  15278. "SELECT count(*) FROM pragma_table_info(%Q)", zName
  15279. );
  15280. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  15281. nSqlCol = sqlite3_column_int(pStmt, 0);
  15282. }
  15283. shellFinalize(&rc, pStmt);
  15284. if( rc!=SQLITE_OK || nSqlCol<nCol ){
  15285. goto finished;
  15286. }
  15287. shellPreparePrintf(dbtmp, &rc, &pStmt,
  15288. "SELECT ("
  15289. " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
  15290. ") FROM sqlite_schema WHERE name = %Q", zName
  15291. );
  15292. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  15293. bSqlIntkey = sqlite3_column_int(pStmt, 0);
  15294. }
  15295. shellFinalize(&rc, pStmt);
  15296. if( bIntkey==bSqlIntkey ){
  15297. int i;
  15298. const char *zPk = "_rowid_";
  15299. sqlite3_stmt *pPkFinder = 0;
  15300. /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
  15301. ** set zPk to the name of the PK column, and pTab->iPk to the index
  15302. ** of the column, where columns are 0-numbered from left to right.
  15303. ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
  15304. ** leave zPk as "_rowid_" and pTab->iPk at -2. */
  15305. pTab->iPk = -2;
  15306. if( bIntkey ){
  15307. shellPreparePrintf(dbtmp, &rc, &pPkFinder,
  15308. "SELECT cid, name FROM pragma_table_info(%Q) "
  15309. " WHERE pk=1 AND type='integer' COLLATE nocase"
  15310. " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
  15311. , zName, zName
  15312. );
  15313. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
  15314. pTab->iPk = sqlite3_column_int(pPkFinder, 0);
  15315. zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
  15316. }
  15317. }
  15318. pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
  15319. pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
  15320. pTab->nCol = nSqlCol;
  15321. if( bIntkey ){
  15322. pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
  15323. }else{
  15324. pTab->azlCol[0] = shellMPrintf(&rc, "");
  15325. }
  15326. i = 1;
  15327. shellPreparePrintf(dbtmp, &rc, &pStmt,
  15328. "SELECT %Q || group_concat(shell_idquote(name), ', ') "
  15329. " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
  15330. "FROM pragma_table_info(%Q)",
  15331. bIntkey ? ", " : "", pTab->iPk,
  15332. bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
  15333. zName
  15334. );
  15335. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  15336. const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
  15337. pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
  15338. i++;
  15339. }
  15340. shellFinalize(&rc, pStmt);
  15341. shellFinalize(&rc, pPkFinder);
  15342. }
  15343. }
  15344. finished:
  15345. sqlite3_close(dbtmp);
  15346. *pRc = rc;
  15347. if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
  15348. recoverFreeTable(pTab);
  15349. pTab = 0;
  15350. }
  15351. return pTab;
  15352. }
  15353. /*
  15354. ** This function is called to search the schema recovered from the
  15355. ** sqlite_schema table of the (possibly) corrupt database as part
  15356. ** of a ".recover" command. Specifically, for a table with root page
  15357. ** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
  15358. ** table must be a WITHOUT ROWID table, or if non-zero, not one of
  15359. ** those.
  15360. **
  15361. ** If a table is found, a (RecoverTable*) object is returned. Or, if
  15362. ** no such table is found, but bIntkey is false and iRoot is the
  15363. ** root page of an index in the recovered schema, then (*pbNoop) is
  15364. ** set to true and NULL returned. Or, if there is no such table or
  15365. ** index, NULL is returned and (*pbNoop) set to 0, indicating that
  15366. ** the caller should write data to the orphans table.
  15367. */
  15368. static RecoverTable *recoverFindTable(
  15369. ShellState *pState, /* Shell state object */
  15370. int *pRc, /* IN/OUT: Error code */
  15371. int iRoot, /* Root page of table */
  15372. int bIntkey, /* True for an intkey table */
  15373. int nCol, /* Number of columns in table */
  15374. int *pbNoop /* OUT: True if iRoot is root of index */
  15375. ){
  15376. sqlite3_stmt *pStmt = 0;
  15377. RecoverTable *pRet = 0;
  15378. int bNoop = 0;
  15379. const char *zSql = 0;
  15380. const char *zName = 0;
  15381. /* Search the recovered schema for an object with root page iRoot. */
  15382. shellPreparePrintf(pState->db, pRc, &pStmt,
  15383. "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
  15384. );
  15385. while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  15386. const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
  15387. if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
  15388. bNoop = 1;
  15389. break;
  15390. }
  15391. if( sqlite3_stricmp(zType, "table")==0 ){
  15392. zName = (const char*)sqlite3_column_text(pStmt, 1);
  15393. zSql = (const char*)sqlite3_column_text(pStmt, 2);
  15394. pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
  15395. break;
  15396. }
  15397. }
  15398. shellFinalize(pRc, pStmt);
  15399. *pbNoop = bNoop;
  15400. return pRet;
  15401. }
  15402. /*
  15403. ** Return a RecoverTable object representing the orphans table.
  15404. */
  15405. static RecoverTable *recoverOrphanTable(
  15406. ShellState *pState, /* Shell state object */
  15407. int *pRc, /* IN/OUT: Error code */
  15408. const char *zLostAndFound, /* Base name for orphans table */
  15409. int nCol /* Number of user data columns */
  15410. ){
  15411. RecoverTable *pTab = 0;
  15412. if( nCol>=0 && *pRc==SQLITE_OK ){
  15413. int i;
  15414. /* This block determines the name of the orphan table. The prefered
  15415. ** name is zLostAndFound. But if that clashes with another name
  15416. ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
  15417. ** and so on until a non-clashing name is found. */
  15418. int iTab = 0;
  15419. char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
  15420. sqlite3_stmt *pTest = 0;
  15421. shellPrepare(pState->db, pRc,
  15422. "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
  15423. );
  15424. if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
  15425. while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
  15426. shellReset(pRc, pTest);
  15427. sqlite3_free(zTab);
  15428. zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
  15429. sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
  15430. }
  15431. shellFinalize(pRc, pTest);
  15432. pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
  15433. if( pTab ){
  15434. pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
  15435. pTab->nCol = nCol;
  15436. pTab->iPk = -2;
  15437. if( nCol>0 ){
  15438. pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
  15439. if( pTab->azlCol ){
  15440. pTab->azlCol[nCol] = shellMPrintf(pRc, "");
  15441. for(i=nCol-1; i>=0; i--){
  15442. pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
  15443. }
  15444. }
  15445. }
  15446. if( *pRc!=SQLITE_OK ){
  15447. recoverFreeTable(pTab);
  15448. pTab = 0;
  15449. }else{
  15450. raw_printf(pState->out,
  15451. "CREATE TABLE %s(rootpgno INTEGER, "
  15452. "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
  15453. );
  15454. for(i=0; i<nCol; i++){
  15455. raw_printf(pState->out, ", c%d", i);
  15456. }
  15457. raw_printf(pState->out, ");\n");
  15458. }
  15459. }
  15460. sqlite3_free(zTab);
  15461. }
  15462. return pTab;
  15463. }
  15464. /*
  15465. ** This function is called to recover data from the database. A script
  15466. ** to construct a new database containing all recovered data is output
  15467. ** on stream pState->out.
  15468. */
  15469. static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
  15470. int rc = SQLITE_OK;
  15471. sqlite3_stmt *pLoop = 0; /* Loop through all root pages */
  15472. sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */
  15473. sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */
  15474. const char *zRecoveryDb = ""; /* Name of "recovery" database */
  15475. const char *zLostAndFound = "lost_and_found";
  15476. int i;
  15477. int nOrphan = -1;
  15478. RecoverTable *pOrphan = 0;
  15479. int bFreelist = 1; /* 0 if --freelist-corrupt is specified */
  15480. int bRowids = 1; /* 0 if --no-rowids */
  15481. for(i=1; i<nArg; i++){
  15482. char *z = azArg[i];
  15483. int n;
  15484. if( z[0]=='-' && z[1]=='-' ) z++;
  15485. n = strlen30(z);
  15486. if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
  15487. bFreelist = 0;
  15488. }else
  15489. if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
  15490. i++;
  15491. zRecoveryDb = azArg[i];
  15492. }else
  15493. if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
  15494. i++;
  15495. zLostAndFound = azArg[i];
  15496. }else
  15497. if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
  15498. bRowids = 0;
  15499. }
  15500. else{
  15501. utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
  15502. showHelp(pState->out, azArg[0]);
  15503. return 1;
  15504. }
  15505. }
  15506. shellExecPrintf(pState->db, &rc,
  15507. /* Attach an in-memory database named 'recovery'. Create an indexed
  15508. ** cache of the sqlite_dbptr virtual table. */
  15509. "PRAGMA writable_schema = on;"
  15510. "ATTACH %Q AS recovery;"
  15511. "DROP TABLE IF EXISTS recovery.dbptr;"
  15512. "DROP TABLE IF EXISTS recovery.freelist;"
  15513. "DROP TABLE IF EXISTS recovery.map;"
  15514. "DROP TABLE IF EXISTS recovery.schema;"
  15515. "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
  15516. );
  15517. if( bFreelist ){
  15518. shellExec(pState->db, &rc,
  15519. "WITH trunk(pgno) AS ("
  15520. " SELECT shell_int32("
  15521. " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
  15522. " WHERE x>0"
  15523. " UNION"
  15524. " SELECT shell_int32("
  15525. " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
  15526. " FROM trunk WHERE x>0"
  15527. "),"
  15528. "freelist(data, n, freepgno) AS ("
  15529. " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
  15530. " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
  15531. " UNION ALL"
  15532. " SELECT data, n-1, shell_int32(data, 2+n) "
  15533. " FROM freelist WHERE n>=0"
  15534. ")"
  15535. "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
  15536. );
  15537. }
  15538. /* If this is an auto-vacuum database, add all pointer-map pages to
  15539. ** the freelist table. Do this regardless of whether or not
  15540. ** --freelist-corrupt was specified. */
  15541. shellExec(pState->db, &rc,
  15542. "WITH ptrmap(pgno) AS ("
  15543. " SELECT 2 WHERE shell_int32("
  15544. " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
  15545. " )"
  15546. " UNION ALL "
  15547. " SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
  15548. " FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
  15549. ")"
  15550. "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
  15551. );
  15552. shellExec(pState->db, &rc,
  15553. "CREATE TABLE recovery.dbptr("
  15554. " pgno, child, PRIMARY KEY(child, pgno)"
  15555. ") WITHOUT ROWID;"
  15556. "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
  15557. " SELECT * FROM sqlite_dbptr"
  15558. " WHERE pgno NOT IN freelist AND child NOT IN freelist;"
  15559. /* Delete any pointer to page 1. This ensures that page 1 is considered
  15560. ** a root page, regardless of how corrupt the db is. */
  15561. "DELETE FROM recovery.dbptr WHERE child = 1;"
  15562. /* Delete all pointers to any pages that have more than one pointer
  15563. ** to them. Such pages will be treated as root pages when recovering
  15564. ** data. */
  15565. "DELETE FROM recovery.dbptr WHERE child IN ("
  15566. " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
  15567. ");"
  15568. /* Create the "map" table that will (eventually) contain instructions
  15569. ** for dealing with each page in the db that contains one or more
  15570. ** records. */
  15571. "CREATE TABLE recovery.map("
  15572. "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
  15573. ");"
  15574. /* Populate table [map]. If there are circular loops of pages in the
  15575. ** database, the following adds all pages in such a loop to the map
  15576. ** as individual root pages. This could be handled better. */
  15577. "WITH pages(i, maxlen) AS ("
  15578. " SELECT page_count, ("
  15579. " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
  15580. " ) FROM pragma_page_count WHERE page_count>0"
  15581. " UNION ALL"
  15582. " SELECT i-1, ("
  15583. " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
  15584. " ) FROM pages WHERE i>=2"
  15585. ")"
  15586. "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
  15587. " SELECT i, maxlen, NULL, ("
  15588. " WITH p(orig, pgno, parent) AS ("
  15589. " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
  15590. " UNION "
  15591. " SELECT i, p.parent, "
  15592. " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
  15593. " )"
  15594. " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
  15595. ") "
  15596. "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
  15597. "UPDATE recovery.map AS o SET intkey = ("
  15598. " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
  15599. ");"
  15600. /* Extract data from page 1 and any linked pages into table
  15601. ** recovery.schema. With the same schema as an sqlite_schema table. */
  15602. "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
  15603. "INSERT INTO recovery.schema SELECT "
  15604. " max(CASE WHEN field=0 THEN value ELSE NULL END),"
  15605. " max(CASE WHEN field=1 THEN value ELSE NULL END),"
  15606. " max(CASE WHEN field=2 THEN value ELSE NULL END),"
  15607. " max(CASE WHEN field=3 THEN value ELSE NULL END),"
  15608. " max(CASE WHEN field=4 THEN value ELSE NULL END)"
  15609. "FROM sqlite_dbdata WHERE pgno IN ("
  15610. " SELECT pgno FROM recovery.map WHERE root=1"
  15611. ")"
  15612. "GROUP BY pgno, cell;"
  15613. "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
  15614. );
  15615. /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
  15616. ** CREATE TABLE statements that extracted from the existing schema. */
  15617. if( rc==SQLITE_OK ){
  15618. sqlite3_stmt *pStmt = 0;
  15619. /* ".recover" might output content in an order which causes immediate
  15620. ** foreign key constraints to be violated. So disable foreign-key
  15621. ** constraint enforcement to prevent problems when running the output
  15622. ** script. */
  15623. raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
  15624. raw_printf(pState->out, "BEGIN;\n");
  15625. raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
  15626. shellPrepare(pState->db, &rc,
  15627. "SELECT sql FROM recovery.schema "
  15628. "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
  15629. );
  15630. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  15631. const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
  15632. raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
  15633. &zCreateTable[12]
  15634. );
  15635. }
  15636. shellFinalize(&rc, pStmt);
  15637. }
  15638. /* Figure out if an orphan table will be required. And if so, how many
  15639. ** user columns it should contain */
  15640. shellPrepare(pState->db, &rc,
  15641. "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
  15642. , &pLoop
  15643. );
  15644. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
  15645. nOrphan = sqlite3_column_int(pLoop, 0);
  15646. }
  15647. shellFinalize(&rc, pLoop);
  15648. pLoop = 0;
  15649. shellPrepare(pState->db, &rc,
  15650. "SELECT pgno FROM recovery.map WHERE root=?", &pPages
  15651. );
  15652. shellPrepare(pState->db, &rc,
  15653. "SELECT max(field), group_concat(shell_escape_crnl(quote"
  15654. "(case when (? AND field<0) then NULL else value end)"
  15655. "), ', ')"
  15656. ", min(field) "
  15657. "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
  15658. "GROUP BY cell", &pCells
  15659. );
  15660. /* Loop through each root page. */
  15661. shellPrepare(pState->db, &rc,
  15662. "SELECT root, intkey, max(maxlen) FROM recovery.map"
  15663. " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
  15664. " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
  15665. ")", &pLoop
  15666. );
  15667. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
  15668. int iRoot = sqlite3_column_int(pLoop, 0);
  15669. int bIntkey = sqlite3_column_int(pLoop, 1);
  15670. int nCol = sqlite3_column_int(pLoop, 2);
  15671. int bNoop = 0;
  15672. RecoverTable *pTab;
  15673. assert( bIntkey==0 || bIntkey==1 );
  15674. pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
  15675. if( bNoop || rc ) continue;
  15676. if( pTab==0 ){
  15677. if( pOrphan==0 ){
  15678. pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
  15679. }
  15680. pTab = pOrphan;
  15681. if( pTab==0 ) break;
  15682. }
  15683. if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
  15684. raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
  15685. }
  15686. sqlite3_bind_int(pPages, 1, iRoot);
  15687. if( bRowids==0 && pTab->iPk<0 ){
  15688. sqlite3_bind_int(pCells, 1, 1);
  15689. }else{
  15690. sqlite3_bind_int(pCells, 1, 0);
  15691. }
  15692. sqlite3_bind_int(pCells, 3, pTab->iPk);
  15693. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
  15694. int iPgno = sqlite3_column_int(pPages, 0);
  15695. sqlite3_bind_int(pCells, 2, iPgno);
  15696. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
  15697. int nField = sqlite3_column_int(pCells, 0);
  15698. int iMin = sqlite3_column_int(pCells, 2);
  15699. const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
  15700. RecoverTable *pTab2 = pTab;
  15701. if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
  15702. if( pOrphan==0 ){
  15703. pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
  15704. }
  15705. pTab2 = pOrphan;
  15706. if( pTab2==0 ) break;
  15707. }
  15708. nField = nField+1;
  15709. if( pTab2==pOrphan ){
  15710. raw_printf(pState->out,
  15711. "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
  15712. pTab2->zQuoted, iRoot, iPgno, nField,
  15713. iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
  15714. );
  15715. }else{
  15716. raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
  15717. pTab2->zQuoted, pTab2->azlCol[nField], zVal
  15718. );
  15719. }
  15720. }
  15721. shellReset(&rc, pCells);
  15722. }
  15723. shellReset(&rc, pPages);
  15724. if( pTab!=pOrphan ) recoverFreeTable(pTab);
  15725. }
  15726. shellFinalize(&rc, pLoop);
  15727. shellFinalize(&rc, pPages);
  15728. shellFinalize(&rc, pCells);
  15729. recoverFreeTable(pOrphan);
  15730. /* The rest of the schema */
  15731. if( rc==SQLITE_OK ){
  15732. sqlite3_stmt *pStmt = 0;
  15733. shellPrepare(pState->db, &rc,
  15734. "SELECT sql, name FROM recovery.schema "
  15735. "WHERE sql NOT LIKE 'create table%'", &pStmt
  15736. );
  15737. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  15738. const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
  15739. if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
  15740. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  15741. char *zPrint = shellMPrintf(&rc,
  15742. "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
  15743. zName, zName, zSql
  15744. );
  15745. raw_printf(pState->out, "%s;\n", zPrint);
  15746. sqlite3_free(zPrint);
  15747. }else{
  15748. raw_printf(pState->out, "%s;\n", zSql);
  15749. }
  15750. }
  15751. shellFinalize(&rc, pStmt);
  15752. }
  15753. if( rc==SQLITE_OK ){
  15754. raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
  15755. raw_printf(pState->out, "COMMIT;\n");
  15756. }
  15757. sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
  15758. return rc;
  15759. }
  15760. #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
  15761. /*
  15762. ** If an input line begins with "." then invoke this routine to
  15763. ** process that line.
  15764. **
  15765. ** Return 1 on error, 2 to exit, and 0 otherwise.
  15766. */
  15767. static int do_meta_command(char *zLine, ShellState *p){
  15768. int h = 1;
  15769. int nArg = 0;
  15770. int n, c;
  15771. int rc = 0;
  15772. char *azArg[52];
  15773. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15774. if( p->expert.pExpert ){
  15775. expertFinish(p, 1, 0);
  15776. }
  15777. #endif
  15778. /* Parse the input line into tokens.
  15779. */
  15780. while( zLine[h] && nArg<ArraySize(azArg)-1 ){
  15781. while( IsSpace(zLine[h]) ){ h++; }
  15782. if( zLine[h]==0 ) break;
  15783. if( zLine[h]=='\'' || zLine[h]=='"' ){
  15784. int delim = zLine[h++];
  15785. azArg[nArg++] = &zLine[h];
  15786. while( zLine[h] && zLine[h]!=delim ){
  15787. if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
  15788. h++;
  15789. }
  15790. if( zLine[h]==delim ){
  15791. zLine[h++] = 0;
  15792. }
  15793. if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  15794. }else{
  15795. azArg[nArg++] = &zLine[h];
  15796. while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
  15797. if( zLine[h] ) zLine[h++] = 0;
  15798. resolve_backslashes(azArg[nArg-1]);
  15799. }
  15800. }
  15801. azArg[nArg] = 0;
  15802. /* Process the input line.
  15803. */
  15804. if( nArg==0 ) return 0; /* no tokens, no error */
  15805. n = strlen30(azArg[0]);
  15806. c = azArg[0][0];
  15807. clearTempFile(p);
  15808. #ifndef SQLITE_OMIT_AUTHORIZATION
  15809. if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
  15810. if( nArg!=2 ){
  15811. raw_printf(stderr, "Usage: .auth ON|OFF\n");
  15812. rc = 1;
  15813. goto meta_command_exit;
  15814. }
  15815. open_db(p, 0);
  15816. if( booleanValue(azArg[1]) ){
  15817. sqlite3_set_authorizer(p->db, shellAuth, p);
  15818. }else{
  15819. sqlite3_set_authorizer(p->db, 0, 0);
  15820. }
  15821. }else
  15822. #endif
  15823. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  15824. if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
  15825. open_db(p, 0);
  15826. rc = arDotCommand(p, 0, azArg, nArg);
  15827. }else
  15828. #endif
  15829. if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
  15830. || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
  15831. ){
  15832. const char *zDestFile = 0;
  15833. const char *zDb = 0;
  15834. sqlite3 *pDest;
  15835. sqlite3_backup *pBackup;
  15836. int j;
  15837. int bAsync = 0;
  15838. const char *zVfs = 0;
  15839. for(j=1; j<nArg; j++){
  15840. const char *z = azArg[j];
  15841. if( z[0]=='-' ){
  15842. if( z[1]=='-' ) z++;
  15843. if( strcmp(z, "-append")==0 ){
  15844. zVfs = "apndvfs";
  15845. }else
  15846. if( strcmp(z, "-async")==0 ){
  15847. bAsync = 1;
  15848. }else
  15849. {
  15850. utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
  15851. return 1;
  15852. }
  15853. }else if( zDestFile==0 ){
  15854. zDestFile = azArg[j];
  15855. }else if( zDb==0 ){
  15856. zDb = zDestFile;
  15857. zDestFile = azArg[j];
  15858. }else{
  15859. raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
  15860. return 1;
  15861. }
  15862. }
  15863. if( zDestFile==0 ){
  15864. raw_printf(stderr, "missing FILENAME argument on .backup\n");
  15865. return 1;
  15866. }
  15867. if( zDb==0 ) zDb = "main";
  15868. rc = sqlite3_open_v2(zDestFile, &pDest,
  15869. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
  15870. if( rc!=SQLITE_OK ){
  15871. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  15872. close_db(pDest);
  15873. return 1;
  15874. }
  15875. if( bAsync ){
  15876. sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
  15877. 0, 0, 0);
  15878. }
  15879. open_db(p, 0);
  15880. pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  15881. if( pBackup==0 ){
  15882. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  15883. close_db(pDest);
  15884. return 1;
  15885. }
  15886. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  15887. sqlite3_backup_finish(pBackup);
  15888. if( rc==SQLITE_DONE ){
  15889. rc = 0;
  15890. }else{
  15891. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  15892. rc = 1;
  15893. }
  15894. close_db(pDest);
  15895. }else
  15896. if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
  15897. if( nArg==2 ){
  15898. bail_on_error = booleanValue(azArg[1]);
  15899. }else{
  15900. raw_printf(stderr, "Usage: .bail on|off\n");
  15901. rc = 1;
  15902. }
  15903. }else
  15904. if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
  15905. if( nArg==2 ){
  15906. if( booleanValue(azArg[1]) ){
  15907. setBinaryMode(p->out, 1);
  15908. }else{
  15909. setTextMode(p->out, 1);
  15910. }
  15911. }else{
  15912. raw_printf(stderr, "Usage: .binary on|off\n");
  15913. rc = 1;
  15914. }
  15915. }else
  15916. if( c=='c' && strcmp(azArg[0],"cd")==0 ){
  15917. if( nArg==2 ){
  15918. #if defined(_WIN32) || defined(WIN32)
  15919. wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
  15920. rc = !SetCurrentDirectoryW(z);
  15921. sqlite3_free(z);
  15922. #else
  15923. rc = chdir(azArg[1]);
  15924. #endif
  15925. if( rc ){
  15926. utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
  15927. rc = 1;
  15928. }
  15929. }else{
  15930. raw_printf(stderr, "Usage: .cd DIRECTORY\n");
  15931. rc = 1;
  15932. }
  15933. }else
  15934. /* The undocumented ".breakpoint" command causes a call to the no-op
  15935. ** routine named test_breakpoint().
  15936. */
  15937. if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
  15938. test_breakpoint();
  15939. }else
  15940. if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
  15941. if( nArg==2 ){
  15942. setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
  15943. }else{
  15944. raw_printf(stderr, "Usage: .changes on|off\n");
  15945. rc = 1;
  15946. }
  15947. }else
  15948. /* Cancel output redirection, if it is currently set (by .testcase)
  15949. ** Then read the content of the testcase-out.txt file and compare against
  15950. ** azArg[1]. If there are differences, report an error and exit.
  15951. */
  15952. if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
  15953. char *zRes = 0;
  15954. output_reset(p);
  15955. if( nArg!=2 ){
  15956. raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
  15957. rc = 2;
  15958. }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
  15959. raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
  15960. rc = 2;
  15961. }else if( testcase_glob(azArg[1],zRes)==0 ){
  15962. utf8_printf(stderr,
  15963. "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
  15964. p->zTestcase, azArg[1], zRes);
  15965. rc = 1;
  15966. }else{
  15967. utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
  15968. p->nCheck++;
  15969. }
  15970. sqlite3_free(zRes);
  15971. }else
  15972. if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
  15973. if( nArg==2 ){
  15974. tryToClone(p, azArg[1]);
  15975. }else{
  15976. raw_printf(stderr, "Usage: .clone FILENAME\n");
  15977. rc = 1;
  15978. }
  15979. }else
  15980. if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
  15981. ShellState data;
  15982. char *zErrMsg = 0;
  15983. open_db(p, 0);
  15984. memcpy(&data, p, sizeof(data));
  15985. data.showHeader = 0;
  15986. data.cMode = data.mode = MODE_List;
  15987. sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
  15988. data.cnt = 0;
  15989. sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
  15990. callback, &data, &zErrMsg);
  15991. if( zErrMsg ){
  15992. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  15993. sqlite3_free(zErrMsg);
  15994. rc = 1;
  15995. }
  15996. }else
  15997. if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
  15998. static const struct DbConfigChoices {
  15999. const char *zName;
  16000. int op;
  16001. } aDbConfig[] = {
  16002. { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
  16003. { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL },
  16004. { "dqs_dml", SQLITE_DBCONFIG_DQS_DML },
  16005. { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
  16006. { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
  16007. { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
  16008. { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW },
  16009. { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
  16010. { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE },
  16011. { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT },
  16012. { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
  16013. { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
  16014. { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
  16015. { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
  16016. { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
  16017. { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
  16018. };
  16019. int ii, v;
  16020. open_db(p, 0);
  16021. for(ii=0; ii<ArraySize(aDbConfig); ii++){
  16022. if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
  16023. if( nArg>=3 ){
  16024. sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
  16025. }
  16026. sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
  16027. utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
  16028. if( nArg>1 ) break;
  16029. }
  16030. if( nArg>1 && ii==ArraySize(aDbConfig) ){
  16031. utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
  16032. utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
  16033. }
  16034. }else
  16035. if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
  16036. rc = shell_dbinfo_command(p, nArg, azArg);
  16037. }else
  16038. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
  16039. if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
  16040. open_db(p, 0);
  16041. rc = recoverDatabaseCmd(p, nArg, azArg);
  16042. }else
  16043. #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
  16044. if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
  16045. char *zLike = 0;
  16046. char *zSql;
  16047. int i;
  16048. int savedShowHeader = p->showHeader;
  16049. int savedShellFlags = p->shellFlgs;
  16050. ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
  16051. for(i=1; i<nArg; i++){
  16052. if( azArg[i][0]=='-' ){
  16053. const char *z = azArg[i]+1;
  16054. if( z[0]=='-' ) z++;
  16055. if( strcmp(z,"preserve-rowids")==0 ){
  16056. #ifdef SQLITE_OMIT_VIRTUALTABLE
  16057. raw_printf(stderr, "The --preserve-rowids option is not compatible"
  16058. " with SQLITE_OMIT_VIRTUALTABLE\n");
  16059. rc = 1;
  16060. sqlite3_free(zLike);
  16061. goto meta_command_exit;
  16062. #else
  16063. ShellSetFlag(p, SHFLG_PreserveRowid);
  16064. #endif
  16065. }else
  16066. if( strcmp(z,"newlines")==0 ){
  16067. ShellSetFlag(p, SHFLG_Newlines);
  16068. }else
  16069. {
  16070. raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
  16071. rc = 1;
  16072. sqlite3_free(zLike);
  16073. goto meta_command_exit;
  16074. }
  16075. }else if( zLike ){
  16076. zLike = sqlite3_mprintf("%z OR name LIKE %Q ESCAPE '\\'",
  16077. zLike, azArg[i]);
  16078. }else{
  16079. zLike = sqlite3_mprintf("name LIKE %Q ESCAPE '\\'", azArg[i]);
  16080. }
  16081. }
  16082. open_db(p, 0);
  16083. /* When playing back a "dump", the content might appear in an order
  16084. ** which causes immediate foreign key constraints to be violated.
  16085. ** So disable foreign-key constraint enforcement to prevent problems. */
  16086. raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
  16087. raw_printf(p->out, "BEGIN TRANSACTION;\n");
  16088. p->writableSchema = 0;
  16089. p->showHeader = 0;
  16090. /* Set writable_schema=ON since doing so forces SQLite to initialize
  16091. ** as much of the schema as it can even if the sqlite_schema table is
  16092. ** corrupt. */
  16093. sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
  16094. p->nErr = 0;
  16095. if( zLike==0 ) zLike = sqlite3_mprintf("true");
  16096. zSql = sqlite3_mprintf(
  16097. "SELECT name, type, sql FROM sqlite_schema "
  16098. "WHERE (%s) AND type=='table'"
  16099. " AND sql NOT NULL"
  16100. " ORDER BY tbl_name='sqlite_sequence', rowid",
  16101. zLike
  16102. );
  16103. run_schema_dump_query(p,zSql);
  16104. sqlite3_free(zSql);
  16105. zSql = sqlite3_mprintf(
  16106. "SELECT sql FROM sqlite_schema "
  16107. "WHERE (%s) AND sql NOT NULL"
  16108. " AND type IN ('index','trigger','view')",
  16109. zLike
  16110. );
  16111. run_table_dump_query(p, zSql);
  16112. sqlite3_free(zSql);
  16113. sqlite3_free(zLike);
  16114. if( p->writableSchema ){
  16115. raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
  16116. p->writableSchema = 0;
  16117. }
  16118. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  16119. sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
  16120. raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
  16121. p->showHeader = savedShowHeader;
  16122. p->shellFlgs = savedShellFlags;
  16123. }else
  16124. if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
  16125. if( nArg==2 ){
  16126. setOrClearFlag(p, SHFLG_Echo, azArg[1]);
  16127. }else{
  16128. raw_printf(stderr, "Usage: .echo on|off\n");
  16129. rc = 1;
  16130. }
  16131. }else
  16132. if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
  16133. if( nArg==2 ){
  16134. p->autoEQPtest = 0;
  16135. if( p->autoEQPtrace ){
  16136. if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
  16137. p->autoEQPtrace = 0;
  16138. }
  16139. if( strcmp(azArg[1],"full")==0 ){
  16140. p->autoEQP = AUTOEQP_full;
  16141. }else if( strcmp(azArg[1],"trigger")==0 ){
  16142. p->autoEQP = AUTOEQP_trigger;
  16143. #ifdef SQLITE_DEBUG
  16144. }else if( strcmp(azArg[1],"test")==0 ){
  16145. p->autoEQP = AUTOEQP_on;
  16146. p->autoEQPtest = 1;
  16147. }else if( strcmp(azArg[1],"trace")==0 ){
  16148. p->autoEQP = AUTOEQP_full;
  16149. p->autoEQPtrace = 1;
  16150. open_db(p, 0);
  16151. sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
  16152. sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
  16153. #endif
  16154. }else{
  16155. p->autoEQP = (u8)booleanValue(azArg[1]);
  16156. }
  16157. }else{
  16158. raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
  16159. rc = 1;
  16160. }
  16161. }else
  16162. if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
  16163. if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
  16164. rc = 2;
  16165. }else
  16166. /* The ".explain" command is automatic now. It is largely pointless. It
  16167. ** retained purely for backwards compatibility */
  16168. if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
  16169. int val = 1;
  16170. if( nArg>=2 ){
  16171. if( strcmp(azArg[1],"auto")==0 ){
  16172. val = 99;
  16173. }else{
  16174. val = booleanValue(azArg[1]);
  16175. }
  16176. }
  16177. if( val==1 && p->mode!=MODE_Explain ){
  16178. p->normalMode = p->mode;
  16179. p->mode = MODE_Explain;
  16180. p->autoExplain = 0;
  16181. }else if( val==0 ){
  16182. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  16183. p->autoExplain = 0;
  16184. }else if( val==99 ){
  16185. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  16186. p->autoExplain = 1;
  16187. }
  16188. }else
  16189. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16190. if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
  16191. open_db(p, 0);
  16192. expertDotCommand(p, azArg, nArg);
  16193. }else
  16194. #endif
  16195. if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
  16196. static const struct {
  16197. const char *zCtrlName; /* Name of a test-control option */
  16198. int ctrlCode; /* Integer code for that option */
  16199. const char *zUsage; /* Usage notes */
  16200. } aCtrl[] = {
  16201. { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" },
  16202. { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" },
  16203. /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
  16204. { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" },
  16205. { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" },
  16206. /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
  16207. { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" },
  16208. { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" },
  16209. { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" },
  16210. { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" },
  16211. };
  16212. int filectrl = -1;
  16213. int iCtrl = -1;
  16214. sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */
  16215. int isOk = 0; /* 0: usage 1: %lld 2: no-result */
  16216. int n2, i;
  16217. const char *zCmd = 0;
  16218. const char *zSchema = 0;
  16219. open_db(p, 0);
  16220. zCmd = nArg>=2 ? azArg[1] : "help";
  16221. if( zCmd[0]=='-'
  16222. && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
  16223. && nArg>=4
  16224. ){
  16225. zSchema = azArg[2];
  16226. for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
  16227. nArg -= 2;
  16228. zCmd = azArg[1];
  16229. }
  16230. /* The argument can optionally begin with "-" or "--" */
  16231. if( zCmd[0]=='-' && zCmd[1] ){
  16232. zCmd++;
  16233. if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
  16234. }
  16235. /* --help lists all file-controls */
  16236. if( strcmp(zCmd,"help")==0 ){
  16237. utf8_printf(p->out, "Available file-controls:\n");
  16238. for(i=0; i<ArraySize(aCtrl); i++){
  16239. utf8_printf(p->out, " .filectrl %s %s\n",
  16240. aCtrl[i].zCtrlName, aCtrl[i].zUsage);
  16241. }
  16242. rc = 1;
  16243. goto meta_command_exit;
  16244. }
  16245. /* convert filectrl text option to value. allow any unique prefix
  16246. ** of the option name, or a numerical value. */
  16247. n2 = strlen30(zCmd);
  16248. for(i=0; i<ArraySize(aCtrl); i++){
  16249. if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
  16250. if( filectrl<0 ){
  16251. filectrl = aCtrl[i].ctrlCode;
  16252. iCtrl = i;
  16253. }else{
  16254. utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
  16255. "Use \".filectrl --help\" for help\n", zCmd);
  16256. rc = 1;
  16257. goto meta_command_exit;
  16258. }
  16259. }
  16260. }
  16261. if( filectrl<0 ){
  16262. utf8_printf(stderr,"Error: unknown file-control: %s\n"
  16263. "Use \".filectrl --help\" for help\n", zCmd);
  16264. }else{
  16265. switch(filectrl){
  16266. case SQLITE_FCNTL_SIZE_LIMIT: {
  16267. if( nArg!=2 && nArg!=3 ) break;
  16268. iRes = nArg==3 ? integerValue(azArg[2]) : -1;
  16269. sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
  16270. isOk = 1;
  16271. break;
  16272. }
  16273. case SQLITE_FCNTL_LOCK_TIMEOUT:
  16274. case SQLITE_FCNTL_CHUNK_SIZE: {
  16275. int x;
  16276. if( nArg!=3 ) break;
  16277. x = (int)integerValue(azArg[2]);
  16278. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  16279. isOk = 2;
  16280. break;
  16281. }
  16282. case SQLITE_FCNTL_PERSIST_WAL:
  16283. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  16284. int x;
  16285. if( nArg!=2 && nArg!=3 ) break;
  16286. x = nArg==3 ? booleanValue(azArg[2]) : -1;
  16287. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  16288. iRes = x;
  16289. isOk = 1;
  16290. break;
  16291. }
  16292. case SQLITE_FCNTL_HAS_MOVED: {
  16293. int x;
  16294. if( nArg!=2 ) break;
  16295. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  16296. iRes = x;
  16297. isOk = 1;
  16298. break;
  16299. }
  16300. case SQLITE_FCNTL_TEMPFILENAME: {
  16301. char *z = 0;
  16302. if( nArg!=2 ) break;
  16303. sqlite3_file_control(p->db, zSchema, filectrl, &z);
  16304. if( z ){
  16305. utf8_printf(p->out, "%s\n", z);
  16306. sqlite3_free(z);
  16307. }
  16308. isOk = 2;
  16309. break;
  16310. }
  16311. case SQLITE_FCNTL_RESERVE_BYTES: {
  16312. int x;
  16313. if( nArg>=3 ){
  16314. x = atoi(azArg[2]);
  16315. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  16316. }
  16317. x = -1;
  16318. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  16319. utf8_printf(p->out,"%d\n", x);
  16320. isOk = 2;
  16321. break;
  16322. }
  16323. }
  16324. }
  16325. if( isOk==0 && iCtrl>=0 ){
  16326. utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
  16327. rc = 1;
  16328. }else if( isOk==1 ){
  16329. char zBuf[100];
  16330. sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
  16331. raw_printf(p->out, "%s\n", zBuf);
  16332. }
  16333. }else
  16334. if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
  16335. ShellState data;
  16336. char *zErrMsg = 0;
  16337. int doStats = 0;
  16338. memcpy(&data, p, sizeof(data));
  16339. data.showHeader = 0;
  16340. data.cMode = data.mode = MODE_Semi;
  16341. if( nArg==2 && optionMatch(azArg[1], "indent") ){
  16342. data.cMode = data.mode = MODE_Pretty;
  16343. nArg = 1;
  16344. }
  16345. if( nArg!=1 ){
  16346. raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
  16347. rc = 1;
  16348. goto meta_command_exit;
  16349. }
  16350. open_db(p, 0);
  16351. rc = sqlite3_exec(p->db,
  16352. "SELECT sql FROM"
  16353. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  16354. " FROM sqlite_schema UNION ALL"
  16355. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
  16356. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  16357. "ORDER BY rowid",
  16358. callback, &data, &zErrMsg
  16359. );
  16360. if( rc==SQLITE_OK ){
  16361. sqlite3_stmt *pStmt;
  16362. rc = sqlite3_prepare_v2(p->db,
  16363. "SELECT rowid FROM sqlite_schema"
  16364. " WHERE name GLOB 'sqlite_stat[134]'",
  16365. -1, &pStmt, 0);
  16366. doStats = sqlite3_step(pStmt)==SQLITE_ROW;
  16367. sqlite3_finalize(pStmt);
  16368. }
  16369. if( doStats==0 ){
  16370. raw_printf(p->out, "/* No STAT tables available */\n");
  16371. }else{
  16372. raw_printf(p->out, "ANALYZE sqlite_schema;\n");
  16373. sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_schema'",
  16374. callback, &data, &zErrMsg);
  16375. data.cMode = data.mode = MODE_Insert;
  16376. data.zDestTable = "sqlite_stat1";
  16377. shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
  16378. data.zDestTable = "sqlite_stat4";
  16379. shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
  16380. raw_printf(p->out, "ANALYZE sqlite_schema;\n");
  16381. }
  16382. }else
  16383. if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
  16384. if( nArg==2 ){
  16385. p->showHeader = booleanValue(azArg[1]);
  16386. p->shellFlgs |= SHFLG_HeaderSet;
  16387. }else{
  16388. raw_printf(stderr, "Usage: .headers on|off\n");
  16389. rc = 1;
  16390. }
  16391. }else
  16392. if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  16393. if( nArg>=2 ){
  16394. n = showHelp(p->out, azArg[1]);
  16395. if( n==0 ){
  16396. utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
  16397. }
  16398. }else{
  16399. showHelp(p->out, 0);
  16400. }
  16401. }else
  16402. if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
  16403. char *zTable = 0; /* Insert data into this table */
  16404. char *zFile = 0; /* Name of file to extra content from */
  16405. sqlite3_stmt *pStmt = NULL; /* A statement */
  16406. int nCol; /* Number of columns in the table */
  16407. int nByte; /* Number of bytes in an SQL string */
  16408. int i, j; /* Loop counters */
  16409. int needCommit; /* True to COMMIT or ROLLBACK at end */
  16410. int nSep; /* Number of bytes in p->colSeparator[] */
  16411. char *zSql; /* An SQL statement */
  16412. ImportCtx sCtx; /* Reader context */
  16413. char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
  16414. int eVerbose = 0; /* Larger for more console output */
  16415. int nSkip = 0; /* Initial lines to skip */
  16416. int useOutputMode = 1; /* Use output mode to determine separators */
  16417. memset(&sCtx, 0, sizeof(sCtx));
  16418. if( p->mode==MODE_Ascii ){
  16419. xRead = ascii_read_one_field;
  16420. }else{
  16421. xRead = csv_read_one_field;
  16422. }
  16423. for(i=1; i<nArg; i++){
  16424. char *z = azArg[i];
  16425. if( z[0]=='-' && z[1]=='-' ) z++;
  16426. if( z[0]!='-' ){
  16427. if( zFile==0 ){
  16428. zFile = z;
  16429. }else if( zTable==0 ){
  16430. zTable = z;
  16431. }else{
  16432. utf8_printf(p->out, "ERROR: extra argument: \"%s\". Usage:\n", z);
  16433. showHelp(p->out, "import");
  16434. rc = 1;
  16435. goto meta_command_exit;
  16436. }
  16437. }else if( strcmp(z,"-v")==0 ){
  16438. eVerbose++;
  16439. }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
  16440. nSkip = integerValue(azArg[++i]);
  16441. }else if( strcmp(z,"-ascii")==0 ){
  16442. sCtx.cColSep = SEP_Unit[0];
  16443. sCtx.cRowSep = SEP_Record[0];
  16444. xRead = ascii_read_one_field;
  16445. useOutputMode = 0;
  16446. }else if( strcmp(z,"-csv")==0 ){
  16447. sCtx.cColSep = ',';
  16448. sCtx.cRowSep = '\n';
  16449. xRead = csv_read_one_field;
  16450. useOutputMode = 0;
  16451. }else{
  16452. utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", z);
  16453. showHelp(p->out, "import");
  16454. rc = 1;
  16455. goto meta_command_exit;
  16456. }
  16457. }
  16458. if( zTable==0 ){
  16459. utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
  16460. zFile==0 ? "FILE" : "TABLE");
  16461. showHelp(p->out, "import");
  16462. rc = 1;
  16463. goto meta_command_exit;
  16464. }
  16465. seenInterrupt = 0;
  16466. open_db(p, 0);
  16467. if( useOutputMode ){
  16468. /* If neither the --csv or --ascii options are specified, then set
  16469. ** the column and row separator characters from the output mode. */
  16470. nSep = strlen30(p->colSeparator);
  16471. if( nSep==0 ){
  16472. raw_printf(stderr,
  16473. "Error: non-null column separator required for import\n");
  16474. rc = 1;
  16475. goto meta_command_exit;
  16476. }
  16477. if( nSep>1 ){
  16478. raw_printf(stderr,
  16479. "Error: multi-character column separators not allowed"
  16480. " for import\n");
  16481. rc = 1;
  16482. goto meta_command_exit;
  16483. }
  16484. nSep = strlen30(p->rowSeparator);
  16485. if( nSep==0 ){
  16486. raw_printf(stderr,
  16487. "Error: non-null row separator required for import\n");
  16488. rc = 1;
  16489. goto meta_command_exit;
  16490. }
  16491. if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
  16492. /* When importing CSV (only), if the row separator is set to the
  16493. ** default output row separator, change it to the default input
  16494. ** row separator. This avoids having to maintain different input
  16495. ** and output row separators. */
  16496. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  16497. nSep = strlen30(p->rowSeparator);
  16498. }
  16499. if( nSep>1 ){
  16500. raw_printf(stderr, "Error: multi-character row separators not allowed"
  16501. " for import\n");
  16502. rc = 1;
  16503. goto meta_command_exit;
  16504. }
  16505. sCtx.cColSep = p->colSeparator[0];
  16506. sCtx.cRowSep = p->rowSeparator[0];
  16507. }
  16508. sCtx.zFile = zFile;
  16509. sCtx.nLine = 1;
  16510. if( sCtx.zFile[0]=='|' ){
  16511. #ifdef SQLITE_OMIT_POPEN
  16512. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  16513. rc = 1;
  16514. goto meta_command_exit;
  16515. #else
  16516. sCtx.in = popen(sCtx.zFile+1, "r");
  16517. sCtx.zFile = "<pipe>";
  16518. sCtx.xCloser = pclose;
  16519. #endif
  16520. }else{
  16521. sCtx.in = fopen(sCtx.zFile, "rb");
  16522. sCtx.xCloser = fclose;
  16523. }
  16524. if( sCtx.in==0 ){
  16525. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  16526. rc = 1;
  16527. goto meta_command_exit;
  16528. }
  16529. if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
  16530. char zSep[2];
  16531. zSep[1] = 0;
  16532. zSep[0] = sCtx.cColSep;
  16533. utf8_printf(p->out, "Column separator ");
  16534. output_c_string(p->out, zSep);
  16535. utf8_printf(p->out, ", row separator ");
  16536. zSep[0] = sCtx.cRowSep;
  16537. output_c_string(p->out, zSep);
  16538. utf8_printf(p->out, "\n");
  16539. }
  16540. while( (nSkip--)>0 ){
  16541. while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
  16542. }
  16543. zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
  16544. if( zSql==0 ){
  16545. import_cleanup(&sCtx);
  16546. shell_out_of_memory();
  16547. }
  16548. nByte = strlen30(zSql);
  16549. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  16550. import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
  16551. if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
  16552. char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
  16553. char cSep = '(';
  16554. while( xRead(&sCtx) ){
  16555. zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
  16556. cSep = ',';
  16557. if( sCtx.cTerm!=sCtx.cColSep ) break;
  16558. }
  16559. if( cSep=='(' ){
  16560. sqlite3_free(zCreate);
  16561. import_cleanup(&sCtx);
  16562. utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
  16563. rc = 1;
  16564. goto meta_command_exit;
  16565. }
  16566. zCreate = sqlite3_mprintf("%z\n)", zCreate);
  16567. if( eVerbose>=1 ){
  16568. utf8_printf(p->out, "%s\n", zCreate);
  16569. }
  16570. rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
  16571. sqlite3_free(zCreate);
  16572. if( rc ){
  16573. utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
  16574. sqlite3_errmsg(p->db));
  16575. import_cleanup(&sCtx);
  16576. rc = 1;
  16577. goto meta_command_exit;
  16578. }
  16579. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  16580. }
  16581. sqlite3_free(zSql);
  16582. if( rc ){
  16583. if (pStmt) sqlite3_finalize(pStmt);
  16584. utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
  16585. import_cleanup(&sCtx);
  16586. rc = 1;
  16587. goto meta_command_exit;
  16588. }
  16589. nCol = sqlite3_column_count(pStmt);
  16590. sqlite3_finalize(pStmt);
  16591. pStmt = 0;
  16592. if( nCol==0 ) return 0; /* no columns, no error */
  16593. zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
  16594. if( zSql==0 ){
  16595. import_cleanup(&sCtx);
  16596. shell_out_of_memory();
  16597. }
  16598. sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
  16599. j = strlen30(zSql);
  16600. for(i=1; i<nCol; i++){
  16601. zSql[j++] = ',';
  16602. zSql[j++] = '?';
  16603. }
  16604. zSql[j++] = ')';
  16605. zSql[j] = 0;
  16606. if( eVerbose>=2 ){
  16607. utf8_printf(p->out, "Insert using: %s\n", zSql);
  16608. }
  16609. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  16610. sqlite3_free(zSql);
  16611. if( rc ){
  16612. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  16613. if (pStmt) sqlite3_finalize(pStmt);
  16614. import_cleanup(&sCtx);
  16615. rc = 1;
  16616. goto meta_command_exit;
  16617. }
  16618. needCommit = sqlite3_get_autocommit(p->db);
  16619. if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
  16620. do{
  16621. int startLine = sCtx.nLine;
  16622. for(i=0; i<nCol; i++){
  16623. char *z = xRead(&sCtx);
  16624. /*
  16625. ** Did we reach end-of-file before finding any columns?
  16626. ** If so, stop instead of NULL filling the remaining columns.
  16627. */
  16628. if( z==0 && i==0 ) break;
  16629. /*
  16630. ** Did we reach end-of-file OR end-of-line before finding any
  16631. ** columns in ASCII mode? If so, stop instead of NULL filling
  16632. ** the remaining columns.
  16633. */
  16634. if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
  16635. sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
  16636. if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
  16637. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  16638. "filling the rest with NULL\n",
  16639. sCtx.zFile, startLine, nCol, i+1);
  16640. i += 2;
  16641. while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
  16642. }
  16643. }
  16644. if( sCtx.cTerm==sCtx.cColSep ){
  16645. do{
  16646. xRead(&sCtx);
  16647. i++;
  16648. }while( sCtx.cTerm==sCtx.cColSep );
  16649. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  16650. "extras ignored\n",
  16651. sCtx.zFile, startLine, nCol, i);
  16652. }
  16653. if( i>=nCol ){
  16654. sqlite3_step(pStmt);
  16655. rc = sqlite3_reset(pStmt);
  16656. if( rc!=SQLITE_OK ){
  16657. utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
  16658. startLine, sqlite3_errmsg(p->db));
  16659. sCtx.nErr++;
  16660. }else{
  16661. sCtx.nRow++;
  16662. }
  16663. }
  16664. }while( sCtx.cTerm!=EOF );
  16665. import_cleanup(&sCtx);
  16666. sqlite3_finalize(pStmt);
  16667. if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
  16668. if( eVerbose>0 ){
  16669. utf8_printf(p->out,
  16670. "Added %d rows with %d errors using %d lines of input\n",
  16671. sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
  16672. }
  16673. }else
  16674. #ifndef SQLITE_UNTESTABLE
  16675. if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
  16676. char *zSql;
  16677. char *zCollist = 0;
  16678. sqlite3_stmt *pStmt;
  16679. int tnum = 0;
  16680. int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */
  16681. int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
  16682. int i;
  16683. if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
  16684. utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
  16685. " .imposter off\n");
  16686. /* Also allowed, but not documented:
  16687. **
  16688. ** .imposter TABLE IMPOSTER
  16689. **
  16690. ** where TABLE is a WITHOUT ROWID table. In that case, the
  16691. ** imposter is another WITHOUT ROWID table with the columns in
  16692. ** storage order. */
  16693. rc = 1;
  16694. goto meta_command_exit;
  16695. }
  16696. open_db(p, 0);
  16697. if( nArg==2 ){
  16698. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
  16699. goto meta_command_exit;
  16700. }
  16701. zSql = sqlite3_mprintf(
  16702. "SELECT rootpage, 0 FROM sqlite_schema"
  16703. " WHERE name='%q' AND type='index'"
  16704. "UNION ALL "
  16705. "SELECT rootpage, 1 FROM sqlite_schema"
  16706. " WHERE name='%q' AND type='table'"
  16707. " AND sql LIKE '%%without%%rowid%%'",
  16708. azArg[1], azArg[1]
  16709. );
  16710. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  16711. sqlite3_free(zSql);
  16712. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  16713. tnum = sqlite3_column_int(pStmt, 0);
  16714. isWO = sqlite3_column_int(pStmt, 1);
  16715. }
  16716. sqlite3_finalize(pStmt);
  16717. zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
  16718. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  16719. sqlite3_free(zSql);
  16720. i = 0;
  16721. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  16722. char zLabel[20];
  16723. const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
  16724. i++;
  16725. if( zCol==0 ){
  16726. if( sqlite3_column_int(pStmt,1)==-1 ){
  16727. zCol = "_ROWID_";
  16728. }else{
  16729. sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
  16730. zCol = zLabel;
  16731. }
  16732. }
  16733. if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
  16734. lenPK = (int)strlen(zCollist);
  16735. }
  16736. if( zCollist==0 ){
  16737. zCollist = sqlite3_mprintf("\"%w\"", zCol);
  16738. }else{
  16739. zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
  16740. }
  16741. }
  16742. sqlite3_finalize(pStmt);
  16743. if( i==0 || tnum==0 ){
  16744. utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
  16745. rc = 1;
  16746. sqlite3_free(zCollist);
  16747. goto meta_command_exit;
  16748. }
  16749. if( lenPK==0 ) lenPK = 100000;
  16750. zSql = sqlite3_mprintf(
  16751. "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
  16752. azArg[2], zCollist, lenPK, zCollist);
  16753. sqlite3_free(zCollist);
  16754. rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
  16755. if( rc==SQLITE_OK ){
  16756. rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
  16757. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
  16758. if( rc ){
  16759. utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
  16760. }else{
  16761. utf8_printf(stdout, "%s;\n", zSql);
  16762. raw_printf(stdout,
  16763. "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
  16764. azArg[1], isWO ? "table" : "index"
  16765. );
  16766. }
  16767. }else{
  16768. raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
  16769. rc = 1;
  16770. }
  16771. sqlite3_free(zSql);
  16772. }else
  16773. #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
  16774. #ifdef SQLITE_ENABLE_IOTRACE
  16775. if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
  16776. SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
  16777. if( iotrace && iotrace!=stdout ) fclose(iotrace);
  16778. iotrace = 0;
  16779. if( nArg<2 ){
  16780. sqlite3IoTrace = 0;
  16781. }else if( strcmp(azArg[1], "-")==0 ){
  16782. sqlite3IoTrace = iotracePrintf;
  16783. iotrace = stdout;
  16784. }else{
  16785. iotrace = fopen(azArg[1], "w");
  16786. if( iotrace==0 ){
  16787. utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  16788. sqlite3IoTrace = 0;
  16789. rc = 1;
  16790. }else{
  16791. sqlite3IoTrace = iotracePrintf;
  16792. }
  16793. }
  16794. }else
  16795. #endif
  16796. if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
  16797. static const struct {
  16798. const char *zLimitName; /* Name of a limit */
  16799. int limitCode; /* Integer code for that limit */
  16800. } aLimit[] = {
  16801. { "length", SQLITE_LIMIT_LENGTH },
  16802. { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
  16803. { "column", SQLITE_LIMIT_COLUMN },
  16804. { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
  16805. { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
  16806. { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
  16807. { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
  16808. { "attached", SQLITE_LIMIT_ATTACHED },
  16809. { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
  16810. { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
  16811. { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
  16812. { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
  16813. };
  16814. int i, n2;
  16815. open_db(p, 0);
  16816. if( nArg==1 ){
  16817. for(i=0; i<ArraySize(aLimit); i++){
  16818. printf("%20s %d\n", aLimit[i].zLimitName,
  16819. sqlite3_limit(p->db, aLimit[i].limitCode, -1));
  16820. }
  16821. }else if( nArg>3 ){
  16822. raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
  16823. rc = 1;
  16824. goto meta_command_exit;
  16825. }else{
  16826. int iLimit = -1;
  16827. n2 = strlen30(azArg[1]);
  16828. for(i=0; i<ArraySize(aLimit); i++){
  16829. if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
  16830. if( iLimit<0 ){
  16831. iLimit = i;
  16832. }else{
  16833. utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
  16834. rc = 1;
  16835. goto meta_command_exit;
  16836. }
  16837. }
  16838. }
  16839. if( iLimit<0 ){
  16840. utf8_printf(stderr, "unknown limit: \"%s\"\n"
  16841. "enter \".limits\" with no arguments for a list.\n",
  16842. azArg[1]);
  16843. rc = 1;
  16844. goto meta_command_exit;
  16845. }
  16846. if( nArg==3 ){
  16847. sqlite3_limit(p->db, aLimit[iLimit].limitCode,
  16848. (int)integerValue(azArg[2]));
  16849. }
  16850. printf("%20s %d\n", aLimit[iLimit].zLimitName,
  16851. sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
  16852. }
  16853. }else
  16854. if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
  16855. open_db(p, 0);
  16856. lintDotCommand(p, azArg, nArg);
  16857. }else
  16858. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  16859. if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
  16860. const char *zFile, *zProc;
  16861. char *zErrMsg = 0;
  16862. if( nArg<2 ){
  16863. raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
  16864. rc = 1;
  16865. goto meta_command_exit;
  16866. }
  16867. zFile = azArg[1];
  16868. zProc = nArg>=3 ? azArg[2] : 0;
  16869. open_db(p, 0);
  16870. rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  16871. if( rc!=SQLITE_OK ){
  16872. utf8_printf(stderr, "Error: %s\n", zErrMsg);
  16873. sqlite3_free(zErrMsg);
  16874. rc = 1;
  16875. }
  16876. }else
  16877. #endif
  16878. if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
  16879. if( nArg!=2 ){
  16880. raw_printf(stderr, "Usage: .log FILENAME\n");
  16881. rc = 1;
  16882. }else{
  16883. const char *zFile = azArg[1];
  16884. output_file_close(p->pLog);
  16885. p->pLog = output_file_open(zFile, 0);
  16886. }
  16887. }else
  16888. if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
  16889. const char *zMode = nArg>=2 ? azArg[1] : "";
  16890. int n2 = strlen30(zMode);
  16891. int c2 = zMode[0];
  16892. if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
  16893. p->mode = MODE_Line;
  16894. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  16895. }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
  16896. p->mode = MODE_Column;
  16897. if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
  16898. p->showHeader = 1;
  16899. }
  16900. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  16901. }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
  16902. p->mode = MODE_List;
  16903. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
  16904. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  16905. }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
  16906. p->mode = MODE_Html;
  16907. }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
  16908. p->mode = MODE_Tcl;
  16909. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
  16910. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  16911. }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
  16912. p->mode = MODE_Csv;
  16913. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  16914. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  16915. }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
  16916. p->mode = MODE_List;
  16917. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
  16918. }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
  16919. p->mode = MODE_Insert;
  16920. set_table_name(p, nArg>=3 ? azArg[2] : "table");
  16921. }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
  16922. p->mode = MODE_Quote;
  16923. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  16924. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  16925. }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
  16926. p->mode = MODE_Ascii;
  16927. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
  16928. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
  16929. }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){
  16930. p->mode = MODE_Markdown;
  16931. }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){
  16932. p->mode = MODE_Table;
  16933. }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){
  16934. p->mode = MODE_Box;
  16935. }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){
  16936. p->mode = MODE_Json;
  16937. }else if( nArg==1 ){
  16938. raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
  16939. }else{
  16940. raw_printf(stderr, "Error: mode should be one of: "
  16941. "ascii box column csv html insert json line list markdown "
  16942. "quote table tabs tcl\n");
  16943. rc = 1;
  16944. }
  16945. p->cMode = p->mode;
  16946. }else
  16947. if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
  16948. if( nArg==2 ){
  16949. sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
  16950. "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
  16951. }else{
  16952. raw_printf(stderr, "Usage: .nullvalue STRING\n");
  16953. rc = 1;
  16954. }
  16955. }else
  16956. #ifdef SQLITE_DEBUG
  16957. if( c=='o' && strcmp(azArg[0],"oom")==0 ){
  16958. int i;
  16959. for(i=1; i<nArg; i++){
  16960. const char *z = azArg[i];
  16961. if( z[0]=='-' && z[1]=='-' ) z++;
  16962. if( strcmp(z,"-repeat")==0 ){
  16963. if( i==nArg-1 ){
  16964. raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]);
  16965. rc = 1;
  16966. }else{
  16967. oomRepeat = (int)integerValue(azArg[++i]);
  16968. }
  16969. }else if( IsDigit(z[0]) ){
  16970. oomCounter = (int)integerValue(azArg[i]);
  16971. }else{
  16972. raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]);
  16973. raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n");
  16974. rc = 1;
  16975. }
  16976. }
  16977. if( rc==0 ){
  16978. raw_printf(p->out, "oomCounter = %d\n", oomCounter);
  16979. raw_printf(p->out, "oomRepeat = %d\n", oomRepeat);
  16980. }
  16981. }else
  16982. #endif /* SQLITE_DEBUG */
  16983. if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
  16984. char *zNewFilename; /* Name of the database file to open */
  16985. int iName = 1; /* Index in azArg[] of the filename */
  16986. int newFlag = 0; /* True to delete file before opening */
  16987. /* Close the existing database */
  16988. session_close_all(p);
  16989. close_db(p->db);
  16990. p->db = 0;
  16991. p->zDbFilename = 0;
  16992. sqlite3_free(p->zFreeOnClose);
  16993. p->zFreeOnClose = 0;
  16994. p->openMode = SHELL_OPEN_UNSPEC;
  16995. p->openFlags = 0;
  16996. p->szMax = 0;
  16997. /* Check for command-line arguments */
  16998. for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
  16999. const char *z = azArg[iName];
  17000. if( optionMatch(z,"new") ){
  17001. newFlag = 1;
  17002. #ifdef SQLITE_HAVE_ZLIB
  17003. }else if( optionMatch(z, "zip") ){
  17004. p->openMode = SHELL_OPEN_ZIPFILE;
  17005. #endif
  17006. }else if( optionMatch(z, "append") ){
  17007. p->openMode = SHELL_OPEN_APPENDVFS;
  17008. }else if( optionMatch(z, "readonly") ){
  17009. p->openMode = SHELL_OPEN_READONLY;
  17010. }else if( optionMatch(z, "nofollow") ){
  17011. p->openFlags |= SQLITE_OPEN_NOFOLLOW;
  17012. #ifdef SQLITE_ENABLE_DESERIALIZE
  17013. }else if( optionMatch(z, "deserialize") ){
  17014. p->openMode = SHELL_OPEN_DESERIALIZE;
  17015. }else if( optionMatch(z, "hexdb") ){
  17016. p->openMode = SHELL_OPEN_HEXDB;
  17017. }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
  17018. p->szMax = integerValue(azArg[++iName]);
  17019. #endif /* SQLITE_ENABLE_DESERIALIZE */
  17020. }else if( z[0]=='-' ){
  17021. utf8_printf(stderr, "unknown option: %s\n", z);
  17022. rc = 1;
  17023. goto meta_command_exit;
  17024. }
  17025. }
  17026. /* If a filename is specified, try to open it first */
  17027. zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
  17028. if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
  17029. if( newFlag ) shellDeleteFile(zNewFilename);
  17030. p->zDbFilename = zNewFilename;
  17031. open_db(p, OPEN_DB_KEEPALIVE);
  17032. if( p->db==0 ){
  17033. utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
  17034. sqlite3_free(zNewFilename);
  17035. }else{
  17036. p->zFreeOnClose = zNewFilename;
  17037. }
  17038. }
  17039. if( p->db==0 ){
  17040. /* As a fall-back open a TEMP database */
  17041. p->zDbFilename = 0;
  17042. open_db(p, 0);
  17043. }
  17044. }else
  17045. if( (c=='o'
  17046. && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
  17047. || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
  17048. ){
  17049. const char *zFile = 0;
  17050. int bTxtMode = 0;
  17051. int i;
  17052. int eMode = 0;
  17053. int bBOM = 0;
  17054. int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */
  17055. if( c=='e' ){
  17056. eMode = 'x';
  17057. bOnce = 2;
  17058. }else if( strncmp(azArg[0],"once",n)==0 ){
  17059. bOnce = 1;
  17060. }
  17061. for(i=1; i<nArg; i++){
  17062. char *z = azArg[i];
  17063. if( z[0]=='-' ){
  17064. if( z[1]=='-' ) z++;
  17065. if( strcmp(z,"-bom")==0 ){
  17066. bBOM = 1;
  17067. }else if( c!='e' && strcmp(z,"-x")==0 ){
  17068. eMode = 'x'; /* spreadsheet */
  17069. }else if( c!='e' && strcmp(z,"-e")==0 ){
  17070. eMode = 'e'; /* text editor */
  17071. }else{
  17072. utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n",
  17073. azArg[i]);
  17074. showHelp(p->out, azArg[0]);
  17075. rc = 1;
  17076. goto meta_command_exit;
  17077. }
  17078. }else if( zFile==0 ){
  17079. zFile = z;
  17080. }else{
  17081. utf8_printf(p->out,"ERROR: extra parameter: \"%s\". Usage:\n",
  17082. azArg[i]);
  17083. showHelp(p->out, azArg[0]);
  17084. rc = 1;
  17085. goto meta_command_exit;
  17086. }
  17087. }
  17088. if( zFile==0 ) zFile = "stdout";
  17089. if( bOnce ){
  17090. p->outCount = 2;
  17091. }else{
  17092. p->outCount = 0;
  17093. }
  17094. output_reset(p);
  17095. #ifndef SQLITE_NOHAVE_SYSTEM
  17096. if( eMode=='e' || eMode=='x' ){
  17097. p->doXdgOpen = 1;
  17098. outputModePush(p);
  17099. if( eMode=='x' ){
  17100. /* spreadsheet mode. Output as CSV. */
  17101. newTempFile(p, "csv");
  17102. ShellClearFlag(p, SHFLG_Echo);
  17103. p->mode = MODE_Csv;
  17104. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  17105. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  17106. }else{
  17107. /* text editor mode */
  17108. newTempFile(p, "txt");
  17109. bTxtMode = 1;
  17110. }
  17111. zFile = p->zTempFile;
  17112. }
  17113. #endif /* SQLITE_NOHAVE_SYSTEM */
  17114. if( zFile[0]=='|' ){
  17115. #ifdef SQLITE_OMIT_POPEN
  17116. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  17117. rc = 1;
  17118. p->out = stdout;
  17119. #else
  17120. p->out = popen(zFile + 1, "w");
  17121. if( p->out==0 ){
  17122. utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
  17123. p->out = stdout;
  17124. rc = 1;
  17125. }else{
  17126. if( bBOM ) fprintf(p->out,"\357\273\277");
  17127. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  17128. }
  17129. #endif
  17130. }else{
  17131. p->out = output_file_open(zFile, bTxtMode);
  17132. if( p->out==0 ){
  17133. if( strcmp(zFile,"off")!=0 ){
  17134. utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
  17135. }
  17136. p->out = stdout;
  17137. rc = 1;
  17138. } else {
  17139. if( bBOM ) fprintf(p->out,"\357\273\277");
  17140. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  17141. }
  17142. }
  17143. }else
  17144. if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
  17145. open_db(p,0);
  17146. if( nArg<=1 ) goto parameter_syntax_error;
  17147. /* .parameter clear
  17148. ** Clear all bind parameters by dropping the TEMP table that holds them.
  17149. */
  17150. if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
  17151. sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
  17152. 0, 0, 0);
  17153. }else
  17154. /* .parameter list
  17155. ** List all bind parameters.
  17156. */
  17157. if( nArg==2 && strcmp(azArg[1],"list")==0 ){
  17158. sqlite3_stmt *pStmt = 0;
  17159. int rx;
  17160. int len = 0;
  17161. rx = sqlite3_prepare_v2(p->db,
  17162. "SELECT max(length(key)) "
  17163. "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
  17164. if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
  17165. len = sqlite3_column_int(pStmt, 0);
  17166. if( len>40 ) len = 40;
  17167. }
  17168. sqlite3_finalize(pStmt);
  17169. pStmt = 0;
  17170. if( len ){
  17171. rx = sqlite3_prepare_v2(p->db,
  17172. "SELECT key, quote(value) "
  17173. "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
  17174. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  17175. utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
  17176. sqlite3_column_text(pStmt,1));
  17177. }
  17178. sqlite3_finalize(pStmt);
  17179. }
  17180. }else
  17181. /* .parameter init
  17182. ** Make sure the TEMP table used to hold bind parameters exists.
  17183. ** Create it if necessary.
  17184. */
  17185. if( nArg==2 && strcmp(azArg[1],"init")==0 ){
  17186. bind_table_init(p);
  17187. }else
  17188. /* .parameter set NAME VALUE
  17189. ** Set or reset a bind parameter. NAME should be the full parameter
  17190. ** name exactly as it appears in the query. (ex: $abc, @def). The
  17191. ** VALUE can be in either SQL literal notation, or if not it will be
  17192. ** understood to be a text string.
  17193. */
  17194. if( nArg==4 && strcmp(azArg[1],"set")==0 ){
  17195. int rx;
  17196. char *zSql;
  17197. sqlite3_stmt *pStmt;
  17198. const char *zKey = azArg[2];
  17199. const char *zValue = azArg[3];
  17200. bind_table_init(p);
  17201. zSql = sqlite3_mprintf(
  17202. "REPLACE INTO temp.sqlite_parameters(key,value)"
  17203. "VALUES(%Q,%s);", zKey, zValue);
  17204. if( zSql==0 ) shell_out_of_memory();
  17205. pStmt = 0;
  17206. rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  17207. sqlite3_free(zSql);
  17208. if( rx!=SQLITE_OK ){
  17209. sqlite3_finalize(pStmt);
  17210. pStmt = 0;
  17211. zSql = sqlite3_mprintf(
  17212. "REPLACE INTO temp.sqlite_parameters(key,value)"
  17213. "VALUES(%Q,%Q);", zKey, zValue);
  17214. if( zSql==0 ) shell_out_of_memory();
  17215. rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  17216. sqlite3_free(zSql);
  17217. if( rx!=SQLITE_OK ){
  17218. utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
  17219. sqlite3_finalize(pStmt);
  17220. pStmt = 0;
  17221. rc = 1;
  17222. }
  17223. }
  17224. sqlite3_step(pStmt);
  17225. sqlite3_finalize(pStmt);
  17226. }else
  17227. /* .parameter unset NAME
  17228. ** Remove the NAME binding from the parameter binding table, if it
  17229. ** exists.
  17230. */
  17231. if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
  17232. char *zSql = sqlite3_mprintf(
  17233. "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
  17234. if( zSql==0 ) shell_out_of_memory();
  17235. sqlite3_exec(p->db, zSql, 0, 0, 0);
  17236. sqlite3_free(zSql);
  17237. }else
  17238. /* If no command name matches, show a syntax error */
  17239. parameter_syntax_error:
  17240. showHelp(p->out, "parameter");
  17241. }else
  17242. if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
  17243. int i;
  17244. for(i=1; i<nArg; i++){
  17245. if( i>1 ) raw_printf(p->out, " ");
  17246. utf8_printf(p->out, "%s", azArg[i]);
  17247. }
  17248. raw_printf(p->out, "\n");
  17249. }else
  17250. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  17251. if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
  17252. int i;
  17253. int nn = 0;
  17254. p->flgProgress = 0;
  17255. p->mxProgress = 0;
  17256. p->nProgress = 0;
  17257. for(i=1; i<nArg; i++){
  17258. const char *z = azArg[i];
  17259. if( z[0]=='-' ){
  17260. z++;
  17261. if( z[0]=='-' ) z++;
  17262. if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
  17263. p->flgProgress |= SHELL_PROGRESS_QUIET;
  17264. continue;
  17265. }
  17266. if( strcmp(z,"reset")==0 ){
  17267. p->flgProgress |= SHELL_PROGRESS_RESET;
  17268. continue;
  17269. }
  17270. if( strcmp(z,"once")==0 ){
  17271. p->flgProgress |= SHELL_PROGRESS_ONCE;
  17272. continue;
  17273. }
  17274. if( strcmp(z,"limit")==0 ){
  17275. if( i+1>=nArg ){
  17276. utf8_printf(stderr, "Error: missing argument on --limit\n");
  17277. rc = 1;
  17278. goto meta_command_exit;
  17279. }else{
  17280. p->mxProgress = (int)integerValue(azArg[++i]);
  17281. }
  17282. continue;
  17283. }
  17284. utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
  17285. rc = 1;
  17286. goto meta_command_exit;
  17287. }else{
  17288. nn = (int)integerValue(z);
  17289. }
  17290. }
  17291. open_db(p, 0);
  17292. sqlite3_progress_handler(p->db, nn, progress_handler, p);
  17293. }else
  17294. #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
  17295. if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
  17296. if( nArg >= 2) {
  17297. strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  17298. }
  17299. if( nArg >= 3) {
  17300. strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  17301. }
  17302. }else
  17303. if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
  17304. rc = 2;
  17305. }else
  17306. if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
  17307. FILE *inSaved = p->in;
  17308. int savedLineno = p->lineno;
  17309. if( nArg!=2 ){
  17310. raw_printf(stderr, "Usage: .read FILE\n");
  17311. rc = 1;
  17312. goto meta_command_exit;
  17313. }
  17314. if( notNormalFile(azArg[1])
  17315. || (p->in = fopen(azArg[1], "rb"))==0
  17316. ){
  17317. utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
  17318. rc = 1;
  17319. }else{
  17320. rc = process_input(p);
  17321. fclose(p->in);
  17322. }
  17323. p->in = inSaved;
  17324. p->lineno = savedLineno;
  17325. }else
  17326. if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
  17327. const char *zSrcFile;
  17328. const char *zDb;
  17329. sqlite3 *pSrc;
  17330. sqlite3_backup *pBackup;
  17331. int nTimeout = 0;
  17332. if( nArg==2 ){
  17333. zSrcFile = azArg[1];
  17334. zDb = "main";
  17335. }else if( nArg==3 ){
  17336. zSrcFile = azArg[2];
  17337. zDb = azArg[1];
  17338. }else{
  17339. raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
  17340. rc = 1;
  17341. goto meta_command_exit;
  17342. }
  17343. rc = sqlite3_open(zSrcFile, &pSrc);
  17344. if( rc!=SQLITE_OK ){
  17345. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  17346. close_db(pSrc);
  17347. return 1;
  17348. }
  17349. open_db(p, 0);
  17350. pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  17351. if( pBackup==0 ){
  17352. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  17353. close_db(pSrc);
  17354. return 1;
  17355. }
  17356. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  17357. || rc==SQLITE_BUSY ){
  17358. if( rc==SQLITE_BUSY ){
  17359. if( nTimeout++ >= 3 ) break;
  17360. sqlite3_sleep(100);
  17361. }
  17362. }
  17363. sqlite3_backup_finish(pBackup);
  17364. if( rc==SQLITE_DONE ){
  17365. rc = 0;
  17366. }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  17367. raw_printf(stderr, "Error: source database is busy\n");
  17368. rc = 1;
  17369. }else{
  17370. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  17371. rc = 1;
  17372. }
  17373. close_db(pSrc);
  17374. }else
  17375. if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
  17376. if( nArg==2 ){
  17377. p->scanstatsOn = (u8)booleanValue(azArg[1]);
  17378. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  17379. raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
  17380. #endif
  17381. }else{
  17382. raw_printf(stderr, "Usage: .scanstats on|off\n");
  17383. rc = 1;
  17384. }
  17385. }else
  17386. if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
  17387. ShellText sSelect;
  17388. ShellState data;
  17389. char *zErrMsg = 0;
  17390. const char *zDiv = "(";
  17391. const char *zName = 0;
  17392. int iSchema = 0;
  17393. int bDebug = 0;
  17394. int ii;
  17395. open_db(p, 0);
  17396. memcpy(&data, p, sizeof(data));
  17397. data.showHeader = 0;
  17398. data.cMode = data.mode = MODE_Semi;
  17399. initText(&sSelect);
  17400. for(ii=1; ii<nArg; ii++){
  17401. if( optionMatch(azArg[ii],"indent") ){
  17402. data.cMode = data.mode = MODE_Pretty;
  17403. }else if( optionMatch(azArg[ii],"debug") ){
  17404. bDebug = 1;
  17405. }else if( zName==0 ){
  17406. zName = azArg[ii];
  17407. }else{
  17408. raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
  17409. rc = 1;
  17410. goto meta_command_exit;
  17411. }
  17412. }
  17413. if( zName!=0 ){
  17414. int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
  17415. || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
  17416. || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
  17417. || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
  17418. if( isSchema ){
  17419. char *new_argv[2], *new_colv[2];
  17420. new_argv[0] = sqlite3_mprintf(
  17421. "CREATE TABLE %s (\n"
  17422. " type text,\n"
  17423. " name text,\n"
  17424. " tbl_name text,\n"
  17425. " rootpage integer,\n"
  17426. " sql text\n"
  17427. ")", zName);
  17428. new_argv[1] = 0;
  17429. new_colv[0] = "sql";
  17430. new_colv[1] = 0;
  17431. callback(&data, 1, new_argv, new_colv);
  17432. sqlite3_free(new_argv[0]);
  17433. }
  17434. }
  17435. if( zDiv ){
  17436. sqlite3_stmt *pStmt = 0;
  17437. rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
  17438. -1, &pStmt, 0);
  17439. if( rc ){
  17440. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  17441. sqlite3_finalize(pStmt);
  17442. rc = 1;
  17443. goto meta_command_exit;
  17444. }
  17445. appendText(&sSelect, "SELECT sql FROM", 0);
  17446. iSchema = 0;
  17447. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  17448. const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
  17449. char zScNum[30];
  17450. sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
  17451. appendText(&sSelect, zDiv, 0);
  17452. zDiv = " UNION ALL ";
  17453. appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
  17454. if( sqlite3_stricmp(zDb, "main")!=0 ){
  17455. appendText(&sSelect, zDb, '\'');
  17456. }else{
  17457. appendText(&sSelect, "NULL", 0);
  17458. }
  17459. appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
  17460. appendText(&sSelect, zScNum, 0);
  17461. appendText(&sSelect, " AS snum, ", 0);
  17462. appendText(&sSelect, zDb, '\'');
  17463. appendText(&sSelect, " AS sname FROM ", 0);
  17464. appendText(&sSelect, zDb, quoteChar(zDb));
  17465. appendText(&sSelect, ".sqlite_schema", 0);
  17466. }
  17467. sqlite3_finalize(pStmt);
  17468. #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
  17469. if( zName ){
  17470. appendText(&sSelect,
  17471. " UNION ALL SELECT shell_module_schema(name),"
  17472. " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
  17473. 0);
  17474. }
  17475. #endif
  17476. appendText(&sSelect, ") WHERE ", 0);
  17477. if( zName ){
  17478. char *zQarg = sqlite3_mprintf("%Q", zName);
  17479. int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
  17480. strchr(zName, '[') != 0;
  17481. if( strchr(zName, '.') ){
  17482. appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
  17483. }else{
  17484. appendText(&sSelect, "lower(tbl_name)", 0);
  17485. }
  17486. appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
  17487. appendText(&sSelect, zQarg, 0);
  17488. if( !bGlob ){
  17489. appendText(&sSelect, " ESCAPE '\\' ", 0);
  17490. }
  17491. appendText(&sSelect, " AND ", 0);
  17492. sqlite3_free(zQarg);
  17493. }
  17494. appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
  17495. " ORDER BY snum, rowid", 0);
  17496. if( bDebug ){
  17497. utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
  17498. }else{
  17499. rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
  17500. }
  17501. freeText(&sSelect);
  17502. }
  17503. if( zErrMsg ){
  17504. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  17505. sqlite3_free(zErrMsg);
  17506. rc = 1;
  17507. }else if( rc != SQLITE_OK ){
  17508. raw_printf(stderr,"Error: querying schema information\n");
  17509. rc = 1;
  17510. }else{
  17511. rc = 0;
  17512. }
  17513. }else
  17514. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  17515. if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
  17516. sqlite3_unsupported_selecttrace = nArg>=2 ? (int)integerValue(azArg[1]) : 0xffff;
  17517. }else
  17518. #endif
  17519. #if defined(SQLITE_ENABLE_SESSION)
  17520. if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
  17521. OpenSession *pSession = &p->aSession[0];
  17522. char **azCmd = &azArg[1];
  17523. int iSes = 0;
  17524. int nCmd = nArg - 1;
  17525. int i;
  17526. if( nArg<=1 ) goto session_syntax_error;
  17527. open_db(p, 0);
  17528. if( nArg>=3 ){
  17529. for(iSes=0; iSes<p->nSession; iSes++){
  17530. if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
  17531. }
  17532. if( iSes<p->nSession ){
  17533. pSession = &p->aSession[iSes];
  17534. azCmd++;
  17535. nCmd--;
  17536. }else{
  17537. pSession = &p->aSession[0];
  17538. iSes = 0;
  17539. }
  17540. }
  17541. /* .session attach TABLE
  17542. ** Invoke the sqlite3session_attach() interface to attach a particular
  17543. ** table so that it is never filtered.
  17544. */
  17545. if( strcmp(azCmd[0],"attach")==0 ){
  17546. if( nCmd!=2 ) goto session_syntax_error;
  17547. if( pSession->p==0 ){
  17548. session_not_open:
  17549. raw_printf(stderr, "ERROR: No sessions are open\n");
  17550. }else{
  17551. rc = sqlite3session_attach(pSession->p, azCmd[1]);
  17552. if( rc ){
  17553. raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
  17554. rc = 0;
  17555. }
  17556. }
  17557. }else
  17558. /* .session changeset FILE
  17559. ** .session patchset FILE
  17560. ** Write a changeset or patchset into a file. The file is overwritten.
  17561. */
  17562. if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
  17563. FILE *out = 0;
  17564. if( nCmd!=2 ) goto session_syntax_error;
  17565. if( pSession->p==0 ) goto session_not_open;
  17566. out = fopen(azCmd[1], "wb");
  17567. if( out==0 ){
  17568. utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
  17569. azCmd[1]);
  17570. }else{
  17571. int szChng;
  17572. void *pChng;
  17573. if( azCmd[0][0]=='c' ){
  17574. rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
  17575. }else{
  17576. rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
  17577. }
  17578. if( rc ){
  17579. printf("Error: error code %d\n", rc);
  17580. rc = 0;
  17581. }
  17582. if( pChng
  17583. && fwrite(pChng, szChng, 1, out)!=1 ){
  17584. raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
  17585. szChng);
  17586. }
  17587. sqlite3_free(pChng);
  17588. fclose(out);
  17589. }
  17590. }else
  17591. /* .session close
  17592. ** Close the identified session
  17593. */
  17594. if( strcmp(azCmd[0], "close")==0 ){
  17595. if( nCmd!=1 ) goto session_syntax_error;
  17596. if( p->nSession ){
  17597. session_close(pSession);
  17598. p->aSession[iSes] = p->aSession[--p->nSession];
  17599. }
  17600. }else
  17601. /* .session enable ?BOOLEAN?
  17602. ** Query or set the enable flag
  17603. */
  17604. if( strcmp(azCmd[0], "enable")==0 ){
  17605. int ii;
  17606. if( nCmd>2 ) goto session_syntax_error;
  17607. ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  17608. if( p->nSession ){
  17609. ii = sqlite3session_enable(pSession->p, ii);
  17610. utf8_printf(p->out, "session %s enable flag = %d\n",
  17611. pSession->zName, ii);
  17612. }
  17613. }else
  17614. /* .session filter GLOB ....
  17615. ** Set a list of GLOB patterns of table names to be excluded.
  17616. */
  17617. if( strcmp(azCmd[0], "filter")==0 ){
  17618. int ii, nByte;
  17619. if( nCmd<2 ) goto session_syntax_error;
  17620. if( p->nSession ){
  17621. for(ii=0; ii<pSession->nFilter; ii++){
  17622. sqlite3_free(pSession->azFilter[ii]);
  17623. }
  17624. sqlite3_free(pSession->azFilter);
  17625. nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
  17626. pSession->azFilter = sqlite3_malloc( nByte );
  17627. if( pSession->azFilter==0 ){
  17628. raw_printf(stderr, "Error: out or memory\n");
  17629. exit(1);
  17630. }
  17631. for(ii=1; ii<nCmd; ii++){
  17632. pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
  17633. }
  17634. pSession->nFilter = ii-1;
  17635. }
  17636. }else
  17637. /* .session indirect ?BOOLEAN?
  17638. ** Query or set the indirect flag
  17639. */
  17640. if( strcmp(azCmd[0], "indirect")==0 ){
  17641. int ii;
  17642. if( nCmd>2 ) goto session_syntax_error;
  17643. ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  17644. if( p->nSession ){
  17645. ii = sqlite3session_indirect(pSession->p, ii);
  17646. utf8_printf(p->out, "session %s indirect flag = %d\n",
  17647. pSession->zName, ii);
  17648. }
  17649. }else
  17650. /* .session isempty
  17651. ** Determine if the session is empty
  17652. */
  17653. if( strcmp(azCmd[0], "isempty")==0 ){
  17654. int ii;
  17655. if( nCmd!=1 ) goto session_syntax_error;
  17656. if( p->nSession ){
  17657. ii = sqlite3session_isempty(pSession->p);
  17658. utf8_printf(p->out, "session %s isempty flag = %d\n",
  17659. pSession->zName, ii);
  17660. }
  17661. }else
  17662. /* .session list
  17663. ** List all currently open sessions
  17664. */
  17665. if( strcmp(azCmd[0],"list")==0 ){
  17666. for(i=0; i<p->nSession; i++){
  17667. utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
  17668. }
  17669. }else
  17670. /* .session open DB NAME
  17671. ** Open a new session called NAME on the attached database DB.
  17672. ** DB is normally "main".
  17673. */
  17674. if( strcmp(azCmd[0],"open")==0 ){
  17675. char *zName;
  17676. if( nCmd!=3 ) goto session_syntax_error;
  17677. zName = azCmd[2];
  17678. if( zName[0]==0 ) goto session_syntax_error;
  17679. for(i=0; i<p->nSession; i++){
  17680. if( strcmp(p->aSession[i].zName,zName)==0 ){
  17681. utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
  17682. goto meta_command_exit;
  17683. }
  17684. }
  17685. if( p->nSession>=ArraySize(p->aSession) ){
  17686. raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
  17687. goto meta_command_exit;
  17688. }
  17689. pSession = &p->aSession[p->nSession];
  17690. rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
  17691. if( rc ){
  17692. raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
  17693. rc = 0;
  17694. goto meta_command_exit;
  17695. }
  17696. pSession->nFilter = 0;
  17697. sqlite3session_table_filter(pSession->p, session_filter, pSession);
  17698. p->nSession++;
  17699. pSession->zName = sqlite3_mprintf("%s", zName);
  17700. }else
  17701. /* If no command name matches, show a syntax error */
  17702. session_syntax_error:
  17703. showHelp(p->out, "session");
  17704. }else
  17705. #endif
  17706. #ifdef SQLITE_DEBUG
  17707. /* Undocumented commands for internal testing. Subject to change
  17708. ** without notice. */
  17709. if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
  17710. if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
  17711. int i, v;
  17712. for(i=1; i<nArg; i++){
  17713. v = booleanValue(azArg[i]);
  17714. utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
  17715. }
  17716. }
  17717. if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
  17718. int i; sqlite3_int64 v;
  17719. for(i=1; i<nArg; i++){
  17720. char zBuf[200];
  17721. v = integerValue(azArg[i]);
  17722. sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
  17723. utf8_printf(p->out, "%s", zBuf);
  17724. }
  17725. }
  17726. }else
  17727. #endif
  17728. if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
  17729. int bIsInit = 0; /* True to initialize the SELFTEST table */
  17730. int bVerbose = 0; /* Verbose output */
  17731. int bSelftestExists; /* True if SELFTEST already exists */
  17732. int i, k; /* Loop counters */
  17733. int nTest = 0; /* Number of tests runs */
  17734. int nErr = 0; /* Number of errors seen */
  17735. ShellText str; /* Answer for a query */
  17736. sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
  17737. open_db(p,0);
  17738. for(i=1; i<nArg; i++){
  17739. const char *z = azArg[i];
  17740. if( z[0]=='-' && z[1]=='-' ) z++;
  17741. if( strcmp(z,"-init")==0 ){
  17742. bIsInit = 1;
  17743. }else
  17744. if( strcmp(z,"-v")==0 ){
  17745. bVerbose++;
  17746. }else
  17747. {
  17748. utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
  17749. azArg[i], azArg[0]);
  17750. raw_printf(stderr, "Should be one of: --init -v\n");
  17751. rc = 1;
  17752. goto meta_command_exit;
  17753. }
  17754. }
  17755. if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
  17756. != SQLITE_OK ){
  17757. bSelftestExists = 0;
  17758. }else{
  17759. bSelftestExists = 1;
  17760. }
  17761. if( bIsInit ){
  17762. createSelftestTable(p);
  17763. bSelftestExists = 1;
  17764. }
  17765. initText(&str);
  17766. appendText(&str, "x", 0);
  17767. for(k=bSelftestExists; k>=0; k--){
  17768. if( k==1 ){
  17769. rc = sqlite3_prepare_v2(p->db,
  17770. "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
  17771. -1, &pStmt, 0);
  17772. }else{
  17773. rc = sqlite3_prepare_v2(p->db,
  17774. "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
  17775. " (1,'run','PRAGMA integrity_check','ok')",
  17776. -1, &pStmt, 0);
  17777. }
  17778. if( rc ){
  17779. raw_printf(stderr, "Error querying the selftest table\n");
  17780. rc = 1;
  17781. sqlite3_finalize(pStmt);
  17782. goto meta_command_exit;
  17783. }
  17784. for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
  17785. int tno = sqlite3_column_int(pStmt, 0);
  17786. const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
  17787. const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
  17788. const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
  17789. k = 0;
  17790. if( bVerbose>0 ){
  17791. char *zQuote = sqlite3_mprintf("%q", zSql);
  17792. printf("%d: %s %s\n", tno, zOp, zSql);
  17793. sqlite3_free(zQuote);
  17794. }
  17795. if( strcmp(zOp,"memo")==0 ){
  17796. utf8_printf(p->out, "%s\n", zSql);
  17797. }else
  17798. if( strcmp(zOp,"run")==0 ){
  17799. char *zErrMsg = 0;
  17800. str.n = 0;
  17801. str.z[0] = 0;
  17802. rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
  17803. nTest++;
  17804. if( bVerbose ){
  17805. utf8_printf(p->out, "Result: %s\n", str.z);
  17806. }
  17807. if( rc || zErrMsg ){
  17808. nErr++;
  17809. rc = 1;
  17810. utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
  17811. sqlite3_free(zErrMsg);
  17812. }else if( strcmp(zAns,str.z)!=0 ){
  17813. nErr++;
  17814. rc = 1;
  17815. utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
  17816. utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
  17817. }
  17818. }else
  17819. {
  17820. utf8_printf(stderr,
  17821. "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
  17822. rc = 1;
  17823. break;
  17824. }
  17825. } /* End loop over rows of content from SELFTEST */
  17826. sqlite3_finalize(pStmt);
  17827. } /* End loop over k */
  17828. freeText(&str);
  17829. utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
  17830. }else
  17831. if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
  17832. if( nArg<2 || nArg>3 ){
  17833. raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
  17834. rc = 1;
  17835. }
  17836. if( nArg>=2 ){
  17837. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
  17838. "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
  17839. }
  17840. if( nArg>=3 ){
  17841. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
  17842. "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
  17843. }
  17844. }else
  17845. if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
  17846. const char *zLike = 0; /* Which table to checksum. 0 means everything */
  17847. int i; /* Loop counter */
  17848. int bSchema = 0; /* Also hash the schema */
  17849. int bSeparate = 0; /* Hash each table separately */
  17850. int iSize = 224; /* Hash algorithm to use */
  17851. int bDebug = 0; /* Only show the query that would have run */
  17852. sqlite3_stmt *pStmt; /* For querying tables names */
  17853. char *zSql; /* SQL to be run */
  17854. char *zSep; /* Separator */
  17855. ShellText sSql; /* Complete SQL for the query to run the hash */
  17856. ShellText sQuery; /* Set of queries used to read all content */
  17857. open_db(p, 0);
  17858. for(i=1; i<nArg; i++){
  17859. const char *z = azArg[i];
  17860. if( z[0]=='-' ){
  17861. z++;
  17862. if( z[0]=='-' ) z++;
  17863. if( strcmp(z,"schema")==0 ){
  17864. bSchema = 1;
  17865. }else
  17866. if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
  17867. || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
  17868. ){
  17869. iSize = atoi(&z[5]);
  17870. }else
  17871. if( strcmp(z,"debug")==0 ){
  17872. bDebug = 1;
  17873. }else
  17874. {
  17875. utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
  17876. azArg[i], azArg[0]);
  17877. showHelp(p->out, azArg[0]);
  17878. rc = 1;
  17879. goto meta_command_exit;
  17880. }
  17881. }else if( zLike ){
  17882. raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
  17883. rc = 1;
  17884. goto meta_command_exit;
  17885. }else{
  17886. zLike = z;
  17887. bSeparate = 1;
  17888. if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
  17889. }
  17890. }
  17891. if( bSchema ){
  17892. zSql = "SELECT lower(name) FROM sqlite_schema"
  17893. " WHERE type='table' AND coalesce(rootpage,0)>1"
  17894. " UNION ALL SELECT 'sqlite_schema'"
  17895. " ORDER BY 1 collate nocase";
  17896. }else{
  17897. zSql = "SELECT lower(name) FROM sqlite_schema"
  17898. " WHERE type='table' AND coalesce(rootpage,0)>1"
  17899. " AND name NOT LIKE 'sqlite_%'"
  17900. " ORDER BY 1 collate nocase";
  17901. }
  17902. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  17903. initText(&sQuery);
  17904. initText(&sSql);
  17905. appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
  17906. zSep = "VALUES(";
  17907. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  17908. const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
  17909. if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
  17910. if( strncmp(zTab, "sqlite_",7)!=0 ){
  17911. appendText(&sQuery,"SELECT * FROM ", 0);
  17912. appendText(&sQuery,zTab,'"');
  17913. appendText(&sQuery," NOT INDEXED;", 0);
  17914. }else if( strcmp(zTab, "sqlite_schema")==0 ){
  17915. appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
  17916. " ORDER BY name;", 0);
  17917. }else if( strcmp(zTab, "sqlite_sequence")==0 ){
  17918. appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
  17919. " ORDER BY name;", 0);
  17920. }else if( strcmp(zTab, "sqlite_stat1")==0 ){
  17921. appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
  17922. " ORDER BY tbl,idx;", 0);
  17923. }else if( strcmp(zTab, "sqlite_stat4")==0 ){
  17924. appendText(&sQuery, "SELECT * FROM ", 0);
  17925. appendText(&sQuery, zTab, 0);
  17926. appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
  17927. }
  17928. appendText(&sSql, zSep, 0);
  17929. appendText(&sSql, sQuery.z, '\'');
  17930. sQuery.n = 0;
  17931. appendText(&sSql, ",", 0);
  17932. appendText(&sSql, zTab, '\'');
  17933. zSep = "),(";
  17934. }
  17935. sqlite3_finalize(pStmt);
  17936. if( bSeparate ){
  17937. zSql = sqlite3_mprintf(
  17938. "%s))"
  17939. " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
  17940. " FROM [sha3sum$query]",
  17941. sSql.z, iSize);
  17942. }else{
  17943. zSql = sqlite3_mprintf(
  17944. "%s))"
  17945. " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
  17946. " FROM [sha3sum$query]",
  17947. sSql.z, iSize);
  17948. }
  17949. freeText(&sQuery);
  17950. freeText(&sSql);
  17951. if( bDebug ){
  17952. utf8_printf(p->out, "%s\n", zSql);
  17953. }else{
  17954. shell_exec(p, zSql, 0);
  17955. }
  17956. sqlite3_free(zSql);
  17957. }else
  17958. #ifndef SQLITE_NOHAVE_SYSTEM
  17959. if( c=='s'
  17960. && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
  17961. ){
  17962. char *zCmd;
  17963. int i, x;
  17964. if( nArg<2 ){
  17965. raw_printf(stderr, "Usage: .system COMMAND\n");
  17966. rc = 1;
  17967. goto meta_command_exit;
  17968. }
  17969. zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
  17970. for(i=2; i<nArg; i++){
  17971. zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
  17972. zCmd, azArg[i]);
  17973. }
  17974. x = system(zCmd);
  17975. sqlite3_free(zCmd);
  17976. if( x ) raw_printf(stderr, "System command returns %d\n", x);
  17977. }else
  17978. #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
  17979. if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
  17980. static const char *azBool[] = { "off", "on", "trigger", "full"};
  17981. int i;
  17982. if( nArg!=1 ){
  17983. raw_printf(stderr, "Usage: .show\n");
  17984. rc = 1;
  17985. goto meta_command_exit;
  17986. }
  17987. utf8_printf(p->out, "%12.12s: %s\n","echo",
  17988. azBool[ShellHasFlag(p, SHFLG_Echo)]);
  17989. utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
  17990. utf8_printf(p->out, "%12.12s: %s\n","explain",
  17991. p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
  17992. utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
  17993. utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
  17994. utf8_printf(p->out, "%12.12s: ", "nullvalue");
  17995. output_c_string(p->out, p->nullValue);
  17996. raw_printf(p->out, "\n");
  17997. utf8_printf(p->out,"%12.12s: %s\n","output",
  17998. strlen30(p->outfile) ? p->outfile : "stdout");
  17999. utf8_printf(p->out,"%12.12s: ", "colseparator");
  18000. output_c_string(p->out, p->colSeparator);
  18001. raw_printf(p->out, "\n");
  18002. utf8_printf(p->out,"%12.12s: ", "rowseparator");
  18003. output_c_string(p->out, p->rowSeparator);
  18004. raw_printf(p->out, "\n");
  18005. utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
  18006. utf8_printf(p->out, "%12.12s: ", "width");
  18007. for (i=0;i<p->nWidth;i++) {
  18008. raw_printf(p->out, "%d ", p->colWidth[i]);
  18009. }
  18010. raw_printf(p->out, "\n");
  18011. utf8_printf(p->out, "%12.12s: %s\n", "filename",
  18012. p->zDbFilename ? p->zDbFilename : "");
  18013. }else
  18014. if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
  18015. if( nArg==2 ){
  18016. p->statsOn = (u8)booleanValue(azArg[1]);
  18017. }else if( nArg==1 ){
  18018. display_stats(p->db, p, 0);
  18019. }else{
  18020. raw_printf(stderr, "Usage: .stats ?on|off?\n");
  18021. rc = 1;
  18022. }
  18023. }else
  18024. if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
  18025. || (c=='i' && (strncmp(azArg[0], "indices", n)==0
  18026. || strncmp(azArg[0], "indexes", n)==0) )
  18027. ){
  18028. sqlite3_stmt *pStmt;
  18029. char **azResult;
  18030. int nRow, nAlloc;
  18031. int ii;
  18032. ShellText s;
  18033. initText(&s);
  18034. open_db(p, 0);
  18035. rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
  18036. if( rc ){
  18037. sqlite3_finalize(pStmt);
  18038. return shellDatabaseError(p->db);
  18039. }
  18040. if( nArg>2 && c=='i' ){
  18041. /* It is an historical accident that the .indexes command shows an error
  18042. ** when called with the wrong number of arguments whereas the .tables
  18043. ** command does not. */
  18044. raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
  18045. rc = 1;
  18046. sqlite3_finalize(pStmt);
  18047. goto meta_command_exit;
  18048. }
  18049. for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
  18050. const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
  18051. if( zDbName==0 ) continue;
  18052. if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
  18053. if( sqlite3_stricmp(zDbName, "main")==0 ){
  18054. appendText(&s, "SELECT name FROM ", 0);
  18055. }else{
  18056. appendText(&s, "SELECT ", 0);
  18057. appendText(&s, zDbName, '\'');
  18058. appendText(&s, "||'.'||name FROM ", 0);
  18059. }
  18060. appendText(&s, zDbName, '"');
  18061. appendText(&s, ".sqlite_schema ", 0);
  18062. if( c=='t' ){
  18063. appendText(&s," WHERE type IN ('table','view')"
  18064. " AND name NOT LIKE 'sqlite_%'"
  18065. " AND name LIKE ?1", 0);
  18066. }else{
  18067. appendText(&s," WHERE type='index'"
  18068. " AND tbl_name LIKE ?1", 0);
  18069. }
  18070. }
  18071. rc = sqlite3_finalize(pStmt);
  18072. appendText(&s, " ORDER BY 1", 0);
  18073. rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
  18074. freeText(&s);
  18075. if( rc ) return shellDatabaseError(p->db);
  18076. /* Run the SQL statement prepared by the above block. Store the results
  18077. ** as an array of nul-terminated strings in azResult[]. */
  18078. nRow = nAlloc = 0;
  18079. azResult = 0;
  18080. if( nArg>1 ){
  18081. sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
  18082. }else{
  18083. sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
  18084. }
  18085. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  18086. if( nRow>=nAlloc ){
  18087. char **azNew;
  18088. int n2 = nAlloc*2 + 10;
  18089. azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
  18090. if( azNew==0 ) shell_out_of_memory();
  18091. nAlloc = n2;
  18092. azResult = azNew;
  18093. }
  18094. azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  18095. if( 0==azResult[nRow] ) shell_out_of_memory();
  18096. nRow++;
  18097. }
  18098. if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
  18099. rc = shellDatabaseError(p->db);
  18100. }
  18101. /* Pretty-print the contents of array azResult[] to the output */
  18102. if( rc==0 && nRow>0 ){
  18103. int len, maxlen = 0;
  18104. int i, j;
  18105. int nPrintCol, nPrintRow;
  18106. for(i=0; i<nRow; i++){
  18107. len = strlen30(azResult[i]);
  18108. if( len>maxlen ) maxlen = len;
  18109. }
  18110. nPrintCol = 80/(maxlen+2);
  18111. if( nPrintCol<1 ) nPrintCol = 1;
  18112. nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  18113. for(i=0; i<nPrintRow; i++){
  18114. for(j=i; j<nRow; j+=nPrintRow){
  18115. char *zSp = j<nPrintRow ? "" : " ";
  18116. utf8_printf(p->out, "%s%-*s", zSp, maxlen,
  18117. azResult[j] ? azResult[j]:"");
  18118. }
  18119. raw_printf(p->out, "\n");
  18120. }
  18121. }
  18122. for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
  18123. sqlite3_free(azResult);
  18124. }else
  18125. /* Begin redirecting output to the file "testcase-out.txt" */
  18126. if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
  18127. output_reset(p);
  18128. p->out = output_file_open("testcase-out.txt", 0);
  18129. if( p->out==0 ){
  18130. raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
  18131. }
  18132. if( nArg>=2 ){
  18133. sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
  18134. }else{
  18135. sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
  18136. }
  18137. }else
  18138. #ifndef SQLITE_UNTESTABLE
  18139. if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
  18140. static const struct {
  18141. const char *zCtrlName; /* Name of a test-control option */
  18142. int ctrlCode; /* Integer code for that option */
  18143. const char *zUsage; /* Usage notes */
  18144. } aCtrl[] = {
  18145. { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
  18146. { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
  18147. /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
  18148. /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
  18149. { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
  18150. { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN" },
  18151. /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" },*/
  18152. { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
  18153. { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "" },
  18154. { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
  18155. { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
  18156. { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
  18157. #ifdef YYCOVERAGE
  18158. { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
  18159. #endif
  18160. { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
  18161. { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
  18162. { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
  18163. { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, "SEED ?db?" },
  18164. };
  18165. int testctrl = -1;
  18166. int iCtrl = -1;
  18167. int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
  18168. int isOk = 0;
  18169. int i, n2;
  18170. const char *zCmd = 0;
  18171. open_db(p, 0);
  18172. zCmd = nArg>=2 ? azArg[1] : "help";
  18173. /* The argument can optionally begin with "-" or "--" */
  18174. if( zCmd[0]=='-' && zCmd[1] ){
  18175. zCmd++;
  18176. if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
  18177. }
  18178. /* --help lists all test-controls */
  18179. if( strcmp(zCmd,"help")==0 ){
  18180. utf8_printf(p->out, "Available test-controls:\n");
  18181. for(i=0; i<ArraySize(aCtrl); i++){
  18182. utf8_printf(p->out, " .testctrl %s %s\n",
  18183. aCtrl[i].zCtrlName, aCtrl[i].zUsage);
  18184. }
  18185. rc = 1;
  18186. goto meta_command_exit;
  18187. }
  18188. /* convert testctrl text option to value. allow any unique prefix
  18189. ** of the option name, or a numerical value. */
  18190. n2 = strlen30(zCmd);
  18191. for(i=0; i<ArraySize(aCtrl); i++){
  18192. if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
  18193. if( testctrl<0 ){
  18194. testctrl = aCtrl[i].ctrlCode;
  18195. iCtrl = i;
  18196. }else{
  18197. utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
  18198. "Use \".testctrl --help\" for help\n", zCmd);
  18199. rc = 1;
  18200. goto meta_command_exit;
  18201. }
  18202. }
  18203. }
  18204. if( testctrl<0 ){
  18205. utf8_printf(stderr,"Error: unknown test-control: %s\n"
  18206. "Use \".testctrl --help\" for help\n", zCmd);
  18207. }else{
  18208. switch(testctrl){
  18209. /* sqlite3_test_control(int, db, int) */
  18210. case SQLITE_TESTCTRL_OPTIMIZATIONS:
  18211. if( nArg==3 ){
  18212. int opt = (int)strtol(azArg[2], 0, 0);
  18213. rc2 = sqlite3_test_control(testctrl, p->db, opt);
  18214. isOk = 3;
  18215. }
  18216. break;
  18217. /* sqlite3_test_control(int) */
  18218. case SQLITE_TESTCTRL_PRNG_SAVE:
  18219. case SQLITE_TESTCTRL_PRNG_RESTORE:
  18220. case SQLITE_TESTCTRL_PRNG_RESET:
  18221. case SQLITE_TESTCTRL_BYTEORDER:
  18222. if( nArg==2 ){
  18223. rc2 = sqlite3_test_control(testctrl);
  18224. isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
  18225. }
  18226. break;
  18227. /* sqlite3_test_control(int, uint) */
  18228. case SQLITE_TESTCTRL_PENDING_BYTE:
  18229. if( nArg==3 ){
  18230. unsigned int opt = (unsigned int)integerValue(azArg[2]);
  18231. rc2 = sqlite3_test_control(testctrl, opt);
  18232. isOk = 3;
  18233. }
  18234. break;
  18235. /* sqlite3_test_control(int, int, sqlite3*) */
  18236. case SQLITE_TESTCTRL_PRNG_SEED:
  18237. if( nArg==3 || nArg==4 ){
  18238. int ii = (int)integerValue(azArg[2]);
  18239. sqlite3 *db;
  18240. if( ii==0 && strcmp(azArg[2],"random")==0 ){
  18241. sqlite3_randomness(sizeof(ii),&ii);
  18242. printf("-- random seed: %d\n", ii);
  18243. }
  18244. if( nArg==3 ){
  18245. db = 0;
  18246. }else{
  18247. db = p->db;
  18248. /* Make sure the schema has been loaded */
  18249. sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
  18250. }
  18251. rc2 = sqlite3_test_control(testctrl, ii, db);
  18252. isOk = 3;
  18253. }
  18254. break;
  18255. /* sqlite3_test_control(int, int) */
  18256. case SQLITE_TESTCTRL_ASSERT:
  18257. case SQLITE_TESTCTRL_ALWAYS:
  18258. if( nArg==3 ){
  18259. int opt = booleanValue(azArg[2]);
  18260. rc2 = sqlite3_test_control(testctrl, opt);
  18261. isOk = 1;
  18262. }
  18263. break;
  18264. /* sqlite3_test_control(int, int) */
  18265. case SQLITE_TESTCTRL_LOCALTIME_FAULT:
  18266. case SQLITE_TESTCTRL_NEVER_CORRUPT:
  18267. if( nArg==3 ){
  18268. int opt = booleanValue(azArg[2]);
  18269. rc2 = sqlite3_test_control(testctrl, opt);
  18270. isOk = 3;
  18271. }
  18272. break;
  18273. /* sqlite3_test_control(sqlite3*) */
  18274. case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
  18275. rc2 = sqlite3_test_control(testctrl, p->db);
  18276. isOk = 3;
  18277. break;
  18278. case SQLITE_TESTCTRL_IMPOSTER:
  18279. if( nArg==5 ){
  18280. rc2 = sqlite3_test_control(testctrl, p->db,
  18281. azArg[2],
  18282. integerValue(azArg[3]),
  18283. integerValue(azArg[4]));
  18284. isOk = 3;
  18285. }
  18286. break;
  18287. #ifdef YYCOVERAGE
  18288. case SQLITE_TESTCTRL_PARSER_COVERAGE:
  18289. if( nArg==2 ){
  18290. sqlite3_test_control(testctrl, p->out);
  18291. isOk = 3;
  18292. }
  18293. #endif
  18294. }
  18295. }
  18296. if( isOk==0 && iCtrl>=0 ){
  18297. utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
  18298. rc = 1;
  18299. }else if( isOk==1 ){
  18300. raw_printf(p->out, "%d\n", rc2);
  18301. }else if( isOk==2 ){
  18302. raw_printf(p->out, "0x%08x\n", rc2);
  18303. }
  18304. }else
  18305. #endif /* !defined(SQLITE_UNTESTABLE) */
  18306. if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
  18307. open_db(p, 0);
  18308. sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
  18309. }else
  18310. if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
  18311. if( nArg==2 ){
  18312. enableTimer = booleanValue(azArg[1]);
  18313. if( enableTimer && !HAS_TIMER ){
  18314. raw_printf(stderr, "Error: timer not available on this system.\n");
  18315. enableTimer = 0;
  18316. }
  18317. }else{
  18318. raw_printf(stderr, "Usage: .timer on|off\n");
  18319. rc = 1;
  18320. }
  18321. }else
  18322. #ifndef SQLITE_OMIT_TRACE
  18323. if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
  18324. int mType = 0;
  18325. int jj;
  18326. open_db(p, 0);
  18327. for(jj=1; jj<nArg; jj++){
  18328. const char *z = azArg[jj];
  18329. if( z[0]=='-' ){
  18330. if( optionMatch(z, "expanded") ){
  18331. p->eTraceType = SHELL_TRACE_EXPANDED;
  18332. }
  18333. #ifdef SQLITE_ENABLE_NORMALIZE
  18334. else if( optionMatch(z, "normalized") ){
  18335. p->eTraceType = SHELL_TRACE_NORMALIZED;
  18336. }
  18337. #endif
  18338. else if( optionMatch(z, "plain") ){
  18339. p->eTraceType = SHELL_TRACE_PLAIN;
  18340. }
  18341. else if( optionMatch(z, "profile") ){
  18342. mType |= SQLITE_TRACE_PROFILE;
  18343. }
  18344. else if( optionMatch(z, "row") ){
  18345. mType |= SQLITE_TRACE_ROW;
  18346. }
  18347. else if( optionMatch(z, "stmt") ){
  18348. mType |= SQLITE_TRACE_STMT;
  18349. }
  18350. else if( optionMatch(z, "close") ){
  18351. mType |= SQLITE_TRACE_CLOSE;
  18352. }
  18353. else {
  18354. raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
  18355. rc = 1;
  18356. goto meta_command_exit;
  18357. }
  18358. }else{
  18359. output_file_close(p->traceOut);
  18360. p->traceOut = output_file_open(azArg[1], 0);
  18361. }
  18362. }
  18363. if( p->traceOut==0 ){
  18364. sqlite3_trace_v2(p->db, 0, 0, 0);
  18365. }else{
  18366. if( mType==0 ) mType = SQLITE_TRACE_STMT;
  18367. sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
  18368. }
  18369. }else
  18370. #endif /* !defined(SQLITE_OMIT_TRACE) */
  18371. #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
  18372. if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
  18373. int ii;
  18374. int lenOpt;
  18375. char *zOpt;
  18376. if( nArg<2 ){
  18377. raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
  18378. rc = 1;
  18379. goto meta_command_exit;
  18380. }
  18381. open_db(p, 0);
  18382. zOpt = azArg[1];
  18383. if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
  18384. lenOpt = (int)strlen(zOpt);
  18385. if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
  18386. assert( azArg[nArg]==0 );
  18387. sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
  18388. }else{
  18389. for(ii=1; ii<nArg; ii++){
  18390. sqlite3_create_module(p->db, azArg[ii], 0, 0);
  18391. }
  18392. }
  18393. }else
  18394. #endif
  18395. #if SQLITE_USER_AUTHENTICATION
  18396. if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
  18397. if( nArg<2 ){
  18398. raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
  18399. rc = 1;
  18400. goto meta_command_exit;
  18401. }
  18402. open_db(p, 0);
  18403. if( strcmp(azArg[1],"login")==0 ){
  18404. if( nArg!=4 ){
  18405. raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
  18406. rc = 1;
  18407. goto meta_command_exit;
  18408. }
  18409. rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
  18410. strlen30(azArg[3]));
  18411. if( rc ){
  18412. utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
  18413. rc = 1;
  18414. }
  18415. }else if( strcmp(azArg[1],"add")==0 ){
  18416. if( nArg!=5 ){
  18417. raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
  18418. rc = 1;
  18419. goto meta_command_exit;
  18420. }
  18421. rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
  18422. booleanValue(azArg[4]));
  18423. if( rc ){
  18424. raw_printf(stderr, "User-Add failed: %d\n", rc);
  18425. rc = 1;
  18426. }
  18427. }else if( strcmp(azArg[1],"edit")==0 ){
  18428. if( nArg!=5 ){
  18429. raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
  18430. rc = 1;
  18431. goto meta_command_exit;
  18432. }
  18433. rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
  18434. booleanValue(azArg[4]));
  18435. if( rc ){
  18436. raw_printf(stderr, "User-Edit failed: %d\n", rc);
  18437. rc = 1;
  18438. }
  18439. }else if( strcmp(azArg[1],"delete")==0 ){
  18440. if( nArg!=3 ){
  18441. raw_printf(stderr, "Usage: .user delete USER\n");
  18442. rc = 1;
  18443. goto meta_command_exit;
  18444. }
  18445. rc = sqlite3_user_delete(p->db, azArg[2]);
  18446. if( rc ){
  18447. raw_printf(stderr, "User-Delete failed: %d\n", rc);
  18448. rc = 1;
  18449. }
  18450. }else{
  18451. raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
  18452. rc = 1;
  18453. goto meta_command_exit;
  18454. }
  18455. }else
  18456. #endif /* SQLITE_USER_AUTHENTICATION */
  18457. if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
  18458. utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
  18459. sqlite3_libversion(), sqlite3_sourceid());
  18460. #if SQLITE_HAVE_ZLIB
  18461. utf8_printf(p->out, "zlib version %s\n", zlibVersion());
  18462. #endif
  18463. #define CTIMEOPT_VAL_(opt) #opt
  18464. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  18465. #if defined(__clang__) && defined(__clang_major__)
  18466. utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
  18467. CTIMEOPT_VAL(__clang_minor__) "."
  18468. CTIMEOPT_VAL(__clang_patchlevel__) "\n");
  18469. #elif defined(_MSC_VER)
  18470. utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
  18471. #elif defined(__GNUC__) && defined(__VERSION__)
  18472. utf8_printf(p->out, "gcc-" __VERSION__ "\n");
  18473. #endif
  18474. }else
  18475. if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
  18476. const char *zDbName = nArg==2 ? azArg[1] : "main";
  18477. sqlite3_vfs *pVfs = 0;
  18478. if( p->db ){
  18479. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
  18480. if( pVfs ){
  18481. utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
  18482. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  18483. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  18484. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  18485. }
  18486. }
  18487. }else
  18488. if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
  18489. sqlite3_vfs *pVfs;
  18490. sqlite3_vfs *pCurrent = 0;
  18491. if( p->db ){
  18492. sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
  18493. }
  18494. for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
  18495. utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
  18496. pVfs==pCurrent ? " <--- CURRENT" : "");
  18497. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  18498. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  18499. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  18500. if( pVfs->pNext ){
  18501. raw_printf(p->out, "-----------------------------------\n");
  18502. }
  18503. }
  18504. }else
  18505. if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
  18506. const char *zDbName = nArg==2 ? azArg[1] : "main";
  18507. char *zVfsName = 0;
  18508. if( p->db ){
  18509. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
  18510. if( zVfsName ){
  18511. utf8_printf(p->out, "%s\n", zVfsName);
  18512. sqlite3_free(zVfsName);
  18513. }
  18514. }
  18515. }else
  18516. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  18517. if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
  18518. sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
  18519. }else
  18520. #endif
  18521. if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
  18522. int j;
  18523. assert( nArg<=ArraySize(azArg) );
  18524. p->nWidth = nArg-1;
  18525. p->colWidth = realloc(p->colWidth, p->nWidth*sizeof(int)*2);
  18526. if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
  18527. if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
  18528. for(j=1; j<nArg; j++){
  18529. p->colWidth[j-1] = (int)integerValue(azArg[j]);
  18530. }
  18531. }else
  18532. {
  18533. utf8_printf(stderr, "Error: unknown command or invalid arguments: "
  18534. " \"%s\". Enter \".help\" for help\n", azArg[0]);
  18535. rc = 1;
  18536. }
  18537. meta_command_exit:
  18538. if( p->outCount ){
  18539. p->outCount--;
  18540. if( p->outCount==0 ) output_reset(p);
  18541. }
  18542. return rc;
  18543. }
  18544. /*
  18545. ** Return TRUE if a semicolon occurs anywhere in the first N characters
  18546. ** of string z[].
  18547. */
  18548. static int line_contains_semicolon(const char *z, int N){
  18549. int i;
  18550. for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
  18551. return 0;
  18552. }
  18553. /*
  18554. ** Test to see if a line consists entirely of whitespace.
  18555. */
  18556. static int _all_whitespace(const char *z){
  18557. for(; *z; z++){
  18558. if( IsSpace(z[0]) ) continue;
  18559. if( *z=='/' && z[1]=='*' ){
  18560. z += 2;
  18561. while( *z && (*z!='*' || z[1]!='/') ){ z++; }
  18562. if( *z==0 ) return 0;
  18563. z++;
  18564. continue;
  18565. }
  18566. if( *z=='-' && z[1]=='-' ){
  18567. z += 2;
  18568. while( *z && *z!='\n' ){ z++; }
  18569. if( *z==0 ) return 1;
  18570. continue;
  18571. }
  18572. return 0;
  18573. }
  18574. return 1;
  18575. }
  18576. /*
  18577. ** Return TRUE if the line typed in is an SQL command terminator other
  18578. ** than a semi-colon. The SQL Server style "go" command is understood
  18579. ** as is the Oracle "/".
  18580. */
  18581. static int line_is_command_terminator(const char *zLine){
  18582. while( IsSpace(zLine[0]) ){ zLine++; };
  18583. if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
  18584. return 1; /* Oracle */
  18585. }
  18586. if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
  18587. && _all_whitespace(&zLine[2]) ){
  18588. return 1; /* SQL Server */
  18589. }
  18590. return 0;
  18591. }
  18592. /*
  18593. ** We need a default sqlite3_complete() implementation to use in case
  18594. ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
  18595. ** any arbitrary text is a complete SQL statement. This is not very
  18596. ** user-friendly, but it does seem to work.
  18597. */
  18598. #ifdef SQLITE_OMIT_COMPLETE
  18599. #define sqlite3_complete(x) 1
  18600. #endif
  18601. /*
  18602. ** Return true if zSql is a complete SQL statement. Return false if it
  18603. ** ends in the middle of a string literal or C-style comment.
  18604. */
  18605. static int line_is_complete(char *zSql, int nSql){
  18606. int rc;
  18607. if( zSql==0 ) return 1;
  18608. zSql[nSql] = ';';
  18609. zSql[nSql+1] = 0;
  18610. rc = sqlite3_complete(zSql);
  18611. zSql[nSql] = 0;
  18612. return rc;
  18613. }
  18614. /*
  18615. ** Run a single line of SQL. Return the number of errors.
  18616. */
  18617. static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
  18618. int rc;
  18619. char *zErrMsg = 0;
  18620. open_db(p, 0);
  18621. if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
  18622. if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
  18623. BEGIN_TIMER;
  18624. rc = shell_exec(p, zSql, &zErrMsg);
  18625. END_TIMER;
  18626. if( rc || zErrMsg ){
  18627. char zPrefix[100];
  18628. if( in!=0 || !stdin_is_interactive ){
  18629. sqlite3_snprintf(sizeof(zPrefix), zPrefix,
  18630. "Error: near line %d:", startline);
  18631. }else{
  18632. sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
  18633. }
  18634. if( zErrMsg!=0 ){
  18635. utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
  18636. sqlite3_free(zErrMsg);
  18637. zErrMsg = 0;
  18638. }else{
  18639. utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
  18640. }
  18641. return 1;
  18642. }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
  18643. raw_printf(p->out, "changes: %3d total_changes: %d\n",
  18644. sqlite3_changes(p->db), sqlite3_total_changes(p->db));
  18645. }
  18646. return 0;
  18647. }
  18648. /*
  18649. ** Read input from *in and process it. If *in==0 then input
  18650. ** is interactive - the user is typing it it. Otherwise, input
  18651. ** is coming from a file or device. A prompt is issued and history
  18652. ** is saved only if input is interactive. An interrupt signal will
  18653. ** cause this routine to exit immediately, unless input is interactive.
  18654. **
  18655. ** Return the number of errors.
  18656. */
  18657. static int process_input(ShellState *p){
  18658. char *zLine = 0; /* A single input line */
  18659. char *zSql = 0; /* Accumulated SQL text */
  18660. int nLine; /* Length of current line */
  18661. int nSql = 0; /* Bytes of zSql[] used */
  18662. int nAlloc = 0; /* Allocated zSql[] space */
  18663. int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
  18664. int rc; /* Error code */
  18665. int errCnt = 0; /* Number of errors seen */
  18666. int startline = 0; /* Line number for start of current input */
  18667. p->lineno = 0;
  18668. while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
  18669. fflush(p->out);
  18670. zLine = one_input_line(p->in, zLine, nSql>0);
  18671. if( zLine==0 ){
  18672. /* End of input */
  18673. if( p->in==0 && stdin_is_interactive ) printf("\n");
  18674. break;
  18675. }
  18676. if( seenInterrupt ){
  18677. if( p->in!=0 ) break;
  18678. seenInterrupt = 0;
  18679. }
  18680. p->lineno++;
  18681. if( nSql==0 && _all_whitespace(zLine) ){
  18682. if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
  18683. continue;
  18684. }
  18685. if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
  18686. if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
  18687. if( zLine[0]=='.' ){
  18688. rc = do_meta_command(zLine, p);
  18689. if( rc==2 ){ /* exit requested */
  18690. break;
  18691. }else if( rc ){
  18692. errCnt++;
  18693. }
  18694. }
  18695. continue;
  18696. }
  18697. if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
  18698. memcpy(zLine,";",2);
  18699. }
  18700. nLine = strlen30(zLine);
  18701. if( nSql+nLine+2>=nAlloc ){
  18702. nAlloc = nSql+nLine+100;
  18703. zSql = realloc(zSql, nAlloc);
  18704. if( zSql==0 ) shell_out_of_memory();
  18705. }
  18706. nSqlPrior = nSql;
  18707. if( nSql==0 ){
  18708. int i;
  18709. for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
  18710. assert( nAlloc>0 && zSql!=0 );
  18711. memcpy(zSql, zLine+i, nLine+1-i);
  18712. startline = p->lineno;
  18713. nSql = nLine-i;
  18714. }else{
  18715. zSql[nSql++] = '\n';
  18716. memcpy(zSql+nSql, zLine, nLine+1);
  18717. nSql += nLine;
  18718. }
  18719. if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  18720. && sqlite3_complete(zSql) ){
  18721. errCnt += runOneSqlLine(p, zSql, p->in, startline);
  18722. nSql = 0;
  18723. if( p->outCount ){
  18724. output_reset(p);
  18725. p->outCount = 0;
  18726. }else{
  18727. clearTempFile(p);
  18728. }
  18729. }else if( nSql && _all_whitespace(zSql) ){
  18730. if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
  18731. nSql = 0;
  18732. }
  18733. }
  18734. if( nSql && !_all_whitespace(zSql) ){
  18735. errCnt += runOneSqlLine(p, zSql, p->in, startline);
  18736. }
  18737. free(zSql);
  18738. free(zLine);
  18739. return errCnt>0;
  18740. }
  18741. /*
  18742. ** Return a pathname which is the user's home directory. A
  18743. ** 0 return indicates an error of some kind.
  18744. */
  18745. static char *find_home_dir(int clearFlag){
  18746. static char *home_dir = NULL;
  18747. if( clearFlag ){
  18748. free(home_dir);
  18749. home_dir = 0;
  18750. return 0;
  18751. }
  18752. if( home_dir ) return home_dir;
  18753. #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
  18754. && !defined(__RTP__) && !defined(_WRS_KERNEL)
  18755. {
  18756. struct passwd *pwent;
  18757. uid_t uid = getuid();
  18758. if( (pwent=getpwuid(uid)) != NULL) {
  18759. home_dir = pwent->pw_dir;
  18760. }
  18761. }
  18762. #endif
  18763. #if defined(_WIN32_WCE)
  18764. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  18765. */
  18766. home_dir = "/";
  18767. #else
  18768. #if defined(_WIN32) || defined(WIN32)
  18769. if (!home_dir) {
  18770. home_dir = getenv("USERPROFILE");
  18771. }
  18772. #endif
  18773. if (!home_dir) {
  18774. home_dir = getenv("HOME");
  18775. }
  18776. #if defined(_WIN32) || defined(WIN32)
  18777. if (!home_dir) {
  18778. char *zDrive, *zPath;
  18779. int n;
  18780. zDrive = getenv("HOMEDRIVE");
  18781. zPath = getenv("HOMEPATH");
  18782. if( zDrive && zPath ){
  18783. n = strlen30(zDrive) + strlen30(zPath) + 1;
  18784. home_dir = malloc( n );
  18785. if( home_dir==0 ) return 0;
  18786. sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  18787. return home_dir;
  18788. }
  18789. home_dir = "c:\\";
  18790. }
  18791. #endif
  18792. #endif /* !_WIN32_WCE */
  18793. if( home_dir ){
  18794. int n = strlen30(home_dir) + 1;
  18795. char *z = malloc( n );
  18796. if( z ) memcpy(z, home_dir, n);
  18797. home_dir = z;
  18798. }
  18799. return home_dir;
  18800. }
  18801. /*
  18802. ** Read input from the file given by sqliterc_override. Or if that
  18803. ** parameter is NULL, take input from ~/.sqliterc
  18804. **
  18805. ** Returns the number of errors.
  18806. */
  18807. static void process_sqliterc(
  18808. ShellState *p, /* Configuration data */
  18809. const char *sqliterc_override /* Name of config file. NULL to use default */
  18810. ){
  18811. char *home_dir = NULL;
  18812. const char *sqliterc = sqliterc_override;
  18813. char *zBuf = 0;
  18814. FILE *inSaved = p->in;
  18815. int savedLineno = p->lineno;
  18816. if (sqliterc == NULL) {
  18817. home_dir = find_home_dir(0);
  18818. if( home_dir==0 ){
  18819. raw_printf(stderr, "-- warning: cannot find home directory;"
  18820. " cannot read ~/.sqliterc\n");
  18821. return;
  18822. }
  18823. zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
  18824. sqliterc = zBuf;
  18825. }
  18826. p->in = fopen(sqliterc,"rb");
  18827. if( p->in ){
  18828. if( stdin_is_interactive ){
  18829. utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
  18830. }
  18831. process_input(p);
  18832. fclose(p->in);
  18833. }
  18834. p->in = inSaved;
  18835. p->lineno = savedLineno;
  18836. sqlite3_free(zBuf);
  18837. }
  18838. /*
  18839. ** Show available command line options
  18840. */
  18841. static const char zOptions[] =
  18842. #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
  18843. " -A ARGS... run \".archive ARGS\" and exit\n"
  18844. #endif
  18845. " -append append the database to the end of the file\n"
  18846. " -ascii set output mode to 'ascii'\n"
  18847. " -bail stop after hitting an error\n"
  18848. " -batch force batch I/O\n"
  18849. " -box set output mode to 'box'\n"
  18850. " -column set output mode to 'column'\n"
  18851. " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
  18852. " -csv set output mode to 'csv'\n"
  18853. #if defined(SQLITE_ENABLE_DESERIALIZE)
  18854. " -deserialize open the database using sqlite3_deserialize()\n"
  18855. #endif
  18856. " -echo print commands before execution\n"
  18857. " -init FILENAME read/process named file\n"
  18858. " -[no]header turn headers on or off\n"
  18859. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  18860. " -heap SIZE Size of heap for memsys3 or memsys5\n"
  18861. #endif
  18862. " -help show this message\n"
  18863. " -html set output mode to HTML\n"
  18864. " -interactive force interactive I/O\n"
  18865. " -json set output mode to 'json'\n"
  18866. " -line set output mode to 'line'\n"
  18867. " -list set output mode to 'list'\n"
  18868. " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
  18869. " -markdown set output mode to 'markdown'\n"
  18870. #if defined(SQLITE_ENABLE_DESERIALIZE)
  18871. " -maxsize N maximum size for a --deserialize database\n"
  18872. #endif
  18873. " -memtrace trace all memory allocations and deallocations\n"
  18874. " -mmap N default mmap size set to N\n"
  18875. #ifdef SQLITE_ENABLE_MULTIPLEX
  18876. " -multiplex enable the multiplexor VFS\n"
  18877. #endif
  18878. " -newline SEP set output row separator. Default: '\\n'\n"
  18879. " -nofollow refuse to open symbolic links to database files\n"
  18880. " -nullvalue TEXT set text string for NULL values. Default ''\n"
  18881. " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
  18882. " -quote set output mode to 'quote'\n"
  18883. " -readonly open the database read-only\n"
  18884. " -separator SEP set output column separator. Default: '|'\n"
  18885. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  18886. " -sorterref SIZE sorter references threshold size\n"
  18887. #endif
  18888. " -stats print memory stats before each finalize\n"
  18889. " -table set output mode to 'table'\n"
  18890. " -version show SQLite version\n"
  18891. " -vfs NAME use NAME as the default VFS\n"
  18892. #ifdef SQLITE_ENABLE_VFSTRACE
  18893. " -vfstrace enable tracing of all VFS calls\n"
  18894. #endif
  18895. #ifdef SQLITE_HAVE_ZLIB
  18896. " -zip open the file as a ZIP Archive\n"
  18897. #endif
  18898. ;
  18899. static void usage(int showDetail){
  18900. utf8_printf(stderr,
  18901. "Usage: %s [OPTIONS] FILENAME [SQL]\n"
  18902. "FILENAME is the name of an SQLite database. A new database is created\n"
  18903. "if the file does not previously exist.\n", Argv0);
  18904. if( showDetail ){
  18905. utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
  18906. }else{
  18907. raw_printf(stderr, "Use the -help option for additional information\n");
  18908. }
  18909. exit(1);
  18910. }
  18911. /*
  18912. ** Internal check: Verify that the SQLite is uninitialized. Print a
  18913. ** error message if it is initialized.
  18914. */
  18915. static void verify_uninitialized(void){
  18916. if( sqlite3_config(-1)==SQLITE_MISUSE ){
  18917. utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
  18918. " initialization.\n");
  18919. }
  18920. }
  18921. /*
  18922. ** Initialize the state information in data
  18923. */
  18924. static void main_init(ShellState *data) {
  18925. memset(data, 0, sizeof(*data));
  18926. data->normalMode = data->cMode = data->mode = MODE_List;
  18927. data->autoExplain = 1;
  18928. memcpy(data->colSeparator,SEP_Column, 2);
  18929. memcpy(data->rowSeparator,SEP_Row, 2);
  18930. data->showHeader = 0;
  18931. data->shellFlgs = SHFLG_Lookaside;
  18932. verify_uninitialized();
  18933. sqlite3_config(SQLITE_CONFIG_URI, 1);
  18934. sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
  18935. sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
  18936. sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  18937. sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
  18938. }
  18939. /*
  18940. ** Output text to the console in a font that attracts extra attention.
  18941. */
  18942. #ifdef _WIN32
  18943. static void printBold(const char *zText){
  18944. #if !SQLITE_OS_WINRT
  18945. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  18946. CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
  18947. GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
  18948. SetConsoleTextAttribute(out,
  18949. FOREGROUND_RED|FOREGROUND_INTENSITY
  18950. );
  18951. #endif
  18952. printf("%s", zText);
  18953. #if !SQLITE_OS_WINRT
  18954. SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
  18955. #endif
  18956. }
  18957. #else
  18958. static void printBold(const char *zText){
  18959. printf("\033[1m%s\033[0m", zText);
  18960. }
  18961. #endif
  18962. /*
  18963. ** Get the argument to an --option. Throw an error and die if no argument
  18964. ** is available.
  18965. */
  18966. static char *cmdline_option_value(int argc, char **argv, int i){
  18967. if( i==argc ){
  18968. utf8_printf(stderr, "%s: Error: missing argument to %s\n",
  18969. argv[0], argv[argc-1]);
  18970. exit(1);
  18971. }
  18972. return argv[i];
  18973. }
  18974. #ifndef SQLITE_SHELL_IS_UTF8
  18975. # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
  18976. # define SQLITE_SHELL_IS_UTF8 (0)
  18977. # else
  18978. # define SQLITE_SHELL_IS_UTF8 (1)
  18979. # endif
  18980. #endif
  18981. #if SQLITE_SHELL_IS_UTF8
  18982. int SQLITE_CDECL main(int argc, char **argv){
  18983. #else
  18984. int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
  18985. char **argv;
  18986. #endif
  18987. char *zErrMsg = 0;
  18988. ShellState data;
  18989. const char *zInitFile = 0;
  18990. int i;
  18991. int rc = 0;
  18992. int warnInmemoryDb = 0;
  18993. int readStdin = 1;
  18994. int nCmd = 0;
  18995. char **azCmd = 0;
  18996. const char *zVfs = 0; /* Value of -vfs command-line option */
  18997. #if !SQLITE_SHELL_IS_UTF8
  18998. char **argvToFree = 0;
  18999. int argcToFree = 0;
  19000. #endif
  19001. setBinaryMode(stdin, 0);
  19002. setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
  19003. stdin_is_interactive = isatty(0);
  19004. stdout_is_console = isatty(1);
  19005. #ifdef SQLITE_DEBUG
  19006. registerOomSimulator();
  19007. #endif
  19008. #if !defined(_WIN32_WCE)
  19009. if( getenv("SQLITE_DEBUG_BREAK") ){
  19010. if( isatty(0) && isatty(2) ){
  19011. fprintf(stderr,
  19012. "attach debugger to process %d and press any key to continue.\n",
  19013. GETPID());
  19014. fgetc(stdin);
  19015. }else{
  19016. #if defined(_WIN32) || defined(WIN32)
  19017. #if SQLITE_OS_WINRT
  19018. __debugbreak();
  19019. #else
  19020. DebugBreak();
  19021. #endif
  19022. #elif defined(SIGTRAP)
  19023. raise(SIGTRAP);
  19024. #endif
  19025. }
  19026. }
  19027. #endif
  19028. #if USE_SYSTEM_SQLITE+0!=1
  19029. if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
  19030. utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
  19031. sqlite3_sourceid(), SQLITE_SOURCE_ID);
  19032. exit(1);
  19033. }
  19034. #endif
  19035. main_init(&data);
  19036. /* On Windows, we must translate command-line arguments into UTF-8.
  19037. ** The SQLite memory allocator subsystem has to be enabled in order to
  19038. ** do this. But we want to run an sqlite3_shutdown() afterwards so that
  19039. ** subsequent sqlite3_config() calls will work. So copy all results into
  19040. ** memory that does not come from the SQLite memory allocator.
  19041. */
  19042. #if !SQLITE_SHELL_IS_UTF8
  19043. sqlite3_initialize();
  19044. argvToFree = malloc(sizeof(argv[0])*argc*2);
  19045. argcToFree = argc;
  19046. argv = argvToFree + argc;
  19047. if( argv==0 ) shell_out_of_memory();
  19048. for(i=0; i<argc; i++){
  19049. char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
  19050. int n;
  19051. if( z==0 ) shell_out_of_memory();
  19052. n = (int)strlen(z);
  19053. argv[i] = malloc( n+1 );
  19054. if( argv[i]==0 ) shell_out_of_memory();
  19055. memcpy(argv[i], z, n+1);
  19056. argvToFree[i] = argv[i];
  19057. sqlite3_free(z);
  19058. }
  19059. sqlite3_shutdown();
  19060. #endif
  19061. assert( argc>=1 && argv && argv[0] );
  19062. Argv0 = argv[0];
  19063. /* Make sure we have a valid signal handler early, before anything
  19064. ** else is done.
  19065. */
  19066. #ifdef SIGINT
  19067. signal(SIGINT, interrupt_handler);
  19068. #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
  19069. SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
  19070. #endif
  19071. #ifdef SQLITE_SHELL_DBNAME_PROC
  19072. {
  19073. /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
  19074. ** of a C-function that will provide the name of the database file. Use
  19075. ** this compile-time option to embed this shell program in larger
  19076. ** applications. */
  19077. extern void SQLITE_SHELL_DBNAME_PROC(const char**);
  19078. SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
  19079. warnInmemoryDb = 0;
  19080. }
  19081. #endif
  19082. /* Do an initial pass through the command-line argument to locate
  19083. ** the name of the database file, the name of the initialization file,
  19084. ** the size of the alternative malloc heap,
  19085. ** and the first command to execute.
  19086. */
  19087. verify_uninitialized();
  19088. for(i=1; i<argc; i++){
  19089. char *z;
  19090. z = argv[i];
  19091. if( z[0]!='-' ){
  19092. if( data.zDbFilename==0 ){
  19093. data.zDbFilename = z;
  19094. }else{
  19095. /* Excesss arguments are interpreted as SQL (or dot-commands) and
  19096. ** mean that nothing is read from stdin */
  19097. readStdin = 0;
  19098. nCmd++;
  19099. azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
  19100. if( azCmd==0 ) shell_out_of_memory();
  19101. azCmd[nCmd-1] = z;
  19102. }
  19103. }
  19104. if( z[1]=='-' ) z++;
  19105. if( strcmp(z,"-separator")==0
  19106. || strcmp(z,"-nullvalue")==0
  19107. || strcmp(z,"-newline")==0
  19108. || strcmp(z,"-cmd")==0
  19109. ){
  19110. (void)cmdline_option_value(argc, argv, ++i);
  19111. }else if( strcmp(z,"-init")==0 ){
  19112. zInitFile = cmdline_option_value(argc, argv, ++i);
  19113. }else if( strcmp(z,"-batch")==0 ){
  19114. /* Need to check for batch mode here to so we can avoid printing
  19115. ** informational messages (like from process_sqliterc) before
  19116. ** we do the actual processing of arguments later in a second pass.
  19117. */
  19118. stdin_is_interactive = 0;
  19119. }else if( strcmp(z,"-heap")==0 ){
  19120. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  19121. const char *zSize;
  19122. sqlite3_int64 szHeap;
  19123. zSize = cmdline_option_value(argc, argv, ++i);
  19124. szHeap = integerValue(zSize);
  19125. if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
  19126. sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
  19127. #else
  19128. (void)cmdline_option_value(argc, argv, ++i);
  19129. #endif
  19130. }else if( strcmp(z,"-pagecache")==0 ){
  19131. int n, sz;
  19132. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  19133. if( sz>70000 ) sz = 70000;
  19134. if( sz<0 ) sz = 0;
  19135. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  19136. sqlite3_config(SQLITE_CONFIG_PAGECACHE,
  19137. (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
  19138. data.shellFlgs |= SHFLG_Pagecache;
  19139. }else if( strcmp(z,"-lookaside")==0 ){
  19140. int n, sz;
  19141. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  19142. if( sz<0 ) sz = 0;
  19143. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  19144. if( n<0 ) n = 0;
  19145. sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
  19146. if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
  19147. #ifdef SQLITE_ENABLE_VFSTRACE
  19148. }else if( strcmp(z,"-vfstrace")==0 ){
  19149. extern int vfstrace_register(
  19150. const char *zTraceName,
  19151. const char *zOldVfsName,
  19152. int (*xOut)(const char*,void*),
  19153. void *pOutArg,
  19154. int makeDefault
  19155. );
  19156. vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
  19157. #endif
  19158. #ifdef SQLITE_ENABLE_MULTIPLEX
  19159. }else if( strcmp(z,"-multiplex")==0 ){
  19160. extern int sqlite3_multiple_initialize(const char*,int);
  19161. sqlite3_multiplex_initialize(0, 1);
  19162. #endif
  19163. }else if( strcmp(z,"-mmap")==0 ){
  19164. sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  19165. sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
  19166. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  19167. }else if( strcmp(z,"-sorterref")==0 ){
  19168. sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  19169. sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
  19170. #endif
  19171. }else if( strcmp(z,"-vfs")==0 ){
  19172. zVfs = cmdline_option_value(argc, argv, ++i);
  19173. #ifdef SQLITE_HAVE_ZLIB
  19174. }else if( strcmp(z,"-zip")==0 ){
  19175. data.openMode = SHELL_OPEN_ZIPFILE;
  19176. #endif
  19177. }else if( strcmp(z,"-append")==0 ){
  19178. data.openMode = SHELL_OPEN_APPENDVFS;
  19179. #ifdef SQLITE_ENABLE_DESERIALIZE
  19180. }else if( strcmp(z,"-deserialize")==0 ){
  19181. data.openMode = SHELL_OPEN_DESERIALIZE;
  19182. }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
  19183. data.szMax = integerValue(argv[++i]);
  19184. #endif
  19185. }else if( strcmp(z,"-readonly")==0 ){
  19186. data.openMode = SHELL_OPEN_READONLY;
  19187. }else if( strcmp(z,"-nofollow")==0 ){
  19188. data.openFlags = SQLITE_OPEN_NOFOLLOW;
  19189. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  19190. }else if( strncmp(z, "-A",2)==0 ){
  19191. /* All remaining command-line arguments are passed to the ".archive"
  19192. ** command, so ignore them */
  19193. break;
  19194. #endif
  19195. }else if( strcmp(z, "-memtrace")==0 ){
  19196. sqlite3MemTraceActivate(stderr);
  19197. }
  19198. }
  19199. verify_uninitialized();
  19200. #ifdef SQLITE_SHELL_INIT_PROC
  19201. {
  19202. /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
  19203. ** of a C-function that will perform initialization actions on SQLite that
  19204. ** occur just before or after sqlite3_initialize(). Use this compile-time
  19205. ** option to embed this shell program in larger applications. */
  19206. extern void SQLITE_SHELL_INIT_PROC(void);
  19207. SQLITE_SHELL_INIT_PROC();
  19208. }
  19209. #else
  19210. /* All the sqlite3_config() calls have now been made. So it is safe
  19211. ** to call sqlite3_initialize() and process any command line -vfs option. */
  19212. sqlite3_initialize();
  19213. #endif
  19214. if( zVfs ){
  19215. sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
  19216. if( pVfs ){
  19217. sqlite3_vfs_register(pVfs, 1);
  19218. }else{
  19219. utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
  19220. exit(1);
  19221. }
  19222. }
  19223. if( data.zDbFilename==0 ){
  19224. #ifndef SQLITE_OMIT_MEMORYDB
  19225. data.zDbFilename = ":memory:";
  19226. warnInmemoryDb = argc==1;
  19227. #else
  19228. utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
  19229. return 1;
  19230. #endif
  19231. }
  19232. data.out = stdout;
  19233. sqlite3_appendvfs_init(0,0,0);
  19234. /* Go ahead and open the database file if it already exists. If the
  19235. ** file does not exist, delay opening it. This prevents empty database
  19236. ** files from being created if a user mistypes the database name argument
  19237. ** to the sqlite command-line tool.
  19238. */
  19239. if( access(data.zDbFilename, 0)==0 ){
  19240. open_db(&data, 0);
  19241. }
  19242. /* Process the initialization file if there is one. If no -init option
  19243. ** is given on the command line, look for a file named ~/.sqliterc and
  19244. ** try to process it.
  19245. */
  19246. process_sqliterc(&data,zInitFile);
  19247. /* Make a second pass through the command-line argument and set
  19248. ** options. This second pass is delayed until after the initialization
  19249. ** file is processed so that the command-line arguments will override
  19250. ** settings in the initialization file.
  19251. */
  19252. for(i=1; i<argc; i++){
  19253. char *z = argv[i];
  19254. if( z[0]!='-' ) continue;
  19255. if( z[1]=='-' ){ z++; }
  19256. if( strcmp(z,"-init")==0 ){
  19257. i++;
  19258. }else if( strcmp(z,"-html")==0 ){
  19259. data.mode = MODE_Html;
  19260. }else if( strcmp(z,"-list")==0 ){
  19261. data.mode = MODE_List;
  19262. }else if( strcmp(z,"-quote")==0 ){
  19263. data.mode = MODE_Quote;
  19264. }else if( strcmp(z,"-line")==0 ){
  19265. data.mode = MODE_Line;
  19266. }else if( strcmp(z,"-column")==0 ){
  19267. data.mode = MODE_Column;
  19268. }else if( strcmp(z,"-json")==0 ){
  19269. data.mode = MODE_Json;
  19270. }else if( strcmp(z,"-markdown")==0 ){
  19271. data.mode = MODE_Markdown;
  19272. }else if( strcmp(z,"-table")==0 ){
  19273. data.mode = MODE_Table;
  19274. }else if( strcmp(z,"-box")==0 ){
  19275. data.mode = MODE_Box;
  19276. }else if( strcmp(z,"-csv")==0 ){
  19277. data.mode = MODE_Csv;
  19278. memcpy(data.colSeparator,",",2);
  19279. #ifdef SQLITE_HAVE_ZLIB
  19280. }else if( strcmp(z,"-zip")==0 ){
  19281. data.openMode = SHELL_OPEN_ZIPFILE;
  19282. #endif
  19283. }else if( strcmp(z,"-append")==0 ){
  19284. data.openMode = SHELL_OPEN_APPENDVFS;
  19285. #ifdef SQLITE_ENABLE_DESERIALIZE
  19286. }else if( strcmp(z,"-deserialize")==0 ){
  19287. data.openMode = SHELL_OPEN_DESERIALIZE;
  19288. }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
  19289. data.szMax = integerValue(argv[++i]);
  19290. #endif
  19291. }else if( strcmp(z,"-readonly")==0 ){
  19292. data.openMode = SHELL_OPEN_READONLY;
  19293. }else if( strcmp(z,"-nofollow")==0 ){
  19294. data.openFlags |= SQLITE_OPEN_NOFOLLOW;
  19295. }else if( strcmp(z,"-ascii")==0 ){
  19296. data.mode = MODE_Ascii;
  19297. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  19298. SEP_Unit);
  19299. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  19300. SEP_Record);
  19301. }else if( strcmp(z,"-separator")==0 ){
  19302. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  19303. "%s",cmdline_option_value(argc,argv,++i));
  19304. }else if( strcmp(z,"-newline")==0 ){
  19305. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  19306. "%s",cmdline_option_value(argc,argv,++i));
  19307. }else if( strcmp(z,"-nullvalue")==0 ){
  19308. sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
  19309. "%s",cmdline_option_value(argc,argv,++i));
  19310. }else if( strcmp(z,"-header")==0 ){
  19311. data.showHeader = 1;
  19312. }else if( strcmp(z,"-noheader")==0 ){
  19313. data.showHeader = 0;
  19314. }else if( strcmp(z,"-echo")==0 ){
  19315. ShellSetFlag(&data, SHFLG_Echo);
  19316. }else if( strcmp(z,"-eqp")==0 ){
  19317. data.autoEQP = AUTOEQP_on;
  19318. }else if( strcmp(z,"-eqpfull")==0 ){
  19319. data.autoEQP = AUTOEQP_full;
  19320. }else if( strcmp(z,"-stats")==0 ){
  19321. data.statsOn = 1;
  19322. }else if( strcmp(z,"-scanstats")==0 ){
  19323. data.scanstatsOn = 1;
  19324. }else if( strcmp(z,"-backslash")==0 ){
  19325. /* Undocumented command-line option: -backslash
  19326. ** Causes C-style backslash escapes to be evaluated in SQL statements
  19327. ** prior to sending the SQL into SQLite. Useful for injecting
  19328. ** crazy bytes in the middle of SQL statements for testing and debugging.
  19329. */
  19330. ShellSetFlag(&data, SHFLG_Backslash);
  19331. }else if( strcmp(z,"-bail")==0 ){
  19332. bail_on_error = 1;
  19333. }else if( strcmp(z,"-version")==0 ){
  19334. printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
  19335. return 0;
  19336. }else if( strcmp(z,"-interactive")==0 ){
  19337. stdin_is_interactive = 1;
  19338. }else if( strcmp(z,"-batch")==0 ){
  19339. stdin_is_interactive = 0;
  19340. }else if( strcmp(z,"-heap")==0 ){
  19341. i++;
  19342. }else if( strcmp(z,"-pagecache")==0 ){
  19343. i+=2;
  19344. }else if( strcmp(z,"-lookaside")==0 ){
  19345. i+=2;
  19346. }else if( strcmp(z,"-mmap")==0 ){
  19347. i++;
  19348. }else if( strcmp(z,"-memtrace")==0 ){
  19349. i++;
  19350. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  19351. }else if( strcmp(z,"-sorterref")==0 ){
  19352. i++;
  19353. #endif
  19354. }else if( strcmp(z,"-vfs")==0 ){
  19355. i++;
  19356. #ifdef SQLITE_ENABLE_VFSTRACE
  19357. }else if( strcmp(z,"-vfstrace")==0 ){
  19358. i++;
  19359. #endif
  19360. #ifdef SQLITE_ENABLE_MULTIPLEX
  19361. }else if( strcmp(z,"-multiplex")==0 ){
  19362. i++;
  19363. #endif
  19364. }else if( strcmp(z,"-help")==0 ){
  19365. usage(1);
  19366. }else if( strcmp(z,"-cmd")==0 ){
  19367. /* Run commands that follow -cmd first and separately from commands
  19368. ** that simply appear on the command-line. This seems goofy. It would
  19369. ** be better if all commands ran in the order that they appear. But
  19370. ** we retain the goofy behavior for historical compatibility. */
  19371. if( i==argc-1 ) break;
  19372. z = cmdline_option_value(argc,argv,++i);
  19373. if( z[0]=='.' ){
  19374. rc = do_meta_command(z, &data);
  19375. if( rc && bail_on_error ) return rc==2 ? 0 : rc;
  19376. }else{
  19377. open_db(&data, 0);
  19378. rc = shell_exec(&data, z, &zErrMsg);
  19379. if( zErrMsg!=0 ){
  19380. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  19381. if( bail_on_error ) return rc!=0 ? rc : 1;
  19382. }else if( rc!=0 ){
  19383. utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
  19384. if( bail_on_error ) return rc;
  19385. }
  19386. }
  19387. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  19388. }else if( strncmp(z, "-A", 2)==0 ){
  19389. if( nCmd>0 ){
  19390. utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
  19391. " with \"%s\"\n", z);
  19392. return 1;
  19393. }
  19394. open_db(&data, OPEN_DB_ZIPFILE);
  19395. if( z[2] ){
  19396. argv[i] = &z[2];
  19397. arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
  19398. }else{
  19399. arDotCommand(&data, 1, argv+i, argc-i);
  19400. }
  19401. readStdin = 0;
  19402. break;
  19403. #endif
  19404. }else{
  19405. utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
  19406. raw_printf(stderr,"Use -help for a list of options.\n");
  19407. return 1;
  19408. }
  19409. data.cMode = data.mode;
  19410. }
  19411. if( !readStdin ){
  19412. /* Run all arguments that do not begin with '-' as if they were separate
  19413. ** command-line inputs, except for the argToSkip argument which contains
  19414. ** the database filename.
  19415. */
  19416. for(i=0; i<nCmd; i++){
  19417. if( azCmd[i][0]=='.' ){
  19418. rc = do_meta_command(azCmd[i], &data);
  19419. if( rc ) return rc==2 ? 0 : rc;
  19420. }else{
  19421. open_db(&data, 0);
  19422. rc = shell_exec(&data, azCmd[i], &zErrMsg);
  19423. if( zErrMsg!=0 ){
  19424. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  19425. return rc!=0 ? rc : 1;
  19426. }else if( rc!=0 ){
  19427. utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
  19428. return rc;
  19429. }
  19430. }
  19431. }
  19432. free(azCmd);
  19433. }else{
  19434. /* Run commands received from standard input
  19435. */
  19436. if( stdin_is_interactive ){
  19437. char *zHome;
  19438. char *zHistory;
  19439. int nHistory;
  19440. printf(
  19441. "SQLite version %s %.19s\n" /*extra-version-info*/
  19442. "Enter \".help\" for usage hints.\n",
  19443. sqlite3_libversion(), sqlite3_sourceid()
  19444. );
  19445. if( warnInmemoryDb ){
  19446. printf("Connected to a ");
  19447. printBold("transient in-memory database");
  19448. printf(".\nUse \".open FILENAME\" to reopen on a "
  19449. "persistent database.\n");
  19450. }
  19451. zHistory = getenv("SQLITE_HISTORY");
  19452. if( zHistory ){
  19453. zHistory = strdup(zHistory);
  19454. }else if( (zHome = find_home_dir(0))!=0 ){
  19455. nHistory = strlen30(zHome) + 20;
  19456. if( (zHistory = malloc(nHistory))!=0 ){
  19457. sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  19458. }
  19459. }
  19460. if( zHistory ){ shell_read_history(zHistory); }
  19461. #if HAVE_READLINE || HAVE_EDITLINE
  19462. rl_attempted_completion_function = readline_completion;
  19463. #elif HAVE_LINENOISE
  19464. linenoiseSetCompletionCallback(linenoise_completion);
  19465. #endif
  19466. data.in = 0;
  19467. rc = process_input(&data);
  19468. if( zHistory ){
  19469. shell_stifle_history(2000);
  19470. shell_write_history(zHistory);
  19471. free(zHistory);
  19472. }
  19473. }else{
  19474. data.in = stdin;
  19475. rc = process_input(&data);
  19476. }
  19477. }
  19478. set_table_name(&data, 0);
  19479. if( data.db ){
  19480. session_close_all(&data);
  19481. close_db(data.db);
  19482. }
  19483. sqlite3_free(data.zFreeOnClose);
  19484. find_home_dir(1);
  19485. output_reset(&data);
  19486. data.doXdgOpen = 0;
  19487. clearTempFile(&data);
  19488. #if !SQLITE_SHELL_IS_UTF8
  19489. for(i=0; i<argcToFree; i++) free(argvToFree[i]);
  19490. free(argvToFree);
  19491. #endif
  19492. free(data.colWidth);
  19493. /* Clear the global data structure so that valgrind will detect memory
  19494. ** leaks */
  19495. memset(&data, 0, sizeof(data));
  19496. return rc;
  19497. }