shell.c 801 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580
  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. typedef unsigned int u32;
  38. typedef unsigned short int u16;
  39. /*
  40. ** Optionally #include a user-defined header, whereby compilation options
  41. ** may be set prior to where they take effect, but after platform setup.
  42. ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
  43. ** file. Note that this macro has a like effect on sqlite3.c compilation.
  44. */
  45. # define SHELL_STRINGIFY_(f) #f
  46. # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
  47. #ifdef SQLITE_CUSTOM_INCLUDE
  48. # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
  49. #endif
  50. /*
  51. ** Determine if we are dealing with WinRT, which provides only a subset of
  52. ** the full Win32 API.
  53. */
  54. #if !defined(SQLITE_OS_WINRT)
  55. # define SQLITE_OS_WINRT 0
  56. #endif
  57. /*
  58. ** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
  59. ** somewhat for use as a WASM module in a web browser. This flag
  60. ** should only be used when building the "fiddle" web application, as
  61. ** the browser-mode build has much different user input requirements
  62. ** and this build mode rewires the user input subsystem to account for
  63. ** that.
  64. */
  65. /*
  66. ** Warning pragmas copied from msvc.h in the core.
  67. */
  68. #if defined(_MSC_VER)
  69. #pragma warning(disable : 4054)
  70. #pragma warning(disable : 4055)
  71. #pragma warning(disable : 4100)
  72. #pragma warning(disable : 4127)
  73. #pragma warning(disable : 4130)
  74. #pragma warning(disable : 4152)
  75. #pragma warning(disable : 4189)
  76. #pragma warning(disable : 4206)
  77. #pragma warning(disable : 4210)
  78. #pragma warning(disable : 4232)
  79. #pragma warning(disable : 4244)
  80. #pragma warning(disable : 4305)
  81. #pragma warning(disable : 4306)
  82. #pragma warning(disable : 4702)
  83. #pragma warning(disable : 4706)
  84. #endif /* defined(_MSC_VER) */
  85. /*
  86. ** No support for loadable extensions in VxWorks.
  87. */
  88. #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
  89. # define SQLITE_OMIT_LOAD_EXTENSION 1
  90. #endif
  91. /*
  92. ** Enable large-file support for fopen() and friends on unix.
  93. */
  94. #ifndef SQLITE_DISABLE_LFS
  95. # define _LARGE_FILE 1
  96. # ifndef _FILE_OFFSET_BITS
  97. # define _FILE_OFFSET_BITS 64
  98. # endif
  99. # define _LARGEFILE_SOURCE 1
  100. #endif
  101. #if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE)
  102. /*
  103. ** emcc requires _POSIX_SOURCE (or one of several similar defines)
  104. ** to expose strdup().
  105. */
  106. # define _POSIX_SOURCE
  107. #endif
  108. #include <stdlib.h>
  109. #include <string.h>
  110. #include <stdio.h>
  111. #include <assert.h>
  112. #include "sqlite3.h"
  113. typedef sqlite3_int64 i64;
  114. typedef sqlite3_uint64 u64;
  115. typedef unsigned char u8;
  116. #if SQLITE_USER_AUTHENTICATION
  117. # include "sqlite3userauth.h"
  118. #endif
  119. #include <ctype.h>
  120. #include <stdarg.h>
  121. #if !defined(_WIN32) && !defined(WIN32)
  122. # include <signal.h>
  123. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  124. # include <pwd.h>
  125. # endif
  126. #endif
  127. #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
  128. # include <unistd.h>
  129. # include <dirent.h>
  130. # define GETPID getpid
  131. # if defined(__MINGW32__)
  132. # define DIRENT dirent
  133. # ifndef S_ISLNK
  134. # define S_ISLNK(mode) (0)
  135. # endif
  136. # endif
  137. #else
  138. # define GETPID (int)GetCurrentProcessId
  139. #endif
  140. #include <sys/types.h>
  141. #include <sys/stat.h>
  142. #if HAVE_READLINE
  143. # include <readline/readline.h>
  144. # include <readline/history.h>
  145. #endif
  146. #if HAVE_EDITLINE
  147. # include <editline/readline.h>
  148. #endif
  149. #if HAVE_EDITLINE || HAVE_READLINE
  150. # define shell_add_history(X) add_history(X)
  151. # define shell_read_history(X) read_history(X)
  152. # define shell_write_history(X) write_history(X)
  153. # define shell_stifle_history(X) stifle_history(X)
  154. # define shell_readline(X) readline(X)
  155. #elif HAVE_LINENOISE
  156. # include "linenoise.h"
  157. # define shell_add_history(X) linenoiseHistoryAdd(X)
  158. # define shell_read_history(X) linenoiseHistoryLoad(X)
  159. # define shell_write_history(X) linenoiseHistorySave(X)
  160. # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
  161. # define shell_readline(X) linenoise(X)
  162. #else
  163. # define shell_read_history(X)
  164. # define shell_write_history(X)
  165. # define shell_stifle_history(X)
  166. # define SHELL_USE_LOCAL_GETLINE 1
  167. #endif
  168. #if defined(_WIN32) || defined(WIN32)
  169. # if SQLITE_OS_WINRT
  170. # define SQLITE_OMIT_POPEN 1
  171. # else
  172. # include <io.h>
  173. # include <fcntl.h>
  174. # define isatty(h) _isatty(h)
  175. # ifndef access
  176. # define access(f,m) _access((f),(m))
  177. # endif
  178. # ifndef unlink
  179. # define unlink _unlink
  180. # endif
  181. # ifndef strdup
  182. # define strdup _strdup
  183. # endif
  184. # undef popen
  185. # define popen _popen
  186. # undef pclose
  187. # define pclose _pclose
  188. # endif
  189. #else
  190. /* Make sure isatty() has a prototype. */
  191. extern int isatty(int);
  192. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  193. /* popen and pclose are not C89 functions and so are
  194. ** sometimes omitted from the <stdio.h> header */
  195. extern FILE *popen(const char*,const char*);
  196. extern int pclose(FILE*);
  197. # else
  198. # define SQLITE_OMIT_POPEN 1
  199. # endif
  200. #endif
  201. #if defined(_WIN32_WCE)
  202. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
  203. * thus we always assume that we have a console. That can be
  204. * overridden with the -batch command line option.
  205. */
  206. #define isatty(x) 1
  207. #endif
  208. /* ctype macros that work with signed characters */
  209. #define IsSpace(X) isspace((unsigned char)X)
  210. #define IsDigit(X) isdigit((unsigned char)X)
  211. #define ToLower(X) (char)tolower((unsigned char)X)
  212. #if defined(_WIN32) || defined(WIN32)
  213. #if SQLITE_OS_WINRT
  214. #include <intrin.h>
  215. #endif
  216. #include <windows.h>
  217. /* string conversion routines only needed on Win32 */
  218. extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
  219. extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
  220. extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
  221. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
  222. #endif
  223. /* On Windows, we normally run with output mode of TEXT so that \n characters
  224. ** are automatically translated into \r\n. However, this behavior needs
  225. ** to be disabled in some cases (ex: when generating CSV output and when
  226. ** rendering quoted strings that contain \n characters). The following
  227. ** routines take care of that.
  228. */
  229. #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
  230. static void setBinaryMode(FILE *file, int isOutput){
  231. if( isOutput ) fflush(file);
  232. _setmode(_fileno(file), _O_BINARY);
  233. }
  234. static void setTextMode(FILE *file, int isOutput){
  235. if( isOutput ) fflush(file);
  236. _setmode(_fileno(file), _O_TEXT);
  237. }
  238. #else
  239. # define setBinaryMode(X,Y)
  240. # define setTextMode(X,Y)
  241. #endif
  242. /* True if the timer is enabled */
  243. static int enableTimer = 0;
  244. /* A version of strcmp() that works with NULL values */
  245. static int cli_strcmp(const char *a, const char *b){
  246. if( a==0 ) a = "";
  247. if( b==0 ) b = "";
  248. return strcmp(a,b);
  249. }
  250. static int cli_strncmp(const char *a, const char *b, size_t n){
  251. if( a==0 ) a = "";
  252. if( b==0 ) b = "";
  253. return strncmp(a,b,n);
  254. }
  255. /* Return the current wall-clock time */
  256. static sqlite3_int64 timeOfDay(void){
  257. static sqlite3_vfs *clockVfs = 0;
  258. sqlite3_int64 t;
  259. if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
  260. if( clockVfs==0 ) return 0; /* Never actually happens */
  261. if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
  262. clockVfs->xCurrentTimeInt64(clockVfs, &t);
  263. }else{
  264. double r;
  265. clockVfs->xCurrentTime(clockVfs, &r);
  266. t = (sqlite3_int64)(r*86400000.0);
  267. }
  268. return t;
  269. }
  270. #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
  271. #include <sys/time.h>
  272. #include <sys/resource.h>
  273. /* VxWorks does not support getrusage() as far as we can determine */
  274. #if defined(_WRS_KERNEL) || defined(__RTP__)
  275. struct rusage {
  276. struct timeval ru_utime; /* user CPU time used */
  277. struct timeval ru_stime; /* system CPU time used */
  278. };
  279. #define getrusage(A,B) memset(B,0,sizeof(*B))
  280. #endif
  281. /* Saved resource information for the beginning of an operation */
  282. static struct rusage sBegin; /* CPU time at start */
  283. static sqlite3_int64 iBegin; /* Wall-clock time at start */
  284. /*
  285. ** Begin timing an operation
  286. */
  287. static void beginTimer(void){
  288. if( enableTimer ){
  289. getrusage(RUSAGE_SELF, &sBegin);
  290. iBegin = timeOfDay();
  291. }
  292. }
  293. /* Return the difference of two time_structs in seconds */
  294. static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  295. return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
  296. (double)(pEnd->tv_sec - pStart->tv_sec);
  297. }
  298. /*
  299. ** Print the timing results.
  300. */
  301. static void endTimer(void){
  302. if( enableTimer ){
  303. sqlite3_int64 iEnd = timeOfDay();
  304. struct rusage sEnd;
  305. getrusage(RUSAGE_SELF, &sEnd);
  306. printf("Run Time: real %.3f user %f sys %f\n",
  307. (iEnd - iBegin)*0.001,
  308. timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
  309. timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  310. }
  311. }
  312. #define BEGIN_TIMER beginTimer()
  313. #define END_TIMER endTimer()
  314. #define HAS_TIMER 1
  315. #elif (defined(_WIN32) || defined(WIN32))
  316. /* Saved resource information for the beginning of an operation */
  317. static HANDLE hProcess;
  318. static FILETIME ftKernelBegin;
  319. static FILETIME ftUserBegin;
  320. static sqlite3_int64 ftWallBegin;
  321. typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
  322. LPFILETIME, LPFILETIME);
  323. static GETPROCTIMES getProcessTimesAddr = NULL;
  324. /*
  325. ** Check to see if we have timer support. Return 1 if necessary
  326. ** support found (or found previously).
  327. */
  328. static int hasTimer(void){
  329. if( getProcessTimesAddr ){
  330. return 1;
  331. } else {
  332. #if !SQLITE_OS_WINRT
  333. /* GetProcessTimes() isn't supported in WIN95 and some other Windows
  334. ** versions. See if the version we are running on has it, and if it
  335. ** does, save off a pointer to it and the current process handle.
  336. */
  337. hProcess = GetCurrentProcess();
  338. if( hProcess ){
  339. HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
  340. if( NULL != hinstLib ){
  341. getProcessTimesAddr =
  342. (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
  343. if( NULL != getProcessTimesAddr ){
  344. return 1;
  345. }
  346. FreeLibrary(hinstLib);
  347. }
  348. }
  349. #endif
  350. }
  351. return 0;
  352. }
  353. /*
  354. ** Begin timing an operation
  355. */
  356. static void beginTimer(void){
  357. if( enableTimer && getProcessTimesAddr ){
  358. FILETIME ftCreation, ftExit;
  359. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
  360. &ftKernelBegin,&ftUserBegin);
  361. ftWallBegin = timeOfDay();
  362. }
  363. }
  364. /* Return the difference of two FILETIME structs in seconds */
  365. static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
  366. sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
  367. sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
  368. return (double) ((i64End - i64Start) / 10000000.0);
  369. }
  370. /*
  371. ** Print the timing results.
  372. */
  373. static void endTimer(void){
  374. if( enableTimer && getProcessTimesAddr){
  375. FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
  376. sqlite3_int64 ftWallEnd = timeOfDay();
  377. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
  378. printf("Run Time: real %.3f user %f sys %f\n",
  379. (ftWallEnd - ftWallBegin)*0.001,
  380. timeDiff(&ftUserBegin, &ftUserEnd),
  381. timeDiff(&ftKernelBegin, &ftKernelEnd));
  382. }
  383. }
  384. #define BEGIN_TIMER beginTimer()
  385. #define END_TIMER endTimer()
  386. #define HAS_TIMER hasTimer()
  387. #else
  388. #define BEGIN_TIMER
  389. #define END_TIMER
  390. #define HAS_TIMER 0
  391. #endif
  392. /*
  393. ** Used to prevent warnings about unused parameters
  394. */
  395. #define UNUSED_PARAMETER(x) (void)(x)
  396. /*
  397. ** Number of elements in an array
  398. */
  399. #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
  400. /*
  401. ** If the following flag is set, then command execution stops
  402. ** at an error if we are not interactive.
  403. */
  404. static int bail_on_error = 0;
  405. /*
  406. ** Threat stdin as an interactive input if the following variable
  407. ** is true. Otherwise, assume stdin is connected to a file or pipe.
  408. */
  409. static int stdin_is_interactive = 1;
  410. /*
  411. ** On Windows systems we have to know if standard output is a console
  412. ** in order to translate UTF-8 into MBCS. The following variable is
  413. ** true if translation is required.
  414. */
  415. static int stdout_is_console = 1;
  416. /*
  417. ** The following is the open SQLite database. We make a pointer
  418. ** to this database a static variable so that it can be accessed
  419. ** by the SIGINT handler to interrupt database processing.
  420. */
  421. static sqlite3 *globalDb = 0;
  422. /*
  423. ** True if an interrupt (Control-C) has been received.
  424. */
  425. static volatile int seenInterrupt = 0;
  426. /*
  427. ** This is the name of our program. It is set in main(), used
  428. ** in a number of other places, mostly for error messages.
  429. */
  430. static char *Argv0;
  431. /*
  432. ** Prompt strings. Initialized in main. Settable with
  433. ** .prompt main continue
  434. */
  435. static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
  436. static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
  437. /*
  438. ** Render output like fprintf(). Except, if the output is going to the
  439. ** console and if this is running on a Windows machine, translate the
  440. ** output from UTF-8 into MBCS.
  441. */
  442. #if defined(_WIN32) || defined(WIN32)
  443. void utf8_printf(FILE *out, const char *zFormat, ...){
  444. va_list ap;
  445. va_start(ap, zFormat);
  446. if( stdout_is_console && (out==stdout || out==stderr) ){
  447. char *z1 = sqlite3_vmprintf(zFormat, ap);
  448. char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
  449. sqlite3_free(z1);
  450. fputs(z2, out);
  451. sqlite3_free(z2);
  452. }else{
  453. vfprintf(out, zFormat, ap);
  454. }
  455. va_end(ap);
  456. }
  457. #elif !defined(utf8_printf)
  458. # define utf8_printf fprintf
  459. #endif
  460. /*
  461. ** Render output like fprintf(). This should not be used on anything that
  462. ** includes string formatting (e.g. "%s").
  463. */
  464. #if !defined(raw_printf)
  465. # define raw_printf fprintf
  466. #endif
  467. /* Indicate out-of-memory and exit. */
  468. static void shell_out_of_memory(void){
  469. raw_printf(stderr,"Error: out of memory\n");
  470. exit(1);
  471. }
  472. /* Check a pointer to see if it is NULL. If it is NULL, exit with an
  473. ** out-of-memory error.
  474. */
  475. static void shell_check_oom(void *p){
  476. if( p==0 ) shell_out_of_memory();
  477. }
  478. /*
  479. ** Write I/O traces to the following stream.
  480. */
  481. #ifdef SQLITE_ENABLE_IOTRACE
  482. static FILE *iotrace = 0;
  483. #endif
  484. /*
  485. ** This routine works like printf in that its first argument is a
  486. ** format string and subsequent arguments are values to be substituted
  487. ** in place of % fields. The result of formatting this string
  488. ** is written to iotrace.
  489. */
  490. #ifdef SQLITE_ENABLE_IOTRACE
  491. static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
  492. va_list ap;
  493. char *z;
  494. if( iotrace==0 ) return;
  495. va_start(ap, zFormat);
  496. z = sqlite3_vmprintf(zFormat, ap);
  497. va_end(ap);
  498. utf8_printf(iotrace, "%s", z);
  499. sqlite3_free(z);
  500. }
  501. #endif
  502. /*
  503. ** Output string zUtf to stream pOut as w characters. If w is negative,
  504. ** then right-justify the text. W is the width in UTF-8 characters, not
  505. ** in bytes. This is different from the %*.*s specification in printf
  506. ** since with %*.*s the width is measured in bytes, not characters.
  507. */
  508. static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
  509. int i;
  510. int n;
  511. int aw = w<0 ? -w : w;
  512. if( zUtf==0 ) zUtf = "";
  513. for(i=n=0; zUtf[i]; i++){
  514. if( (zUtf[i]&0xc0)!=0x80 ){
  515. n++;
  516. if( n==aw ){
  517. do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
  518. break;
  519. }
  520. }
  521. }
  522. if( n>=aw ){
  523. utf8_printf(pOut, "%.*s", i, zUtf);
  524. }else if( w<0 ){
  525. utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
  526. }else{
  527. utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
  528. }
  529. }
  530. /*
  531. ** Determines if a string is a number of not.
  532. */
  533. static int isNumber(const char *z, int *realnum){
  534. if( *z=='-' || *z=='+' ) z++;
  535. if( !IsDigit(*z) ){
  536. return 0;
  537. }
  538. z++;
  539. if( realnum ) *realnum = 0;
  540. while( IsDigit(*z) ){ z++; }
  541. if( *z=='.' ){
  542. z++;
  543. if( !IsDigit(*z) ) return 0;
  544. while( IsDigit(*z) ){ z++; }
  545. if( realnum ) *realnum = 1;
  546. }
  547. if( *z=='e' || *z=='E' ){
  548. z++;
  549. if( *z=='+' || *z=='-' ) z++;
  550. if( !IsDigit(*z) ) return 0;
  551. while( IsDigit(*z) ){ z++; }
  552. if( realnum ) *realnum = 1;
  553. }
  554. return *z==0;
  555. }
  556. /*
  557. ** Compute a string length that is limited to what can be stored in
  558. ** lower 30 bits of a 32-bit signed integer.
  559. */
  560. static int strlen30(const char *z){
  561. const char *z2 = z;
  562. while( *z2 ){ z2++; }
  563. return 0x3fffffff & (int)(z2 - z);
  564. }
  565. /*
  566. ** Return the length of a string in characters. Multibyte UTF8 characters
  567. ** count as a single character.
  568. */
  569. static int strlenChar(const char *z){
  570. int n = 0;
  571. while( *z ){
  572. if( (0xc0&*(z++))!=0x80 ) n++;
  573. }
  574. return n;
  575. }
  576. /*
  577. ** Return open FILE * if zFile exists, can be opened for read
  578. ** and is an ordinary file or a character stream source.
  579. ** Otherwise return 0.
  580. */
  581. static FILE * openChrSource(const char *zFile){
  582. #ifdef _WIN32
  583. struct _stat x = {0};
  584. # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
  585. /* On Windows, open first, then check the stream nature. This order
  586. ** is necessary because _stat() and sibs, when checking a named pipe,
  587. ** effectively break the pipe as its supplier sees it. */
  588. FILE *rv = fopen(zFile, "rb");
  589. if( rv==0 ) return 0;
  590. if( _fstat(_fileno(rv), &x) != 0
  591. || !STAT_CHR_SRC(x.st_mode)){
  592. fclose(rv);
  593. rv = 0;
  594. }
  595. return rv;
  596. #else
  597. struct stat x = {0};
  598. int rc = stat(zFile, &x);
  599. # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
  600. if( rc!=0 ) return 0;
  601. if( STAT_CHR_SRC(x.st_mode) ){
  602. return fopen(zFile, "rb");
  603. }else{
  604. return 0;
  605. }
  606. #endif
  607. #undef STAT_CHR_SRC
  608. }
  609. /*
  610. ** This routine reads a line of text from FILE in, stores
  611. ** the text in memory obtained from malloc() and returns a pointer
  612. ** to the text. NULL is returned at end of file, or if malloc()
  613. ** fails.
  614. **
  615. ** If zLine is not NULL then it is a malloced buffer returned from
  616. ** a previous call to this routine that may be reused.
  617. */
  618. static char *local_getline(char *zLine, FILE *in){
  619. int nLine = zLine==0 ? 0 : 100;
  620. int n = 0;
  621. while( 1 ){
  622. if( n+100>nLine ){
  623. nLine = nLine*2 + 100;
  624. zLine = realloc(zLine, nLine);
  625. shell_check_oom(zLine);
  626. }
  627. if( fgets(&zLine[n], nLine - n, in)==0 ){
  628. if( n==0 ){
  629. free(zLine);
  630. return 0;
  631. }
  632. zLine[n] = 0;
  633. break;
  634. }
  635. while( zLine[n] ) n++;
  636. if( n>0 && zLine[n-1]=='\n' ){
  637. n--;
  638. if( n>0 && zLine[n-1]=='\r' ) n--;
  639. zLine[n] = 0;
  640. break;
  641. }
  642. }
  643. #if defined(_WIN32) || defined(WIN32)
  644. /* For interactive input on Windows systems, translate the
  645. ** multi-byte characterset characters into UTF-8. */
  646. if( stdin_is_interactive && in==stdin ){
  647. char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
  648. if( zTrans ){
  649. i64 nTrans = strlen(zTrans)+1;
  650. if( nTrans>nLine ){
  651. zLine = realloc(zLine, nTrans);
  652. shell_check_oom(zLine);
  653. }
  654. memcpy(zLine, zTrans, nTrans);
  655. sqlite3_free(zTrans);
  656. }
  657. }
  658. #endif /* defined(_WIN32) || defined(WIN32) */
  659. return zLine;
  660. }
  661. /*
  662. ** Retrieve a single line of input text.
  663. **
  664. ** If in==0 then read from standard input and prompt before each line.
  665. ** If isContinuation is true, then a continuation prompt is appropriate.
  666. ** If isContinuation is zero, then the main prompt should be used.
  667. **
  668. ** If zPrior is not NULL then it is a buffer from a prior call to this
  669. ** routine that can be reused.
  670. **
  671. ** The result is stored in space obtained from malloc() and must either
  672. ** be freed by the caller or else passed back into this routine via the
  673. ** zPrior argument for reuse.
  674. */
  675. #ifndef SQLITE_SHELL_FIDDLE
  676. static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
  677. char *zPrompt;
  678. char *zResult;
  679. if( in!=0 ){
  680. zResult = local_getline(zPrior, in);
  681. }else{
  682. zPrompt = isContinuation ? continuePrompt : mainPrompt;
  683. #if SHELL_USE_LOCAL_GETLINE
  684. printf("%s", zPrompt);
  685. fflush(stdout);
  686. zResult = local_getline(zPrior, stdin);
  687. #else
  688. free(zPrior);
  689. zResult = shell_readline(zPrompt);
  690. if( zResult && *zResult ) shell_add_history(zResult);
  691. #endif
  692. }
  693. return zResult;
  694. }
  695. #endif /* !SQLITE_SHELL_FIDDLE */
  696. /*
  697. ** Return the value of a hexadecimal digit. Return -1 if the input
  698. ** is not a hex digit.
  699. */
  700. static int hexDigitValue(char c){
  701. if( c>='0' && c<='9' ) return c - '0';
  702. if( c>='a' && c<='f' ) return c - 'a' + 10;
  703. if( c>='A' && c<='F' ) return c - 'A' + 10;
  704. return -1;
  705. }
  706. /*
  707. ** Interpret zArg as an integer value, possibly with suffixes.
  708. */
  709. static sqlite3_int64 integerValue(const char *zArg){
  710. sqlite3_int64 v = 0;
  711. static const struct { char *zSuffix; int iMult; } aMult[] = {
  712. { "KiB", 1024 },
  713. { "MiB", 1024*1024 },
  714. { "GiB", 1024*1024*1024 },
  715. { "KB", 1000 },
  716. { "MB", 1000000 },
  717. { "GB", 1000000000 },
  718. { "K", 1000 },
  719. { "M", 1000000 },
  720. { "G", 1000000000 },
  721. };
  722. int i;
  723. int isNeg = 0;
  724. if( zArg[0]=='-' ){
  725. isNeg = 1;
  726. zArg++;
  727. }else if( zArg[0]=='+' ){
  728. zArg++;
  729. }
  730. if( zArg[0]=='0' && zArg[1]=='x' ){
  731. int x;
  732. zArg += 2;
  733. while( (x = hexDigitValue(zArg[0]))>=0 ){
  734. v = (v<<4) + x;
  735. zArg++;
  736. }
  737. }else{
  738. while( IsDigit(zArg[0]) ){
  739. v = v*10 + zArg[0] - '0';
  740. zArg++;
  741. }
  742. }
  743. for(i=0; i<ArraySize(aMult); i++){
  744. if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
  745. v *= aMult[i].iMult;
  746. break;
  747. }
  748. }
  749. return isNeg? -v : v;
  750. }
  751. /*
  752. ** A variable length string to which one can append text.
  753. */
  754. typedef struct ShellText ShellText;
  755. struct ShellText {
  756. char *z;
  757. int n;
  758. int nAlloc;
  759. };
  760. /*
  761. ** Initialize and destroy a ShellText object
  762. */
  763. static void initText(ShellText *p){
  764. memset(p, 0, sizeof(*p));
  765. }
  766. static void freeText(ShellText *p){
  767. free(p->z);
  768. initText(p);
  769. }
  770. /* zIn is either a pointer to a NULL-terminated string in memory obtained
  771. ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  772. ** added to zIn, and the result returned in memory obtained from malloc().
  773. ** zIn, if it was not NULL, is freed.
  774. **
  775. ** If the third argument, quote, is not '\0', then it is used as a
  776. ** quote character for zAppend.
  777. */
  778. static void appendText(ShellText *p, const char *zAppend, char quote){
  779. i64 len;
  780. i64 i;
  781. i64 nAppend = strlen30(zAppend);
  782. len = nAppend+p->n+1;
  783. if( quote ){
  784. len += 2;
  785. for(i=0; i<nAppend; i++){
  786. if( zAppend[i]==quote ) len++;
  787. }
  788. }
  789. if( p->z==0 || p->n+len>=p->nAlloc ){
  790. p->nAlloc = p->nAlloc*2 + len + 20;
  791. p->z = realloc(p->z, p->nAlloc);
  792. shell_check_oom(p->z);
  793. }
  794. if( quote ){
  795. char *zCsr = p->z+p->n;
  796. *zCsr++ = quote;
  797. for(i=0; i<nAppend; i++){
  798. *zCsr++ = zAppend[i];
  799. if( zAppend[i]==quote ) *zCsr++ = quote;
  800. }
  801. *zCsr++ = quote;
  802. p->n = (int)(zCsr - p->z);
  803. *zCsr = '\0';
  804. }else{
  805. memcpy(p->z+p->n, zAppend, nAppend);
  806. p->n += nAppend;
  807. p->z[p->n] = '\0';
  808. }
  809. }
  810. /*
  811. ** Attempt to determine if identifier zName needs to be quoted, either
  812. ** because it contains non-alphanumeric characters, or because it is an
  813. ** SQLite keyword. Be conservative in this estimate: When in doubt assume
  814. ** that quoting is required.
  815. **
  816. ** Return '"' if quoting is required. Return 0 if no quoting is required.
  817. */
  818. static char quoteChar(const char *zName){
  819. int i;
  820. if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
  821. for(i=0; zName[i]; i++){
  822. if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
  823. }
  824. return sqlite3_keyword_check(zName, i) ? '"' : 0;
  825. }
  826. /*
  827. ** Construct a fake object name and column list to describe the structure
  828. ** of the view, virtual table, or table valued function zSchema.zName.
  829. */
  830. static char *shellFakeSchema(
  831. sqlite3 *db, /* The database connection containing the vtab */
  832. const char *zSchema, /* Schema of the database holding the vtab */
  833. const char *zName /* The name of the virtual table */
  834. ){
  835. sqlite3_stmt *pStmt = 0;
  836. char *zSql;
  837. ShellText s;
  838. char cQuote;
  839. char *zDiv = "(";
  840. int nRow = 0;
  841. zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
  842. zSchema ? zSchema : "main", zName);
  843. shell_check_oom(zSql);
  844. sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  845. sqlite3_free(zSql);
  846. initText(&s);
  847. if( zSchema ){
  848. cQuote = quoteChar(zSchema);
  849. if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
  850. appendText(&s, zSchema, cQuote);
  851. appendText(&s, ".", 0);
  852. }
  853. cQuote = quoteChar(zName);
  854. appendText(&s, zName, cQuote);
  855. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  856. const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
  857. nRow++;
  858. appendText(&s, zDiv, 0);
  859. zDiv = ",";
  860. if( zCol==0 ) zCol = "";
  861. cQuote = quoteChar(zCol);
  862. appendText(&s, zCol, cQuote);
  863. }
  864. appendText(&s, ")", 0);
  865. sqlite3_finalize(pStmt);
  866. if( nRow==0 ){
  867. freeText(&s);
  868. s.z = 0;
  869. }
  870. return s.z;
  871. }
  872. /*
  873. ** SQL function: shell_module_schema(X)
  874. **
  875. ** Return a fake schema for the table-valued function or eponymous virtual
  876. ** table X.
  877. */
  878. static void shellModuleSchema(
  879. sqlite3_context *pCtx,
  880. int nVal,
  881. sqlite3_value **apVal
  882. ){
  883. const char *zName;
  884. char *zFake;
  885. UNUSED_PARAMETER(nVal);
  886. zName = (const char*)sqlite3_value_text(apVal[0]);
  887. zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
  888. if( zFake ){
  889. sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
  890. -1, sqlite3_free);
  891. free(zFake);
  892. }
  893. }
  894. /*
  895. ** SQL function: shell_add_schema(S,X)
  896. **
  897. ** Add the schema name X to the CREATE statement in S and return the result.
  898. ** Examples:
  899. **
  900. ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
  901. **
  902. ** Also works on
  903. **
  904. ** CREATE INDEX
  905. ** CREATE UNIQUE INDEX
  906. ** CREATE VIEW
  907. ** CREATE TRIGGER
  908. ** CREATE VIRTUAL TABLE
  909. **
  910. ** This UDF is used by the .schema command to insert the schema name of
  911. ** attached databases into the middle of the sqlite_schema.sql field.
  912. */
  913. static void shellAddSchemaName(
  914. sqlite3_context *pCtx,
  915. int nVal,
  916. sqlite3_value **apVal
  917. ){
  918. static const char *aPrefix[] = {
  919. "TABLE",
  920. "INDEX",
  921. "UNIQUE INDEX",
  922. "VIEW",
  923. "TRIGGER",
  924. "VIRTUAL TABLE"
  925. };
  926. int i = 0;
  927. const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
  928. const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
  929. const char *zName = (const char*)sqlite3_value_text(apVal[2]);
  930. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  931. UNUSED_PARAMETER(nVal);
  932. if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
  933. for(i=0; i<ArraySize(aPrefix); i++){
  934. int n = strlen30(aPrefix[i]);
  935. if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
  936. char *z = 0;
  937. char *zFake = 0;
  938. if( zSchema ){
  939. char cQuote = quoteChar(zSchema);
  940. if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
  941. z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
  942. }else{
  943. z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
  944. }
  945. }
  946. if( zName
  947. && aPrefix[i][0]=='V'
  948. && (zFake = shellFakeSchema(db, zSchema, zName))!=0
  949. ){
  950. if( z==0 ){
  951. z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
  952. }else{
  953. z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
  954. }
  955. free(zFake);
  956. }
  957. if( z ){
  958. sqlite3_result_text(pCtx, z, -1, sqlite3_free);
  959. return;
  960. }
  961. }
  962. }
  963. }
  964. sqlite3_result_value(pCtx, apVal[0]);
  965. }
  966. /*
  967. ** The source code for several run-time loadable extensions is inserted
  968. ** below by the ../tool/mkshellc.tcl script. Before processing that included
  969. ** code, we need to override some macros to make the included program code
  970. ** work here in the middle of this regular program.
  971. */
  972. #define SQLITE_EXTENSION_INIT1
  973. #define SQLITE_EXTENSION_INIT2(X) (void)(X)
  974. #if defined(_WIN32) && defined(_MSC_VER)
  975. /************************* Begin test_windirent.h ******************/
  976. /*
  977. ** 2015 November 30
  978. **
  979. ** The author disclaims copyright to this source code. In place of
  980. ** a legal notice, here is a blessing:
  981. **
  982. ** May you do good and not evil.
  983. ** May you find forgiveness for yourself and forgive others.
  984. ** May you share freely, never taking more than you give.
  985. **
  986. *************************************************************************
  987. ** This file contains declarations for most of the opendir() family of
  988. ** POSIX functions on Win32 using the MSVCRT.
  989. */
  990. #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
  991. #define SQLITE_WINDIRENT_H
  992. /*
  993. ** We need several data types from the Windows SDK header.
  994. */
  995. #ifndef WIN32_LEAN_AND_MEAN
  996. #define WIN32_LEAN_AND_MEAN
  997. #endif
  998. #include "windows.h"
  999. /*
  1000. ** We need several support functions from the SQLite core.
  1001. */
  1002. /* #include "sqlite3.h" */
  1003. /*
  1004. ** We need several things from the ANSI and MSVCRT headers.
  1005. */
  1006. #include <stdio.h>
  1007. #include <stdlib.h>
  1008. #include <errno.h>
  1009. #include <io.h>
  1010. #include <limits.h>
  1011. #include <sys/types.h>
  1012. #include <sys/stat.h>
  1013. /*
  1014. ** We may need several defines that should have been in "sys/stat.h".
  1015. */
  1016. #ifndef S_ISREG
  1017. #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
  1018. #endif
  1019. #ifndef S_ISDIR
  1020. #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
  1021. #endif
  1022. #ifndef S_ISLNK
  1023. #define S_ISLNK(mode) (0)
  1024. #endif
  1025. /*
  1026. ** We may need to provide the "mode_t" type.
  1027. */
  1028. #ifndef MODE_T_DEFINED
  1029. #define MODE_T_DEFINED
  1030. typedef unsigned short mode_t;
  1031. #endif
  1032. /*
  1033. ** We may need to provide the "ino_t" type.
  1034. */
  1035. #ifndef INO_T_DEFINED
  1036. #define INO_T_DEFINED
  1037. typedef unsigned short ino_t;
  1038. #endif
  1039. /*
  1040. ** We need to define "NAME_MAX" if it was not present in "limits.h".
  1041. */
  1042. #ifndef NAME_MAX
  1043. # ifdef FILENAME_MAX
  1044. # define NAME_MAX (FILENAME_MAX)
  1045. # else
  1046. # define NAME_MAX (260)
  1047. # endif
  1048. #endif
  1049. /*
  1050. ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
  1051. */
  1052. #ifndef NULL_INTPTR_T
  1053. # define NULL_INTPTR_T ((intptr_t)(0))
  1054. #endif
  1055. #ifndef BAD_INTPTR_T
  1056. # define BAD_INTPTR_T ((intptr_t)(-1))
  1057. #endif
  1058. /*
  1059. ** We need to provide the necessary structures and related types.
  1060. */
  1061. #ifndef DIRENT_DEFINED
  1062. #define DIRENT_DEFINED
  1063. typedef struct DIRENT DIRENT;
  1064. typedef DIRENT *LPDIRENT;
  1065. struct DIRENT {
  1066. ino_t d_ino; /* Sequence number, do not use. */
  1067. unsigned d_attributes; /* Win32 file attributes. */
  1068. char d_name[NAME_MAX + 1]; /* Name within the directory. */
  1069. };
  1070. #endif
  1071. #ifndef DIR_DEFINED
  1072. #define DIR_DEFINED
  1073. typedef struct DIR DIR;
  1074. typedef DIR *LPDIR;
  1075. struct DIR {
  1076. intptr_t d_handle; /* Value returned by "_findfirst". */
  1077. DIRENT d_first; /* DIRENT constructed based on "_findfirst". */
  1078. DIRENT d_next; /* DIRENT constructed based on "_findnext". */
  1079. };
  1080. #endif
  1081. /*
  1082. ** Provide a macro, for use by the implementation, to determine if a
  1083. ** particular directory entry should be skipped over when searching for
  1084. ** the next directory entry that should be returned by the readdir() or
  1085. ** readdir_r() functions.
  1086. */
  1087. #ifndef is_filtered
  1088. # define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
  1089. #endif
  1090. /*
  1091. ** Provide the function prototype for the POSIX compatiable getenv()
  1092. ** function. This function is not thread-safe.
  1093. */
  1094. extern const char *windirent_getenv(const char *name);
  1095. /*
  1096. ** Finally, we can provide the function prototypes for the opendir(),
  1097. ** readdir(), readdir_r(), and closedir() POSIX functions.
  1098. */
  1099. extern LPDIR opendir(const char *dirname);
  1100. extern LPDIRENT readdir(LPDIR dirp);
  1101. extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
  1102. extern INT closedir(LPDIR dirp);
  1103. #endif /* defined(WIN32) && defined(_MSC_VER) */
  1104. /************************* End test_windirent.h ********************/
  1105. /************************* Begin test_windirent.c ******************/
  1106. /*
  1107. ** 2015 November 30
  1108. **
  1109. ** The author disclaims copyright to this source code. In place of
  1110. ** a legal notice, here is a blessing:
  1111. **
  1112. ** May you do good and not evil.
  1113. ** May you find forgiveness for yourself and forgive others.
  1114. ** May you share freely, never taking more than you give.
  1115. **
  1116. *************************************************************************
  1117. ** This file contains code to implement most of the opendir() family of
  1118. ** POSIX functions on Win32 using the MSVCRT.
  1119. */
  1120. #if defined(_WIN32) && defined(_MSC_VER)
  1121. /* #include "test_windirent.h" */
  1122. /*
  1123. ** Implementation of the POSIX getenv() function using the Win32 API.
  1124. ** This function is not thread-safe.
  1125. */
  1126. const char *windirent_getenv(
  1127. const char *name
  1128. ){
  1129. static char value[32768]; /* Maximum length, per MSDN */
  1130. DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
  1131. DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
  1132. memset(value, 0, sizeof(value));
  1133. dwRet = GetEnvironmentVariableA(name, value, dwSize);
  1134. if( dwRet==0 || dwRet>dwSize ){
  1135. /*
  1136. ** The function call to GetEnvironmentVariableA() failed -OR-
  1137. ** the buffer is not large enough. Either way, return NULL.
  1138. */
  1139. return 0;
  1140. }else{
  1141. /*
  1142. ** The function call to GetEnvironmentVariableA() succeeded
  1143. ** -AND- the buffer contains the entire value.
  1144. */
  1145. return value;
  1146. }
  1147. }
  1148. /*
  1149. ** Implementation of the POSIX opendir() function using the MSVCRT.
  1150. */
  1151. LPDIR opendir(
  1152. const char *dirname
  1153. ){
  1154. struct _finddata_t data;
  1155. LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
  1156. SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
  1157. if( dirp==NULL ) return NULL;
  1158. memset(dirp, 0, sizeof(DIR));
  1159. /* TODO: Remove this if Unix-style root paths are not used. */
  1160. if( sqlite3_stricmp(dirname, "/")==0 ){
  1161. dirname = windirent_getenv("SystemDrive");
  1162. }
  1163. memset(&data, 0, sizeof(struct _finddata_t));
  1164. _snprintf(data.name, namesize, "%s\\*", dirname);
  1165. dirp->d_handle = _findfirst(data.name, &data);
  1166. if( dirp->d_handle==BAD_INTPTR_T ){
  1167. closedir(dirp);
  1168. return NULL;
  1169. }
  1170. /* TODO: Remove this block to allow hidden and/or system files. */
  1171. if( is_filtered(data) ){
  1172. next:
  1173. memset(&data, 0, sizeof(struct _finddata_t));
  1174. if( _findnext(dirp->d_handle, &data)==-1 ){
  1175. closedir(dirp);
  1176. return NULL;
  1177. }
  1178. /* TODO: Remove this block to allow hidden and/or system files. */
  1179. if( is_filtered(data) ) goto next;
  1180. }
  1181. dirp->d_first.d_attributes = data.attrib;
  1182. strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
  1183. dirp->d_first.d_name[NAME_MAX] = '\0';
  1184. return dirp;
  1185. }
  1186. /*
  1187. ** Implementation of the POSIX readdir() function using the MSVCRT.
  1188. */
  1189. LPDIRENT readdir(
  1190. LPDIR dirp
  1191. ){
  1192. struct _finddata_t data;
  1193. if( dirp==NULL ) return NULL;
  1194. if( dirp->d_first.d_ino==0 ){
  1195. dirp->d_first.d_ino++;
  1196. dirp->d_next.d_ino++;
  1197. return &dirp->d_first;
  1198. }
  1199. next:
  1200. memset(&data, 0, sizeof(struct _finddata_t));
  1201. if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
  1202. /* TODO: Remove this block to allow hidden and/or system files. */
  1203. if( is_filtered(data) ) goto next;
  1204. dirp->d_next.d_ino++;
  1205. dirp->d_next.d_attributes = data.attrib;
  1206. strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
  1207. dirp->d_next.d_name[NAME_MAX] = '\0';
  1208. return &dirp->d_next;
  1209. }
  1210. /*
  1211. ** Implementation of the POSIX readdir_r() function using the MSVCRT.
  1212. */
  1213. INT readdir_r(
  1214. LPDIR dirp,
  1215. LPDIRENT entry,
  1216. LPDIRENT *result
  1217. ){
  1218. struct _finddata_t data;
  1219. if( dirp==NULL ) return EBADF;
  1220. if( dirp->d_first.d_ino==0 ){
  1221. dirp->d_first.d_ino++;
  1222. dirp->d_next.d_ino++;
  1223. entry->d_ino = dirp->d_first.d_ino;
  1224. entry->d_attributes = dirp->d_first.d_attributes;
  1225. strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
  1226. entry->d_name[NAME_MAX] = '\0';
  1227. *result = entry;
  1228. return 0;
  1229. }
  1230. next:
  1231. memset(&data, 0, sizeof(struct _finddata_t));
  1232. if( _findnext(dirp->d_handle, &data)==-1 ){
  1233. *result = NULL;
  1234. return ENOENT;
  1235. }
  1236. /* TODO: Remove this block to allow hidden and/or system files. */
  1237. if( is_filtered(data) ) goto next;
  1238. entry->d_ino = (ino_t)-1; /* not available */
  1239. entry->d_attributes = data.attrib;
  1240. strncpy(entry->d_name, data.name, NAME_MAX);
  1241. entry->d_name[NAME_MAX] = '\0';
  1242. *result = entry;
  1243. return 0;
  1244. }
  1245. /*
  1246. ** Implementation of the POSIX closedir() function using the MSVCRT.
  1247. */
  1248. INT closedir(
  1249. LPDIR dirp
  1250. ){
  1251. INT result = 0;
  1252. if( dirp==NULL ) return EINVAL;
  1253. if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
  1254. result = _findclose(dirp->d_handle);
  1255. }
  1256. sqlite3_free(dirp);
  1257. return result;
  1258. }
  1259. #endif /* defined(WIN32) && defined(_MSC_VER) */
  1260. /************************* End test_windirent.c ********************/
  1261. #define dirent DIRENT
  1262. #endif
  1263. /************************* Begin ../ext/misc/memtrace.c ******************/
  1264. /*
  1265. ** 2019-01-21
  1266. **
  1267. ** The author disclaims copyright to this source code. In place of
  1268. ** a legal notice, here is a blessing:
  1269. **
  1270. ** May you do good and not evil.
  1271. ** May you find forgiveness for yourself and forgive others.
  1272. ** May you share freely, never taking more than you give.
  1273. **
  1274. *************************************************************************
  1275. **
  1276. ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
  1277. ** mechanism to add a tracing layer on top of SQLite. If this extension
  1278. ** is registered prior to sqlite3_initialize(), it will cause all memory
  1279. ** allocation activities to be logged on standard output, or to some other
  1280. ** FILE specified by the initializer.
  1281. **
  1282. ** This file needs to be compiled into the application that uses it.
  1283. **
  1284. ** This extension is used to implement the --memtrace option of the
  1285. ** command-line shell.
  1286. */
  1287. #include <assert.h>
  1288. #include <string.h>
  1289. #include <stdio.h>
  1290. /* The original memory allocation routines */
  1291. static sqlite3_mem_methods memtraceBase;
  1292. static FILE *memtraceOut;
  1293. /* Methods that trace memory allocations */
  1294. static void *memtraceMalloc(int n){
  1295. if( memtraceOut ){
  1296. fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
  1297. memtraceBase.xRoundup(n));
  1298. }
  1299. return memtraceBase.xMalloc(n);
  1300. }
  1301. static void memtraceFree(void *p){
  1302. if( p==0 ) return;
  1303. if( memtraceOut ){
  1304. fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
  1305. }
  1306. memtraceBase.xFree(p);
  1307. }
  1308. static void *memtraceRealloc(void *p, int n){
  1309. if( p==0 ) return memtraceMalloc(n);
  1310. if( n==0 ){
  1311. memtraceFree(p);
  1312. return 0;
  1313. }
  1314. if( memtraceOut ){
  1315. fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
  1316. memtraceBase.xSize(p), memtraceBase.xRoundup(n));
  1317. }
  1318. return memtraceBase.xRealloc(p, n);
  1319. }
  1320. static int memtraceSize(void *p){
  1321. return memtraceBase.xSize(p);
  1322. }
  1323. static int memtraceRoundup(int n){
  1324. return memtraceBase.xRoundup(n);
  1325. }
  1326. static int memtraceInit(void *p){
  1327. return memtraceBase.xInit(p);
  1328. }
  1329. static void memtraceShutdown(void *p){
  1330. memtraceBase.xShutdown(p);
  1331. }
  1332. /* The substitute memory allocator */
  1333. static sqlite3_mem_methods ersaztMethods = {
  1334. memtraceMalloc,
  1335. memtraceFree,
  1336. memtraceRealloc,
  1337. memtraceSize,
  1338. memtraceRoundup,
  1339. memtraceInit,
  1340. memtraceShutdown,
  1341. 0
  1342. };
  1343. /* Begin tracing memory allocations to out. */
  1344. int sqlite3MemTraceActivate(FILE *out){
  1345. int rc = SQLITE_OK;
  1346. if( memtraceBase.xMalloc==0 ){
  1347. rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
  1348. if( rc==SQLITE_OK ){
  1349. rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
  1350. }
  1351. }
  1352. memtraceOut = out;
  1353. return rc;
  1354. }
  1355. /* Deactivate memory tracing */
  1356. int sqlite3MemTraceDeactivate(void){
  1357. int rc = SQLITE_OK;
  1358. if( memtraceBase.xMalloc!=0 ){
  1359. rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
  1360. if( rc==SQLITE_OK ){
  1361. memset(&memtraceBase, 0, sizeof(memtraceBase));
  1362. }
  1363. }
  1364. memtraceOut = 0;
  1365. return rc;
  1366. }
  1367. /************************* End ../ext/misc/memtrace.c ********************/
  1368. /************************* Begin ../ext/misc/shathree.c ******************/
  1369. /*
  1370. ** 2017-03-08
  1371. **
  1372. ** The author disclaims copyright to this source code. In place of
  1373. ** a legal notice, here is a blessing:
  1374. **
  1375. ** May you do good and not evil.
  1376. ** May you find forgiveness for yourself and forgive others.
  1377. ** May you share freely, never taking more than you give.
  1378. **
  1379. ******************************************************************************
  1380. **
  1381. ** This SQLite extension implements functions that compute SHA3 hashes.
  1382. ** Two SQL functions are implemented:
  1383. **
  1384. ** sha3(X,SIZE)
  1385. ** sha3_query(Y,SIZE)
  1386. **
  1387. ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
  1388. ** X is NULL.
  1389. **
  1390. ** The sha3_query(Y) function evaluates all queries in the SQL statements of Y
  1391. ** and returns a hash of their results.
  1392. **
  1393. ** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm
  1394. ** is used. If SIZE is included it must be one of the integers 224, 256,
  1395. ** 384, or 512, to determine SHA3 hash variant that is computed.
  1396. */
  1397. /* #include "sqlite3ext.h" */
  1398. SQLITE_EXTENSION_INIT1
  1399. #include <assert.h>
  1400. #include <string.h>
  1401. #include <stdarg.h>
  1402. #ifndef SQLITE_AMALGAMATION
  1403. /* typedef sqlite3_uint64 u64; */
  1404. #endif /* SQLITE_AMALGAMATION */
  1405. /******************************************************************************
  1406. ** The Hash Engine
  1407. */
  1408. /*
  1409. ** Macros to determine whether the machine is big or little endian,
  1410. ** and whether or not that determination is run-time or compile-time.
  1411. **
  1412. ** For best performance, an attempt is made to guess at the byte-order
  1413. ** using C-preprocessor macros. If that is unsuccessful, or if
  1414. ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
  1415. ** at run-time.
  1416. */
  1417. #ifndef SHA3_BYTEORDER
  1418. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  1419. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  1420. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  1421. defined(__arm__)
  1422. # define SHA3_BYTEORDER 1234
  1423. # elif defined(sparc) || defined(__ppc__)
  1424. # define SHA3_BYTEORDER 4321
  1425. # else
  1426. # define SHA3_BYTEORDER 0
  1427. # endif
  1428. #endif
  1429. /*
  1430. ** State structure for a SHA3 hash in progress
  1431. */
  1432. typedef struct SHA3Context SHA3Context;
  1433. struct SHA3Context {
  1434. union {
  1435. u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
  1436. unsigned char x[1600]; /* ... or 1600 bytes */
  1437. } u;
  1438. unsigned nRate; /* Bytes of input accepted per Keccak iteration */
  1439. unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
  1440. unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
  1441. };
  1442. /*
  1443. ** A single step of the Keccak mixing function for a 1600-bit state
  1444. */
  1445. static void KeccakF1600Step(SHA3Context *p){
  1446. int i;
  1447. u64 b0, b1, b2, b3, b4;
  1448. u64 c0, c1, c2, c3, c4;
  1449. u64 d0, d1, d2, d3, d4;
  1450. static const u64 RC[] = {
  1451. 0x0000000000000001ULL, 0x0000000000008082ULL,
  1452. 0x800000000000808aULL, 0x8000000080008000ULL,
  1453. 0x000000000000808bULL, 0x0000000080000001ULL,
  1454. 0x8000000080008081ULL, 0x8000000000008009ULL,
  1455. 0x000000000000008aULL, 0x0000000000000088ULL,
  1456. 0x0000000080008009ULL, 0x000000008000000aULL,
  1457. 0x000000008000808bULL, 0x800000000000008bULL,
  1458. 0x8000000000008089ULL, 0x8000000000008003ULL,
  1459. 0x8000000000008002ULL, 0x8000000000000080ULL,
  1460. 0x000000000000800aULL, 0x800000008000000aULL,
  1461. 0x8000000080008081ULL, 0x8000000000008080ULL,
  1462. 0x0000000080000001ULL, 0x8000000080008008ULL
  1463. };
  1464. # define a00 (p->u.s[0])
  1465. # define a01 (p->u.s[1])
  1466. # define a02 (p->u.s[2])
  1467. # define a03 (p->u.s[3])
  1468. # define a04 (p->u.s[4])
  1469. # define a10 (p->u.s[5])
  1470. # define a11 (p->u.s[6])
  1471. # define a12 (p->u.s[7])
  1472. # define a13 (p->u.s[8])
  1473. # define a14 (p->u.s[9])
  1474. # define a20 (p->u.s[10])
  1475. # define a21 (p->u.s[11])
  1476. # define a22 (p->u.s[12])
  1477. # define a23 (p->u.s[13])
  1478. # define a24 (p->u.s[14])
  1479. # define a30 (p->u.s[15])
  1480. # define a31 (p->u.s[16])
  1481. # define a32 (p->u.s[17])
  1482. # define a33 (p->u.s[18])
  1483. # define a34 (p->u.s[19])
  1484. # define a40 (p->u.s[20])
  1485. # define a41 (p->u.s[21])
  1486. # define a42 (p->u.s[22])
  1487. # define a43 (p->u.s[23])
  1488. # define a44 (p->u.s[24])
  1489. # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
  1490. for(i=0; i<24; i+=4){
  1491. c0 = a00^a10^a20^a30^a40;
  1492. c1 = a01^a11^a21^a31^a41;
  1493. c2 = a02^a12^a22^a32^a42;
  1494. c3 = a03^a13^a23^a33^a43;
  1495. c4 = a04^a14^a24^a34^a44;
  1496. d0 = c4^ROL64(c1, 1);
  1497. d1 = c0^ROL64(c2, 1);
  1498. d2 = c1^ROL64(c3, 1);
  1499. d3 = c2^ROL64(c4, 1);
  1500. d4 = c3^ROL64(c0, 1);
  1501. b0 = (a00^d0);
  1502. b1 = ROL64((a11^d1), 44);
  1503. b2 = ROL64((a22^d2), 43);
  1504. b3 = ROL64((a33^d3), 21);
  1505. b4 = ROL64((a44^d4), 14);
  1506. a00 = b0 ^((~b1)& b2 );
  1507. a00 ^= RC[i];
  1508. a11 = b1 ^((~b2)& b3 );
  1509. a22 = b2 ^((~b3)& b4 );
  1510. a33 = b3 ^((~b4)& b0 );
  1511. a44 = b4 ^((~b0)& b1 );
  1512. b2 = ROL64((a20^d0), 3);
  1513. b3 = ROL64((a31^d1), 45);
  1514. b4 = ROL64((a42^d2), 61);
  1515. b0 = ROL64((a03^d3), 28);
  1516. b1 = ROL64((a14^d4), 20);
  1517. a20 = b0 ^((~b1)& b2 );
  1518. a31 = b1 ^((~b2)& b3 );
  1519. a42 = b2 ^((~b3)& b4 );
  1520. a03 = b3 ^((~b4)& b0 );
  1521. a14 = b4 ^((~b0)& b1 );
  1522. b4 = ROL64((a40^d0), 18);
  1523. b0 = ROL64((a01^d1), 1);
  1524. b1 = ROL64((a12^d2), 6);
  1525. b2 = ROL64((a23^d3), 25);
  1526. b3 = ROL64((a34^d4), 8);
  1527. a40 = b0 ^((~b1)& b2 );
  1528. a01 = b1 ^((~b2)& b3 );
  1529. a12 = b2 ^((~b3)& b4 );
  1530. a23 = b3 ^((~b4)& b0 );
  1531. a34 = b4 ^((~b0)& b1 );
  1532. b1 = ROL64((a10^d0), 36);
  1533. b2 = ROL64((a21^d1), 10);
  1534. b3 = ROL64((a32^d2), 15);
  1535. b4 = ROL64((a43^d3), 56);
  1536. b0 = ROL64((a04^d4), 27);
  1537. a10 = b0 ^((~b1)& b2 );
  1538. a21 = b1 ^((~b2)& b3 );
  1539. a32 = b2 ^((~b3)& b4 );
  1540. a43 = b3 ^((~b4)& b0 );
  1541. a04 = b4 ^((~b0)& b1 );
  1542. b3 = ROL64((a30^d0), 41);
  1543. b4 = ROL64((a41^d1), 2);
  1544. b0 = ROL64((a02^d2), 62);
  1545. b1 = ROL64((a13^d3), 55);
  1546. b2 = ROL64((a24^d4), 39);
  1547. a30 = b0 ^((~b1)& b2 );
  1548. a41 = b1 ^((~b2)& b3 );
  1549. a02 = b2 ^((~b3)& b4 );
  1550. a13 = b3 ^((~b4)& b0 );
  1551. a24 = b4 ^((~b0)& b1 );
  1552. c0 = a00^a20^a40^a10^a30;
  1553. c1 = a11^a31^a01^a21^a41;
  1554. c2 = a22^a42^a12^a32^a02;
  1555. c3 = a33^a03^a23^a43^a13;
  1556. c4 = a44^a14^a34^a04^a24;
  1557. d0 = c4^ROL64(c1, 1);
  1558. d1 = c0^ROL64(c2, 1);
  1559. d2 = c1^ROL64(c3, 1);
  1560. d3 = c2^ROL64(c4, 1);
  1561. d4 = c3^ROL64(c0, 1);
  1562. b0 = (a00^d0);
  1563. b1 = ROL64((a31^d1), 44);
  1564. b2 = ROL64((a12^d2), 43);
  1565. b3 = ROL64((a43^d3), 21);
  1566. b4 = ROL64((a24^d4), 14);
  1567. a00 = b0 ^((~b1)& b2 );
  1568. a00 ^= RC[i+1];
  1569. a31 = b1 ^((~b2)& b3 );
  1570. a12 = b2 ^((~b3)& b4 );
  1571. a43 = b3 ^((~b4)& b0 );
  1572. a24 = b4 ^((~b0)& b1 );
  1573. b2 = ROL64((a40^d0), 3);
  1574. b3 = ROL64((a21^d1), 45);
  1575. b4 = ROL64((a02^d2), 61);
  1576. b0 = ROL64((a33^d3), 28);
  1577. b1 = ROL64((a14^d4), 20);
  1578. a40 = b0 ^((~b1)& b2 );
  1579. a21 = b1 ^((~b2)& b3 );
  1580. a02 = b2 ^((~b3)& b4 );
  1581. a33 = b3 ^((~b4)& b0 );
  1582. a14 = b4 ^((~b0)& b1 );
  1583. b4 = ROL64((a30^d0), 18);
  1584. b0 = ROL64((a11^d1), 1);
  1585. b1 = ROL64((a42^d2), 6);
  1586. b2 = ROL64((a23^d3), 25);
  1587. b3 = ROL64((a04^d4), 8);
  1588. a30 = b0 ^((~b1)& b2 );
  1589. a11 = b1 ^((~b2)& b3 );
  1590. a42 = b2 ^((~b3)& b4 );
  1591. a23 = b3 ^((~b4)& b0 );
  1592. a04 = b4 ^((~b0)& b1 );
  1593. b1 = ROL64((a20^d0), 36);
  1594. b2 = ROL64((a01^d1), 10);
  1595. b3 = ROL64((a32^d2), 15);
  1596. b4 = ROL64((a13^d3), 56);
  1597. b0 = ROL64((a44^d4), 27);
  1598. a20 = b0 ^((~b1)& b2 );
  1599. a01 = b1 ^((~b2)& b3 );
  1600. a32 = b2 ^((~b3)& b4 );
  1601. a13 = b3 ^((~b4)& b0 );
  1602. a44 = b4 ^((~b0)& b1 );
  1603. b3 = ROL64((a10^d0), 41);
  1604. b4 = ROL64((a41^d1), 2);
  1605. b0 = ROL64((a22^d2), 62);
  1606. b1 = ROL64((a03^d3), 55);
  1607. b2 = ROL64((a34^d4), 39);
  1608. a10 = b0 ^((~b1)& b2 );
  1609. a41 = b1 ^((~b2)& b3 );
  1610. a22 = b2 ^((~b3)& b4 );
  1611. a03 = b3 ^((~b4)& b0 );
  1612. a34 = b4 ^((~b0)& b1 );
  1613. c0 = a00^a40^a30^a20^a10;
  1614. c1 = a31^a21^a11^a01^a41;
  1615. c2 = a12^a02^a42^a32^a22;
  1616. c3 = a43^a33^a23^a13^a03;
  1617. c4 = a24^a14^a04^a44^a34;
  1618. d0 = c4^ROL64(c1, 1);
  1619. d1 = c0^ROL64(c2, 1);
  1620. d2 = c1^ROL64(c3, 1);
  1621. d3 = c2^ROL64(c4, 1);
  1622. d4 = c3^ROL64(c0, 1);
  1623. b0 = (a00^d0);
  1624. b1 = ROL64((a21^d1), 44);
  1625. b2 = ROL64((a42^d2), 43);
  1626. b3 = ROL64((a13^d3), 21);
  1627. b4 = ROL64((a34^d4), 14);
  1628. a00 = b0 ^((~b1)& b2 );
  1629. a00 ^= RC[i+2];
  1630. a21 = b1 ^((~b2)& b3 );
  1631. a42 = b2 ^((~b3)& b4 );
  1632. a13 = b3 ^((~b4)& b0 );
  1633. a34 = b4 ^((~b0)& b1 );
  1634. b2 = ROL64((a30^d0), 3);
  1635. b3 = ROL64((a01^d1), 45);
  1636. b4 = ROL64((a22^d2), 61);
  1637. b0 = ROL64((a43^d3), 28);
  1638. b1 = ROL64((a14^d4), 20);
  1639. a30 = b0 ^((~b1)& b2 );
  1640. a01 = b1 ^((~b2)& b3 );
  1641. a22 = b2 ^((~b3)& b4 );
  1642. a43 = b3 ^((~b4)& b0 );
  1643. a14 = b4 ^((~b0)& b1 );
  1644. b4 = ROL64((a10^d0), 18);
  1645. b0 = ROL64((a31^d1), 1);
  1646. b1 = ROL64((a02^d2), 6);
  1647. b2 = ROL64((a23^d3), 25);
  1648. b3 = ROL64((a44^d4), 8);
  1649. a10 = b0 ^((~b1)& b2 );
  1650. a31 = b1 ^((~b2)& b3 );
  1651. a02 = b2 ^((~b3)& b4 );
  1652. a23 = b3 ^((~b4)& b0 );
  1653. a44 = b4 ^((~b0)& b1 );
  1654. b1 = ROL64((a40^d0), 36);
  1655. b2 = ROL64((a11^d1), 10);
  1656. b3 = ROL64((a32^d2), 15);
  1657. b4 = ROL64((a03^d3), 56);
  1658. b0 = ROL64((a24^d4), 27);
  1659. a40 = b0 ^((~b1)& b2 );
  1660. a11 = b1 ^((~b2)& b3 );
  1661. a32 = b2 ^((~b3)& b4 );
  1662. a03 = b3 ^((~b4)& b0 );
  1663. a24 = b4 ^((~b0)& b1 );
  1664. b3 = ROL64((a20^d0), 41);
  1665. b4 = ROL64((a41^d1), 2);
  1666. b0 = ROL64((a12^d2), 62);
  1667. b1 = ROL64((a33^d3), 55);
  1668. b2 = ROL64((a04^d4), 39);
  1669. a20 = b0 ^((~b1)& b2 );
  1670. a41 = b1 ^((~b2)& b3 );
  1671. a12 = b2 ^((~b3)& b4 );
  1672. a33 = b3 ^((~b4)& b0 );
  1673. a04 = b4 ^((~b0)& b1 );
  1674. c0 = a00^a30^a10^a40^a20;
  1675. c1 = a21^a01^a31^a11^a41;
  1676. c2 = a42^a22^a02^a32^a12;
  1677. c3 = a13^a43^a23^a03^a33;
  1678. c4 = a34^a14^a44^a24^a04;
  1679. d0 = c4^ROL64(c1, 1);
  1680. d1 = c0^ROL64(c2, 1);
  1681. d2 = c1^ROL64(c3, 1);
  1682. d3 = c2^ROL64(c4, 1);
  1683. d4 = c3^ROL64(c0, 1);
  1684. b0 = (a00^d0);
  1685. b1 = ROL64((a01^d1), 44);
  1686. b2 = ROL64((a02^d2), 43);
  1687. b3 = ROL64((a03^d3), 21);
  1688. b4 = ROL64((a04^d4), 14);
  1689. a00 = b0 ^((~b1)& b2 );
  1690. a00 ^= RC[i+3];
  1691. a01 = b1 ^((~b2)& b3 );
  1692. a02 = b2 ^((~b3)& b4 );
  1693. a03 = b3 ^((~b4)& b0 );
  1694. a04 = b4 ^((~b0)& b1 );
  1695. b2 = ROL64((a10^d0), 3);
  1696. b3 = ROL64((a11^d1), 45);
  1697. b4 = ROL64((a12^d2), 61);
  1698. b0 = ROL64((a13^d3), 28);
  1699. b1 = ROL64((a14^d4), 20);
  1700. a10 = b0 ^((~b1)& b2 );
  1701. a11 = b1 ^((~b2)& b3 );
  1702. a12 = b2 ^((~b3)& b4 );
  1703. a13 = b3 ^((~b4)& b0 );
  1704. a14 = b4 ^((~b0)& b1 );
  1705. b4 = ROL64((a20^d0), 18);
  1706. b0 = ROL64((a21^d1), 1);
  1707. b1 = ROL64((a22^d2), 6);
  1708. b2 = ROL64((a23^d3), 25);
  1709. b3 = ROL64((a24^d4), 8);
  1710. a20 = b0 ^((~b1)& b2 );
  1711. a21 = b1 ^((~b2)& b3 );
  1712. a22 = b2 ^((~b3)& b4 );
  1713. a23 = b3 ^((~b4)& b0 );
  1714. a24 = b4 ^((~b0)& b1 );
  1715. b1 = ROL64((a30^d0), 36);
  1716. b2 = ROL64((a31^d1), 10);
  1717. b3 = ROL64((a32^d2), 15);
  1718. b4 = ROL64((a33^d3), 56);
  1719. b0 = ROL64((a34^d4), 27);
  1720. a30 = b0 ^((~b1)& b2 );
  1721. a31 = b1 ^((~b2)& b3 );
  1722. a32 = b2 ^((~b3)& b4 );
  1723. a33 = b3 ^((~b4)& b0 );
  1724. a34 = b4 ^((~b0)& b1 );
  1725. b3 = ROL64((a40^d0), 41);
  1726. b4 = ROL64((a41^d1), 2);
  1727. b0 = ROL64((a42^d2), 62);
  1728. b1 = ROL64((a43^d3), 55);
  1729. b2 = ROL64((a44^d4), 39);
  1730. a40 = b0 ^((~b1)& b2 );
  1731. a41 = b1 ^((~b2)& b3 );
  1732. a42 = b2 ^((~b3)& b4 );
  1733. a43 = b3 ^((~b4)& b0 );
  1734. a44 = b4 ^((~b0)& b1 );
  1735. }
  1736. }
  1737. /*
  1738. ** Initialize a new hash. iSize determines the size of the hash
  1739. ** in bits and should be one of 224, 256, 384, or 512. Or iSize
  1740. ** can be zero to use the default hash size of 256 bits.
  1741. */
  1742. static void SHA3Init(SHA3Context *p, int iSize){
  1743. memset(p, 0, sizeof(*p));
  1744. if( iSize>=128 && iSize<=512 ){
  1745. p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
  1746. }else{
  1747. p->nRate = (1600 - 2*256)/8;
  1748. }
  1749. #if SHA3_BYTEORDER==1234
  1750. /* Known to be little-endian at compile-time. No-op */
  1751. #elif SHA3_BYTEORDER==4321
  1752. p->ixMask = 7; /* Big-endian */
  1753. #else
  1754. {
  1755. static unsigned int one = 1;
  1756. if( 1==*(unsigned char*)&one ){
  1757. /* Little endian. No byte swapping. */
  1758. p->ixMask = 0;
  1759. }else{
  1760. /* Big endian. Byte swap. */
  1761. p->ixMask = 7;
  1762. }
  1763. }
  1764. #endif
  1765. }
  1766. /*
  1767. ** Make consecutive calls to the SHA3Update function to add new content
  1768. ** to the hash
  1769. */
  1770. static void SHA3Update(
  1771. SHA3Context *p,
  1772. const unsigned char *aData,
  1773. unsigned int nData
  1774. ){
  1775. unsigned int i = 0;
  1776. if( aData==0 ) return;
  1777. #if SHA3_BYTEORDER==1234
  1778. if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
  1779. for(; i+7<nData; i+=8){
  1780. p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
  1781. p->nLoaded += 8;
  1782. if( p->nLoaded>=p->nRate ){
  1783. KeccakF1600Step(p);
  1784. p->nLoaded = 0;
  1785. }
  1786. }
  1787. }
  1788. #endif
  1789. for(; i<nData; i++){
  1790. #if SHA3_BYTEORDER==1234
  1791. p->u.x[p->nLoaded] ^= aData[i];
  1792. #elif SHA3_BYTEORDER==4321
  1793. p->u.x[p->nLoaded^0x07] ^= aData[i];
  1794. #else
  1795. p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
  1796. #endif
  1797. p->nLoaded++;
  1798. if( p->nLoaded==p->nRate ){
  1799. KeccakF1600Step(p);
  1800. p->nLoaded = 0;
  1801. }
  1802. }
  1803. }
  1804. /*
  1805. ** After all content has been added, invoke SHA3Final() to compute
  1806. ** the final hash. The function returns a pointer to the binary
  1807. ** hash value.
  1808. */
  1809. static unsigned char *SHA3Final(SHA3Context *p){
  1810. unsigned int i;
  1811. if( p->nLoaded==p->nRate-1 ){
  1812. const unsigned char c1 = 0x86;
  1813. SHA3Update(p, &c1, 1);
  1814. }else{
  1815. const unsigned char c2 = 0x06;
  1816. const unsigned char c3 = 0x80;
  1817. SHA3Update(p, &c2, 1);
  1818. p->nLoaded = p->nRate - 1;
  1819. SHA3Update(p, &c3, 1);
  1820. }
  1821. for(i=0; i<p->nRate; i++){
  1822. p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
  1823. }
  1824. return &p->u.x[p->nRate];
  1825. }
  1826. /* End of the hashing logic
  1827. *****************************************************************************/
  1828. /*
  1829. ** Implementation of the sha3(X,SIZE) function.
  1830. **
  1831. ** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
  1832. ** size is 256. If X is a BLOB, it is hashed as is.
  1833. ** For all other non-NULL types of input, X is converted into a UTF-8 string
  1834. ** and the string is hashed without the trailing 0x00 terminator. The hash
  1835. ** of a NULL value is NULL.
  1836. */
  1837. static void sha3Func(
  1838. sqlite3_context *context,
  1839. int argc,
  1840. sqlite3_value **argv
  1841. ){
  1842. SHA3Context cx;
  1843. int eType = sqlite3_value_type(argv[0]);
  1844. int nByte = sqlite3_value_bytes(argv[0]);
  1845. int iSize;
  1846. if( argc==1 ){
  1847. iSize = 256;
  1848. }else{
  1849. iSize = sqlite3_value_int(argv[1]);
  1850. if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
  1851. sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
  1852. "384 512", -1);
  1853. return;
  1854. }
  1855. }
  1856. if( eType==SQLITE_NULL ) return;
  1857. SHA3Init(&cx, iSize);
  1858. if( eType==SQLITE_BLOB ){
  1859. SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
  1860. }else{
  1861. SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
  1862. }
  1863. sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
  1864. }
  1865. /* Compute a string using sqlite3_vsnprintf() with a maximum length
  1866. ** of 50 bytes and add it to the hash.
  1867. */
  1868. static void hash_step_vformat(
  1869. SHA3Context *p, /* Add content to this context */
  1870. const char *zFormat,
  1871. ...
  1872. ){
  1873. va_list ap;
  1874. int n;
  1875. char zBuf[50];
  1876. va_start(ap, zFormat);
  1877. sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
  1878. va_end(ap);
  1879. n = (int)strlen(zBuf);
  1880. SHA3Update(p, (unsigned char*)zBuf, n);
  1881. }
  1882. /*
  1883. ** Implementation of the sha3_query(SQL,SIZE) function.
  1884. **
  1885. ** This function compiles and runs the SQL statement(s) given in the
  1886. ** argument. The results are hashed using a SIZE-bit SHA3. The default
  1887. ** size is 256.
  1888. **
  1889. ** The format of the byte stream that is hashed is summarized as follows:
  1890. **
  1891. ** S<n>:<sql>
  1892. ** R
  1893. ** N
  1894. ** I<int>
  1895. ** F<ieee-float>
  1896. ** B<size>:<bytes>
  1897. ** T<size>:<text>
  1898. **
  1899. ** <sql> is the original SQL text for each statement run and <n> is
  1900. ** the size of that text. The SQL text is UTF-8. A single R character
  1901. ** occurs before the start of each row. N means a NULL value.
  1902. ** I mean an 8-byte little-endian integer <int>. F is a floating point
  1903. ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
  1904. ** B means blobs of <size> bytes. T means text rendered as <size>
  1905. ** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
  1906. ** text integers.
  1907. **
  1908. ** For each SQL statement in the X input, there is one S segment. Each
  1909. ** S segment is followed by zero or more R segments, one for each row in the
  1910. ** result set. After each R, there are one or more N, I, F, B, or T segments,
  1911. ** one for each column in the result set. Segments are concatentated directly
  1912. ** with no delimiters of any kind.
  1913. */
  1914. static void sha3QueryFunc(
  1915. sqlite3_context *context,
  1916. int argc,
  1917. sqlite3_value **argv
  1918. ){
  1919. sqlite3 *db = sqlite3_context_db_handle(context);
  1920. const char *zSql = (const char*)sqlite3_value_text(argv[0]);
  1921. sqlite3_stmt *pStmt = 0;
  1922. int nCol; /* Number of columns in the result set */
  1923. int i; /* Loop counter */
  1924. int rc;
  1925. int n;
  1926. const char *z;
  1927. SHA3Context cx;
  1928. int iSize;
  1929. if( argc==1 ){
  1930. iSize = 256;
  1931. }else{
  1932. iSize = sqlite3_value_int(argv[1]);
  1933. if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
  1934. sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
  1935. "384 512", -1);
  1936. return;
  1937. }
  1938. }
  1939. if( zSql==0 ) return;
  1940. SHA3Init(&cx, iSize);
  1941. while( zSql[0] ){
  1942. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
  1943. if( rc ){
  1944. char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
  1945. zSql, sqlite3_errmsg(db));
  1946. sqlite3_finalize(pStmt);
  1947. sqlite3_result_error(context, zMsg, -1);
  1948. sqlite3_free(zMsg);
  1949. return;
  1950. }
  1951. if( !sqlite3_stmt_readonly(pStmt) ){
  1952. char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
  1953. sqlite3_finalize(pStmt);
  1954. sqlite3_result_error(context, zMsg, -1);
  1955. sqlite3_free(zMsg);
  1956. return;
  1957. }
  1958. nCol = sqlite3_column_count(pStmt);
  1959. z = sqlite3_sql(pStmt);
  1960. if( z ){
  1961. n = (int)strlen(z);
  1962. hash_step_vformat(&cx,"S%d:",n);
  1963. SHA3Update(&cx,(unsigned char*)z,n);
  1964. }
  1965. /* Compute a hash over the result of the query */
  1966. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  1967. SHA3Update(&cx,(const unsigned char*)"R",1);
  1968. for(i=0; i<nCol; i++){
  1969. switch( sqlite3_column_type(pStmt,i) ){
  1970. case SQLITE_NULL: {
  1971. SHA3Update(&cx, (const unsigned char*)"N",1);
  1972. break;
  1973. }
  1974. case SQLITE_INTEGER: {
  1975. sqlite3_uint64 u;
  1976. int j;
  1977. unsigned char x[9];
  1978. sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
  1979. memcpy(&u, &v, 8);
  1980. for(j=8; j>=1; j--){
  1981. x[j] = u & 0xff;
  1982. u >>= 8;
  1983. }
  1984. x[0] = 'I';
  1985. SHA3Update(&cx, x, 9);
  1986. break;
  1987. }
  1988. case SQLITE_FLOAT: {
  1989. sqlite3_uint64 u;
  1990. int j;
  1991. unsigned char x[9];
  1992. double r = sqlite3_column_double(pStmt,i);
  1993. memcpy(&u, &r, 8);
  1994. for(j=8; j>=1; j--){
  1995. x[j] = u & 0xff;
  1996. u >>= 8;
  1997. }
  1998. x[0] = 'F';
  1999. SHA3Update(&cx,x,9);
  2000. break;
  2001. }
  2002. case SQLITE_TEXT: {
  2003. int n2 = sqlite3_column_bytes(pStmt, i);
  2004. const unsigned char *z2 = sqlite3_column_text(pStmt, i);
  2005. hash_step_vformat(&cx,"T%d:",n2);
  2006. SHA3Update(&cx, z2, n2);
  2007. break;
  2008. }
  2009. case SQLITE_BLOB: {
  2010. int n2 = sqlite3_column_bytes(pStmt, i);
  2011. const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
  2012. hash_step_vformat(&cx,"B%d:",n2);
  2013. SHA3Update(&cx, z2, n2);
  2014. break;
  2015. }
  2016. }
  2017. }
  2018. }
  2019. sqlite3_finalize(pStmt);
  2020. }
  2021. sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
  2022. }
  2023. #ifdef _WIN32
  2024. #endif
  2025. int sqlite3_shathree_init(
  2026. sqlite3 *db,
  2027. char **pzErrMsg,
  2028. const sqlite3_api_routines *pApi
  2029. ){
  2030. int rc = SQLITE_OK;
  2031. SQLITE_EXTENSION_INIT2(pApi);
  2032. (void)pzErrMsg; /* Unused parameter */
  2033. rc = sqlite3_create_function(db, "sha3", 1,
  2034. SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
  2035. 0, sha3Func, 0, 0);
  2036. if( rc==SQLITE_OK ){
  2037. rc = sqlite3_create_function(db, "sha3", 2,
  2038. SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
  2039. 0, sha3Func, 0, 0);
  2040. }
  2041. if( rc==SQLITE_OK ){
  2042. rc = sqlite3_create_function(db, "sha3_query", 1,
  2043. SQLITE_UTF8 | SQLITE_DIRECTONLY,
  2044. 0, sha3QueryFunc, 0, 0);
  2045. }
  2046. if( rc==SQLITE_OK ){
  2047. rc = sqlite3_create_function(db, "sha3_query", 2,
  2048. SQLITE_UTF8 | SQLITE_DIRECTONLY,
  2049. 0, sha3QueryFunc, 0, 0);
  2050. }
  2051. return rc;
  2052. }
  2053. /************************* End ../ext/misc/shathree.c ********************/
  2054. /************************* Begin ../ext/misc/uint.c ******************/
  2055. /*
  2056. ** 2020-04-14
  2057. **
  2058. ** The author disclaims copyright to this source code. In place of
  2059. ** a legal notice, here is a blessing:
  2060. **
  2061. ** May you do good and not evil.
  2062. ** May you find forgiveness for yourself and forgive others.
  2063. ** May you share freely, never taking more than you give.
  2064. **
  2065. ******************************************************************************
  2066. **
  2067. ** This SQLite extension implements the UINT collating sequence.
  2068. **
  2069. ** UINT works like BINARY for text, except that embedded strings
  2070. ** of digits compare in numeric order.
  2071. **
  2072. ** * Leading zeros are handled properly, in the sense that
  2073. ** they do not mess of the maginitude comparison of embedded
  2074. ** strings of digits. "x00123y" is equal to "x123y".
  2075. **
  2076. ** * Only unsigned integers are recognized. Plus and minus
  2077. ** signs are ignored. Decimal points and exponential notation
  2078. ** are ignored.
  2079. **
  2080. ** * Embedded integers can be of arbitrary length. Comparison
  2081. ** is *not* limited integers that can be expressed as a
  2082. ** 64-bit machine integer.
  2083. */
  2084. /* #include "sqlite3ext.h" */
  2085. SQLITE_EXTENSION_INIT1
  2086. #include <assert.h>
  2087. #include <string.h>
  2088. #include <ctype.h>
  2089. /*
  2090. ** Compare text in lexicographic order, except strings of digits
  2091. ** compare in numeric order.
  2092. */
  2093. static int uintCollFunc(
  2094. void *notUsed,
  2095. int nKey1, const void *pKey1,
  2096. int nKey2, const void *pKey2
  2097. ){
  2098. const unsigned char *zA = (const unsigned char*)pKey1;
  2099. const unsigned char *zB = (const unsigned char*)pKey2;
  2100. int i=0, j=0, x;
  2101. (void)notUsed;
  2102. while( i<nKey1 && j<nKey2 ){
  2103. x = zA[i] - zB[j];
  2104. if( isdigit(zA[i]) ){
  2105. int k;
  2106. if( !isdigit(zB[j]) ) return x;
  2107. while( i<nKey1 && zA[i]=='0' ){ i++; }
  2108. while( j<nKey2 && zB[j]=='0' ){ j++; }
  2109. k = 0;
  2110. while( i+k<nKey1 && isdigit(zA[i+k])
  2111. && j+k<nKey2 && isdigit(zB[j+k]) ){
  2112. k++;
  2113. }
  2114. if( i+k<nKey1 && isdigit(zA[i+k]) ){
  2115. return +1;
  2116. }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
  2117. return -1;
  2118. }else{
  2119. x = memcmp(zA+i, zB+j, k);
  2120. if( x ) return x;
  2121. i += k;
  2122. j += k;
  2123. }
  2124. }else if( x ){
  2125. return x;
  2126. }else{
  2127. i++;
  2128. j++;
  2129. }
  2130. }
  2131. return (nKey1 - i) - (nKey2 - j);
  2132. }
  2133. #ifdef _WIN32
  2134. #endif
  2135. int sqlite3_uint_init(
  2136. sqlite3 *db,
  2137. char **pzErrMsg,
  2138. const sqlite3_api_routines *pApi
  2139. ){
  2140. SQLITE_EXTENSION_INIT2(pApi);
  2141. (void)pzErrMsg; /* Unused parameter */
  2142. return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
  2143. }
  2144. /************************* End ../ext/misc/uint.c ********************/
  2145. /************************* Begin ../ext/misc/decimal.c ******************/
  2146. /*
  2147. ** 2020-06-22
  2148. **
  2149. ** The author disclaims copyright to this source code. In place of
  2150. ** a legal notice, here is a blessing:
  2151. **
  2152. ** May you do good and not evil.
  2153. ** May you find forgiveness for yourself and forgive others.
  2154. ** May you share freely, never taking more than you give.
  2155. **
  2156. ******************************************************************************
  2157. **
  2158. ** Routines to implement arbitrary-precision decimal math.
  2159. **
  2160. ** The focus here is on simplicity and correctness, not performance.
  2161. */
  2162. /* #include "sqlite3ext.h" */
  2163. SQLITE_EXTENSION_INIT1
  2164. #include <assert.h>
  2165. #include <string.h>
  2166. #include <ctype.h>
  2167. #include <stdlib.h>
  2168. /* Mark a function parameter as unused, to suppress nuisance compiler
  2169. ** warnings. */
  2170. #ifndef UNUSED_PARAMETER
  2171. # define UNUSED_PARAMETER(X) (void)(X)
  2172. #endif
  2173. /* A decimal object */
  2174. typedef struct Decimal Decimal;
  2175. struct Decimal {
  2176. char sign; /* 0 for positive, 1 for negative */
  2177. char oom; /* True if an OOM is encountered */
  2178. char isNull; /* True if holds a NULL rather than a number */
  2179. char isInit; /* True upon initialization */
  2180. int nDigit; /* Total number of digits */
  2181. int nFrac; /* Number of digits to the right of the decimal point */
  2182. signed char *a; /* Array of digits. Most significant first. */
  2183. };
  2184. /*
  2185. ** Release memory held by a Decimal, but do not free the object itself.
  2186. */
  2187. static void decimal_clear(Decimal *p){
  2188. sqlite3_free(p->a);
  2189. }
  2190. /*
  2191. ** Destroy a Decimal object
  2192. */
  2193. static void decimal_free(Decimal *p){
  2194. if( p ){
  2195. decimal_clear(p);
  2196. sqlite3_free(p);
  2197. }
  2198. }
  2199. /*
  2200. ** Allocate a new Decimal object. Initialize it to the number given
  2201. ** by the input string.
  2202. */
  2203. static Decimal *decimal_new(
  2204. sqlite3_context *pCtx,
  2205. sqlite3_value *pIn,
  2206. int nAlt,
  2207. const unsigned char *zAlt
  2208. ){
  2209. Decimal *p;
  2210. int n, i;
  2211. const unsigned char *zIn;
  2212. int iExp = 0;
  2213. p = sqlite3_malloc( sizeof(*p) );
  2214. if( p==0 ) goto new_no_mem;
  2215. p->sign = 0;
  2216. p->oom = 0;
  2217. p->isInit = 1;
  2218. p->isNull = 0;
  2219. p->nDigit = 0;
  2220. p->nFrac = 0;
  2221. if( zAlt ){
  2222. n = nAlt,
  2223. zIn = zAlt;
  2224. }else{
  2225. if( sqlite3_value_type(pIn)==SQLITE_NULL ){
  2226. p->a = 0;
  2227. p->isNull = 1;
  2228. return p;
  2229. }
  2230. n = sqlite3_value_bytes(pIn);
  2231. zIn = sqlite3_value_text(pIn);
  2232. }
  2233. p->a = sqlite3_malloc64( n+1 );
  2234. if( p->a==0 ) goto new_no_mem;
  2235. for(i=0; isspace(zIn[i]); i++){}
  2236. if( zIn[i]=='-' ){
  2237. p->sign = 1;
  2238. i++;
  2239. }else if( zIn[i]=='+' ){
  2240. i++;
  2241. }
  2242. while( i<n && zIn[i]=='0' ) i++;
  2243. while( i<n ){
  2244. char c = zIn[i];
  2245. if( c>='0' && c<='9' ){
  2246. p->a[p->nDigit++] = c - '0';
  2247. }else if( c=='.' ){
  2248. p->nFrac = p->nDigit + 1;
  2249. }else if( c=='e' || c=='E' ){
  2250. int j = i+1;
  2251. int neg = 0;
  2252. if( j>=n ) break;
  2253. if( zIn[j]=='-' ){
  2254. neg = 1;
  2255. j++;
  2256. }else if( zIn[j]=='+' ){
  2257. j++;
  2258. }
  2259. while( j<n && iExp<1000000 ){
  2260. if( zIn[j]>='0' && zIn[j]<='9' ){
  2261. iExp = iExp*10 + zIn[j] - '0';
  2262. }
  2263. j++;
  2264. }
  2265. if( neg ) iExp = -iExp;
  2266. break;
  2267. }
  2268. i++;
  2269. }
  2270. if( p->nFrac ){
  2271. p->nFrac = p->nDigit - (p->nFrac - 1);
  2272. }
  2273. if( iExp>0 ){
  2274. if( p->nFrac>0 ){
  2275. if( iExp<=p->nFrac ){
  2276. p->nFrac -= iExp;
  2277. iExp = 0;
  2278. }else{
  2279. iExp -= p->nFrac;
  2280. p->nFrac = 0;
  2281. }
  2282. }
  2283. if( iExp>0 ){
  2284. p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
  2285. if( p->a==0 ) goto new_no_mem;
  2286. memset(p->a+p->nDigit, 0, iExp);
  2287. p->nDigit += iExp;
  2288. }
  2289. }else if( iExp<0 ){
  2290. int nExtra;
  2291. iExp = -iExp;
  2292. nExtra = p->nDigit - p->nFrac - 1;
  2293. if( nExtra ){
  2294. if( nExtra>=iExp ){
  2295. p->nFrac += iExp;
  2296. iExp = 0;
  2297. }else{
  2298. iExp -= nExtra;
  2299. p->nFrac = p->nDigit - 1;
  2300. }
  2301. }
  2302. if( iExp>0 ){
  2303. p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
  2304. if( p->a==0 ) goto new_no_mem;
  2305. memmove(p->a+iExp, p->a, p->nDigit);
  2306. memset(p->a, 0, iExp);
  2307. p->nDigit += iExp;
  2308. p->nFrac += iExp;
  2309. }
  2310. }
  2311. return p;
  2312. new_no_mem:
  2313. if( pCtx ) sqlite3_result_error_nomem(pCtx);
  2314. sqlite3_free(p);
  2315. return 0;
  2316. }
  2317. /*
  2318. ** Make the given Decimal the result.
  2319. */
  2320. static void decimal_result(sqlite3_context *pCtx, Decimal *p){
  2321. char *z;
  2322. int i, j;
  2323. int n;
  2324. if( p==0 || p->oom ){
  2325. sqlite3_result_error_nomem(pCtx);
  2326. return;
  2327. }
  2328. if( p->isNull ){
  2329. sqlite3_result_null(pCtx);
  2330. return;
  2331. }
  2332. z = sqlite3_malloc( p->nDigit+4 );
  2333. if( z==0 ){
  2334. sqlite3_result_error_nomem(pCtx);
  2335. return;
  2336. }
  2337. i = 0;
  2338. if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
  2339. p->sign = 0;
  2340. }
  2341. if( p->sign ){
  2342. z[0] = '-';
  2343. i = 1;
  2344. }
  2345. n = p->nDigit - p->nFrac;
  2346. if( n<=0 ){
  2347. z[i++] = '0';
  2348. }
  2349. j = 0;
  2350. while( n>1 && p->a[j]==0 ){
  2351. j++;
  2352. n--;
  2353. }
  2354. while( n>0 ){
  2355. z[i++] = p->a[j] + '0';
  2356. j++;
  2357. n--;
  2358. }
  2359. if( p->nFrac ){
  2360. z[i++] = '.';
  2361. do{
  2362. z[i++] = p->a[j] + '0';
  2363. j++;
  2364. }while( j<p->nDigit );
  2365. }
  2366. z[i] = 0;
  2367. sqlite3_result_text(pCtx, z, i, sqlite3_free);
  2368. }
  2369. /*
  2370. ** SQL Function: decimal(X)
  2371. **
  2372. ** Convert input X into decimal and then back into text
  2373. */
  2374. static void decimalFunc(
  2375. sqlite3_context *context,
  2376. int argc,
  2377. sqlite3_value **argv
  2378. ){
  2379. Decimal *p = decimal_new(context, argv[0], 0, 0);
  2380. UNUSED_PARAMETER(argc);
  2381. decimal_result(context, p);
  2382. decimal_free(p);
  2383. }
  2384. /*
  2385. ** Compare to Decimal objects. Return negative, 0, or positive if the
  2386. ** first object is less than, equal to, or greater than the second.
  2387. **
  2388. ** Preconditions for this routine:
  2389. **
  2390. ** pA!=0
  2391. ** pA->isNull==0
  2392. ** pB!=0
  2393. ** pB->isNull==0
  2394. */
  2395. static int decimal_cmp(const Decimal *pA, const Decimal *pB){
  2396. int nASig, nBSig, rc, n;
  2397. if( pA->sign!=pB->sign ){
  2398. return pA->sign ? -1 : +1;
  2399. }
  2400. if( pA->sign ){
  2401. const Decimal *pTemp = pA;
  2402. pA = pB;
  2403. pB = pTemp;
  2404. }
  2405. nASig = pA->nDigit - pA->nFrac;
  2406. nBSig = pB->nDigit - pB->nFrac;
  2407. if( nASig!=nBSig ){
  2408. return nASig - nBSig;
  2409. }
  2410. n = pA->nDigit;
  2411. if( n>pB->nDigit ) n = pB->nDigit;
  2412. rc = memcmp(pA->a, pB->a, n);
  2413. if( rc==0 ){
  2414. rc = pA->nDigit - pB->nDigit;
  2415. }
  2416. return rc;
  2417. }
  2418. /*
  2419. ** SQL Function: decimal_cmp(X, Y)
  2420. **
  2421. ** Return negative, zero, or positive if X is less then, equal to, or
  2422. ** greater than Y.
  2423. */
  2424. static void decimalCmpFunc(
  2425. sqlite3_context *context,
  2426. int argc,
  2427. sqlite3_value **argv
  2428. ){
  2429. Decimal *pA = 0, *pB = 0;
  2430. int rc;
  2431. UNUSED_PARAMETER(argc);
  2432. pA = decimal_new(context, argv[0], 0, 0);
  2433. if( pA==0 || pA->isNull ) goto cmp_done;
  2434. pB = decimal_new(context, argv[1], 0, 0);
  2435. if( pB==0 || pB->isNull ) goto cmp_done;
  2436. rc = decimal_cmp(pA, pB);
  2437. if( rc<0 ) rc = -1;
  2438. else if( rc>0 ) rc = +1;
  2439. sqlite3_result_int(context, rc);
  2440. cmp_done:
  2441. decimal_free(pA);
  2442. decimal_free(pB);
  2443. }
  2444. /*
  2445. ** Expand the Decimal so that it has a least nDigit digits and nFrac
  2446. ** digits to the right of the decimal point.
  2447. */
  2448. static void decimal_expand(Decimal *p, int nDigit, int nFrac){
  2449. int nAddSig;
  2450. int nAddFrac;
  2451. if( p==0 ) return;
  2452. nAddFrac = nFrac - p->nFrac;
  2453. nAddSig = (nDigit - p->nDigit) - nAddFrac;
  2454. if( nAddFrac==0 && nAddSig==0 ) return;
  2455. p->a = sqlite3_realloc64(p->a, nDigit+1);
  2456. if( p->a==0 ){
  2457. p->oom = 1;
  2458. return;
  2459. }
  2460. if( nAddSig ){
  2461. memmove(p->a+nAddSig, p->a, p->nDigit);
  2462. memset(p->a, 0, nAddSig);
  2463. p->nDigit += nAddSig;
  2464. }
  2465. if( nAddFrac ){
  2466. memset(p->a+p->nDigit, 0, nAddFrac);
  2467. p->nDigit += nAddFrac;
  2468. p->nFrac += nAddFrac;
  2469. }
  2470. }
  2471. /*
  2472. ** Add the value pB into pA.
  2473. **
  2474. ** Both pA and pB might become denormalized by this routine.
  2475. */
  2476. static void decimal_add(Decimal *pA, Decimal *pB){
  2477. int nSig, nFrac, nDigit;
  2478. int i, rc;
  2479. if( pA==0 ){
  2480. return;
  2481. }
  2482. if( pA->oom || pB==0 || pB->oom ){
  2483. pA->oom = 1;
  2484. return;
  2485. }
  2486. if( pA->isNull || pB->isNull ){
  2487. pA->isNull = 1;
  2488. return;
  2489. }
  2490. nSig = pA->nDigit - pA->nFrac;
  2491. if( nSig && pA->a[0]==0 ) nSig--;
  2492. if( nSig<pB->nDigit-pB->nFrac ){
  2493. nSig = pB->nDigit - pB->nFrac;
  2494. }
  2495. nFrac = pA->nFrac;
  2496. if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
  2497. nDigit = nSig + nFrac + 1;
  2498. decimal_expand(pA, nDigit, nFrac);
  2499. decimal_expand(pB, nDigit, nFrac);
  2500. if( pA->oom || pB->oom ){
  2501. pA->oom = 1;
  2502. }else{
  2503. if( pA->sign==pB->sign ){
  2504. int carry = 0;
  2505. for(i=nDigit-1; i>=0; i--){
  2506. int x = pA->a[i] + pB->a[i] + carry;
  2507. if( x>=10 ){
  2508. carry = 1;
  2509. pA->a[i] = x - 10;
  2510. }else{
  2511. carry = 0;
  2512. pA->a[i] = x;
  2513. }
  2514. }
  2515. }else{
  2516. signed char *aA, *aB;
  2517. int borrow = 0;
  2518. rc = memcmp(pA->a, pB->a, nDigit);
  2519. if( rc<0 ){
  2520. aA = pB->a;
  2521. aB = pA->a;
  2522. pA->sign = !pA->sign;
  2523. }else{
  2524. aA = pA->a;
  2525. aB = pB->a;
  2526. }
  2527. for(i=nDigit-1; i>=0; i--){
  2528. int x = aA[i] - aB[i] - borrow;
  2529. if( x<0 ){
  2530. pA->a[i] = x+10;
  2531. borrow = 1;
  2532. }else{
  2533. pA->a[i] = x;
  2534. borrow = 0;
  2535. }
  2536. }
  2537. }
  2538. }
  2539. }
  2540. /*
  2541. ** Compare text in decimal order.
  2542. */
  2543. static int decimalCollFunc(
  2544. void *notUsed,
  2545. int nKey1, const void *pKey1,
  2546. int nKey2, const void *pKey2
  2547. ){
  2548. const unsigned char *zA = (const unsigned char*)pKey1;
  2549. const unsigned char *zB = (const unsigned char*)pKey2;
  2550. Decimal *pA = decimal_new(0, 0, nKey1, zA);
  2551. Decimal *pB = decimal_new(0, 0, nKey2, zB);
  2552. int rc;
  2553. UNUSED_PARAMETER(notUsed);
  2554. if( pA==0 || pB==0 ){
  2555. rc = 0;
  2556. }else{
  2557. rc = decimal_cmp(pA, pB);
  2558. }
  2559. decimal_free(pA);
  2560. decimal_free(pB);
  2561. return rc;
  2562. }
  2563. /*
  2564. ** SQL Function: decimal_add(X, Y)
  2565. ** decimal_sub(X, Y)
  2566. **
  2567. ** Return the sum or difference of X and Y.
  2568. */
  2569. static void decimalAddFunc(
  2570. sqlite3_context *context,
  2571. int argc,
  2572. sqlite3_value **argv
  2573. ){
  2574. Decimal *pA = decimal_new(context, argv[0], 0, 0);
  2575. Decimal *pB = decimal_new(context, argv[1], 0, 0);
  2576. UNUSED_PARAMETER(argc);
  2577. decimal_add(pA, pB);
  2578. decimal_result(context, pA);
  2579. decimal_free(pA);
  2580. decimal_free(pB);
  2581. }
  2582. static void decimalSubFunc(
  2583. sqlite3_context *context,
  2584. int argc,
  2585. sqlite3_value **argv
  2586. ){
  2587. Decimal *pA = decimal_new(context, argv[0], 0, 0);
  2588. Decimal *pB = decimal_new(context, argv[1], 0, 0);
  2589. UNUSED_PARAMETER(argc);
  2590. if( pB ){
  2591. pB->sign = !pB->sign;
  2592. decimal_add(pA, pB);
  2593. decimal_result(context, pA);
  2594. }
  2595. decimal_free(pA);
  2596. decimal_free(pB);
  2597. }
  2598. /* Aggregate funcion: decimal_sum(X)
  2599. **
  2600. ** Works like sum() except that it uses decimal arithmetic for unlimited
  2601. ** precision.
  2602. */
  2603. static void decimalSumStep(
  2604. sqlite3_context *context,
  2605. int argc,
  2606. sqlite3_value **argv
  2607. ){
  2608. Decimal *p;
  2609. Decimal *pArg;
  2610. UNUSED_PARAMETER(argc);
  2611. p = sqlite3_aggregate_context(context, sizeof(*p));
  2612. if( p==0 ) return;
  2613. if( !p->isInit ){
  2614. p->isInit = 1;
  2615. p->a = sqlite3_malloc(2);
  2616. if( p->a==0 ){
  2617. p->oom = 1;
  2618. }else{
  2619. p->a[0] = 0;
  2620. }
  2621. p->nDigit = 1;
  2622. p->nFrac = 0;
  2623. }
  2624. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  2625. pArg = decimal_new(context, argv[0], 0, 0);
  2626. decimal_add(p, pArg);
  2627. decimal_free(pArg);
  2628. }
  2629. static void decimalSumInverse(
  2630. sqlite3_context *context,
  2631. int argc,
  2632. sqlite3_value **argv
  2633. ){
  2634. Decimal *p;
  2635. Decimal *pArg;
  2636. UNUSED_PARAMETER(argc);
  2637. p = sqlite3_aggregate_context(context, sizeof(*p));
  2638. if( p==0 ) return;
  2639. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  2640. pArg = decimal_new(context, argv[0], 0, 0);
  2641. if( pArg ) pArg->sign = !pArg->sign;
  2642. decimal_add(p, pArg);
  2643. decimal_free(pArg);
  2644. }
  2645. static void decimalSumValue(sqlite3_context *context){
  2646. Decimal *p = sqlite3_aggregate_context(context, 0);
  2647. if( p==0 ) return;
  2648. decimal_result(context, p);
  2649. }
  2650. static void decimalSumFinalize(sqlite3_context *context){
  2651. Decimal *p = sqlite3_aggregate_context(context, 0);
  2652. if( p==0 ) return;
  2653. decimal_result(context, p);
  2654. decimal_clear(p);
  2655. }
  2656. /*
  2657. ** SQL Function: decimal_mul(X, Y)
  2658. **
  2659. ** Return the product of X and Y.
  2660. **
  2661. ** All significant digits after the decimal point are retained.
  2662. ** Trailing zeros after the decimal point are omitted as long as
  2663. ** the number of digits after the decimal point is no less than
  2664. ** either the number of digits in either input.
  2665. */
  2666. static void decimalMulFunc(
  2667. sqlite3_context *context,
  2668. int argc,
  2669. sqlite3_value **argv
  2670. ){
  2671. Decimal *pA = decimal_new(context, argv[0], 0, 0);
  2672. Decimal *pB = decimal_new(context, argv[1], 0, 0);
  2673. signed char *acc = 0;
  2674. int i, j, k;
  2675. int minFrac;
  2676. UNUSED_PARAMETER(argc);
  2677. if( pA==0 || pA->oom || pA->isNull
  2678. || pB==0 || pB->oom || pB->isNull
  2679. ){
  2680. goto mul_end;
  2681. }
  2682. acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
  2683. if( acc==0 ){
  2684. sqlite3_result_error_nomem(context);
  2685. goto mul_end;
  2686. }
  2687. memset(acc, 0, pA->nDigit + pB->nDigit + 2);
  2688. minFrac = pA->nFrac;
  2689. if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
  2690. for(i=pA->nDigit-1; i>=0; i--){
  2691. signed char f = pA->a[i];
  2692. int carry = 0, x;
  2693. for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
  2694. x = acc[k] + f*pB->a[j] + carry;
  2695. acc[k] = x%10;
  2696. carry = x/10;
  2697. }
  2698. x = acc[k] + carry;
  2699. acc[k] = x%10;
  2700. acc[k-1] += x/10;
  2701. }
  2702. sqlite3_free(pA->a);
  2703. pA->a = acc;
  2704. acc = 0;
  2705. pA->nDigit += pB->nDigit + 2;
  2706. pA->nFrac += pB->nFrac;
  2707. pA->sign ^= pB->sign;
  2708. while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
  2709. pA->nFrac--;
  2710. pA->nDigit--;
  2711. }
  2712. decimal_result(context, pA);
  2713. mul_end:
  2714. sqlite3_free(acc);
  2715. decimal_free(pA);
  2716. decimal_free(pB);
  2717. }
  2718. #ifdef _WIN32
  2719. #endif
  2720. int sqlite3_decimal_init(
  2721. sqlite3 *db,
  2722. char **pzErrMsg,
  2723. const sqlite3_api_routines *pApi
  2724. ){
  2725. int rc = SQLITE_OK;
  2726. static const struct {
  2727. const char *zFuncName;
  2728. int nArg;
  2729. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  2730. } aFunc[] = {
  2731. { "decimal", 1, decimalFunc },
  2732. { "decimal_cmp", 2, decimalCmpFunc },
  2733. { "decimal_add", 2, decimalAddFunc },
  2734. { "decimal_sub", 2, decimalSubFunc },
  2735. { "decimal_mul", 2, decimalMulFunc },
  2736. };
  2737. unsigned int i;
  2738. (void)pzErrMsg; /* Unused parameter */
  2739. SQLITE_EXTENSION_INIT2(pApi);
  2740. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  2741. rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
  2742. SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
  2743. 0, aFunc[i].xFunc, 0, 0);
  2744. }
  2745. if( rc==SQLITE_OK ){
  2746. rc = sqlite3_create_window_function(db, "decimal_sum", 1,
  2747. SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
  2748. decimalSumStep, decimalSumFinalize,
  2749. decimalSumValue, decimalSumInverse, 0);
  2750. }
  2751. if( rc==SQLITE_OK ){
  2752. rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
  2753. 0, decimalCollFunc);
  2754. }
  2755. return rc;
  2756. }
  2757. /************************* End ../ext/misc/decimal.c ********************/
  2758. /************************* Begin ../ext/misc/ieee754.c ******************/
  2759. /*
  2760. ** 2013-04-17
  2761. **
  2762. ** The author disclaims copyright to this source code. In place of
  2763. ** a legal notice, here is a blessing:
  2764. **
  2765. ** May you do good and not evil.
  2766. ** May you find forgiveness for yourself and forgive others.
  2767. ** May you share freely, never taking more than you give.
  2768. **
  2769. ******************************************************************************
  2770. **
  2771. ** This SQLite extension implements functions for the exact display
  2772. ** and input of IEEE754 Binary64 floating-point numbers.
  2773. **
  2774. ** ieee754(X)
  2775. ** ieee754(Y,Z)
  2776. **
  2777. ** In the first form, the value X should be a floating-point number.
  2778. ** The function will return a string of the form 'ieee754(Y,Z)' where
  2779. ** Y and Z are integers such that X==Y*pow(2,Z).
  2780. **
  2781. ** In the second form, Y and Z are integers which are the mantissa and
  2782. ** base-2 exponent of a new floating point number. The function returns
  2783. ** a floating-point value equal to Y*pow(2,Z).
  2784. **
  2785. ** Examples:
  2786. **
  2787. ** ieee754(2.0) -> 'ieee754(2,0)'
  2788. ** ieee754(45.25) -> 'ieee754(181,-2)'
  2789. ** ieee754(2, 0) -> 2.0
  2790. ** ieee754(181, -2) -> 45.25
  2791. **
  2792. ** Two additional functions break apart the one-argument ieee754()
  2793. ** result into separate integer values:
  2794. **
  2795. ** ieee754_mantissa(45.25) -> 181
  2796. ** ieee754_exponent(45.25) -> -2
  2797. **
  2798. ** These functions convert binary64 numbers into blobs and back again.
  2799. **
  2800. ** ieee754_from_blob(x'3ff0000000000000') -> 1.0
  2801. ** ieee754_to_blob(1.0) -> x'3ff0000000000000'
  2802. **
  2803. ** In all single-argument functions, if the argument is an 8-byte blob
  2804. ** then that blob is interpreted as a big-endian binary64 value.
  2805. **
  2806. **
  2807. ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
  2808. ** -----------------------------------------------
  2809. **
  2810. ** This extension in combination with the separate 'decimal' extension
  2811. ** can be used to compute the exact decimal representation of binary64
  2812. ** values. To begin, first compute a table of exponent values:
  2813. **
  2814. ** CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
  2815. ** WITH RECURSIVE c(x,v) AS (
  2816. ** VALUES(0,'1')
  2817. ** UNION ALL
  2818. ** SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
  2819. ** ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
  2820. ** WITH RECURSIVE c(x,v) AS (
  2821. ** VALUES(-1,'0.5')
  2822. ** UNION ALL
  2823. ** SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
  2824. ** ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
  2825. **
  2826. ** Then, to compute the exact decimal representation of a floating
  2827. ** point value (the value 47.49 is used in the example) do:
  2828. **
  2829. ** WITH c(n) AS (VALUES(47.49))
  2830. ** ---------------^^^^^---- Replace with whatever you want
  2831. ** SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
  2832. ** FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
  2833. **
  2834. ** Here is a query to show various boundry values for the binary64
  2835. ** number format:
  2836. **
  2837. ** WITH c(name,bin) AS (VALUES
  2838. ** ('minimum positive value', x'0000000000000001'),
  2839. ** ('maximum subnormal value', x'000fffffffffffff'),
  2840. ** ('mininum positive nornal value', x'0010000000000000'),
  2841. ** ('maximum value', x'7fefffffffffffff'))
  2842. ** SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
  2843. ** FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
  2844. **
  2845. */
  2846. /* #include "sqlite3ext.h" */
  2847. SQLITE_EXTENSION_INIT1
  2848. #include <assert.h>
  2849. #include <string.h>
  2850. /* Mark a function parameter as unused, to suppress nuisance compiler
  2851. ** warnings. */
  2852. #ifndef UNUSED_PARAMETER
  2853. # define UNUSED_PARAMETER(X) (void)(X)
  2854. #endif
  2855. /*
  2856. ** Implementation of the ieee754() function
  2857. */
  2858. static void ieee754func(
  2859. sqlite3_context *context,
  2860. int argc,
  2861. sqlite3_value **argv
  2862. ){
  2863. if( argc==1 ){
  2864. sqlite3_int64 m, a;
  2865. double r;
  2866. int e;
  2867. int isNeg;
  2868. char zResult[100];
  2869. assert( sizeof(m)==sizeof(r) );
  2870. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  2871. && sqlite3_value_bytes(argv[0])==sizeof(r)
  2872. ){
  2873. const unsigned char *x = sqlite3_value_blob(argv[0]);
  2874. unsigned int i;
  2875. sqlite3_uint64 v = 0;
  2876. for(i=0; i<sizeof(r); i++){
  2877. v = (v<<8) | x[i];
  2878. }
  2879. memcpy(&r, &v, sizeof(r));
  2880. }else{
  2881. r = sqlite3_value_double(argv[0]);
  2882. }
  2883. if( r<0.0 ){
  2884. isNeg = 1;
  2885. r = -r;
  2886. }else{
  2887. isNeg = 0;
  2888. }
  2889. memcpy(&a,&r,sizeof(a));
  2890. if( a==0 ){
  2891. e = 0;
  2892. m = 0;
  2893. }else{
  2894. e = a>>52;
  2895. m = a & ((((sqlite3_int64)1)<<52)-1);
  2896. if( e==0 ){
  2897. m <<= 1;
  2898. }else{
  2899. m |= ((sqlite3_int64)1)<<52;
  2900. }
  2901. while( e<1075 && m>0 && (m&1)==0 ){
  2902. m >>= 1;
  2903. e++;
  2904. }
  2905. if( isNeg ) m = -m;
  2906. }
  2907. switch( *(int*)sqlite3_user_data(context) ){
  2908. case 0:
  2909. sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
  2910. m, e-1075);
  2911. sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
  2912. break;
  2913. case 1:
  2914. sqlite3_result_int64(context, m);
  2915. break;
  2916. case 2:
  2917. sqlite3_result_int(context, e-1075);
  2918. break;
  2919. }
  2920. }else{
  2921. sqlite3_int64 m, e, a;
  2922. double r;
  2923. int isNeg = 0;
  2924. m = sqlite3_value_int64(argv[0]);
  2925. e = sqlite3_value_int64(argv[1]);
  2926. /* Limit the range of e. Ticket 22dea1cfdb9151e4 2021-03-02 */
  2927. if( e>10000 ){
  2928. e = 10000;
  2929. }else if( e<-10000 ){
  2930. e = -10000;
  2931. }
  2932. if( m<0 ){
  2933. isNeg = 1;
  2934. m = -m;
  2935. if( m<0 ) return;
  2936. }else if( m==0 && e>-1000 && e<1000 ){
  2937. sqlite3_result_double(context, 0.0);
  2938. return;
  2939. }
  2940. while( (m>>32)&0xffe00000 ){
  2941. m >>= 1;
  2942. e++;
  2943. }
  2944. while( m!=0 && ((m>>32)&0xfff00000)==0 ){
  2945. m <<= 1;
  2946. e--;
  2947. }
  2948. e += 1075;
  2949. if( e<=0 ){
  2950. /* Subnormal */
  2951. if( 1-e >= 64 ){
  2952. m = 0;
  2953. }else{
  2954. m >>= 1-e;
  2955. }
  2956. e = 0;
  2957. }else if( e>0x7ff ){
  2958. e = 0x7ff;
  2959. }
  2960. a = m & ((((sqlite3_int64)1)<<52)-1);
  2961. a |= e<<52;
  2962. if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
  2963. memcpy(&r, &a, sizeof(r));
  2964. sqlite3_result_double(context, r);
  2965. }
  2966. }
  2967. /*
  2968. ** Functions to convert between blobs and floats.
  2969. */
  2970. static void ieee754func_from_blob(
  2971. sqlite3_context *context,
  2972. int argc,
  2973. sqlite3_value **argv
  2974. ){
  2975. UNUSED_PARAMETER(argc);
  2976. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  2977. && sqlite3_value_bytes(argv[0])==sizeof(double)
  2978. ){
  2979. double r;
  2980. const unsigned char *x = sqlite3_value_blob(argv[0]);
  2981. unsigned int i;
  2982. sqlite3_uint64 v = 0;
  2983. for(i=0; i<sizeof(r); i++){
  2984. v = (v<<8) | x[i];
  2985. }
  2986. memcpy(&r, &v, sizeof(r));
  2987. sqlite3_result_double(context, r);
  2988. }
  2989. }
  2990. static void ieee754func_to_blob(
  2991. sqlite3_context *context,
  2992. int argc,
  2993. sqlite3_value **argv
  2994. ){
  2995. UNUSED_PARAMETER(argc);
  2996. if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
  2997. || sqlite3_value_type(argv[0])==SQLITE_INTEGER
  2998. ){
  2999. double r = sqlite3_value_double(argv[0]);
  3000. sqlite3_uint64 v;
  3001. unsigned char a[sizeof(r)];
  3002. unsigned int i;
  3003. memcpy(&v, &r, sizeof(r));
  3004. for(i=1; i<=sizeof(r); i++){
  3005. a[sizeof(r)-i] = v&0xff;
  3006. v >>= 8;
  3007. }
  3008. sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
  3009. }
  3010. }
  3011. #ifdef _WIN32
  3012. #endif
  3013. int sqlite3_ieee_init(
  3014. sqlite3 *db,
  3015. char **pzErrMsg,
  3016. const sqlite3_api_routines *pApi
  3017. ){
  3018. static const struct {
  3019. char *zFName;
  3020. int nArg;
  3021. int iAux;
  3022. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  3023. } aFunc[] = {
  3024. { "ieee754", 1, 0, ieee754func },
  3025. { "ieee754", 2, 0, ieee754func },
  3026. { "ieee754_mantissa", 1, 1, ieee754func },
  3027. { "ieee754_exponent", 1, 2, ieee754func },
  3028. { "ieee754_to_blob", 1, 0, ieee754func_to_blob },
  3029. { "ieee754_from_blob", 1, 0, ieee754func_from_blob },
  3030. };
  3031. unsigned int i;
  3032. int rc = SQLITE_OK;
  3033. SQLITE_EXTENSION_INIT2(pApi);
  3034. (void)pzErrMsg; /* Unused parameter */
  3035. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  3036. rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
  3037. SQLITE_UTF8|SQLITE_INNOCUOUS,
  3038. (void*)&aFunc[i].iAux,
  3039. aFunc[i].xFunc, 0, 0);
  3040. }
  3041. return rc;
  3042. }
  3043. /************************* End ../ext/misc/ieee754.c ********************/
  3044. /************************* Begin ../ext/misc/series.c ******************/
  3045. /*
  3046. ** 2015-08-18
  3047. **
  3048. ** The author disclaims copyright to this source code. In place of
  3049. ** a legal notice, here is a blessing:
  3050. **
  3051. ** May you do good and not evil.
  3052. ** May you find forgiveness for yourself and forgive others.
  3053. ** May you share freely, never taking more than you give.
  3054. **
  3055. *************************************************************************
  3056. **
  3057. ** This file demonstrates how to create a table-valued-function using
  3058. ** a virtual table. This demo implements the generate_series() function
  3059. ** which gives similar results to the eponymous function in PostgreSQL.
  3060. ** Examples:
  3061. **
  3062. ** SELECT * FROM generate_series(0,100,5);
  3063. **
  3064. ** The query above returns integers from 0 through 100 counting by steps
  3065. ** of 5.
  3066. **
  3067. ** SELECT * FROM generate_series(0,100);
  3068. **
  3069. ** Integers from 0 through 100 with a step size of 1.
  3070. **
  3071. ** SELECT * FROM generate_series(20) LIMIT 10;
  3072. **
  3073. ** Integers 20 through 29.
  3074. **
  3075. ** HOW IT WORKS
  3076. **
  3077. ** The generate_series "function" is really a virtual table with the
  3078. ** following schema:
  3079. **
  3080. ** CREATE TABLE generate_series(
  3081. ** value,
  3082. ** start HIDDEN,
  3083. ** stop HIDDEN,
  3084. ** step HIDDEN
  3085. ** );
  3086. **
  3087. ** Function arguments in queries against this virtual table are translated
  3088. ** into equality constraints against successive hidden columns. In other
  3089. ** words, the following pairs of queries are equivalent to each other:
  3090. **
  3091. ** SELECT * FROM generate_series(0,100,5);
  3092. ** SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
  3093. **
  3094. ** SELECT * FROM generate_series(0,100);
  3095. ** SELECT * FROM generate_series WHERE start=0 AND stop=100;
  3096. **
  3097. ** SELECT * FROM generate_series(20) LIMIT 10;
  3098. ** SELECT * FROM generate_series WHERE start=20 LIMIT 10;
  3099. **
  3100. ** The generate_series virtual table implementation leaves the xCreate method
  3101. ** set to NULL. This means that it is not possible to do a CREATE VIRTUAL
  3102. ** TABLE command with "generate_series" as the USING argument. Instead, there
  3103. ** is a single generate_series virtual table that is always available without
  3104. ** having to be created first.
  3105. **
  3106. ** The xBestIndex method looks for equality constraints against the hidden
  3107. ** start, stop, and step columns, and if present, it uses those constraints
  3108. ** to bound the sequence of generated values. If the equality constraints
  3109. ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
  3110. ** xBestIndex returns a small cost when both start and stop are available,
  3111. ** and a very large cost if either start or stop are unavailable. This
  3112. ** encourages the query planner to order joins such that the bounds of the
  3113. ** series are well-defined.
  3114. */
  3115. /* #include "sqlite3ext.h" */
  3116. SQLITE_EXTENSION_INIT1
  3117. #include <assert.h>
  3118. #include <string.h>
  3119. #ifndef SQLITE_OMIT_VIRTUALTABLE
  3120. /* series_cursor is a subclass of sqlite3_vtab_cursor which will
  3121. ** serve as the underlying representation of a cursor that scans
  3122. ** over rows of the result
  3123. */
  3124. typedef struct series_cursor series_cursor;
  3125. struct series_cursor {
  3126. sqlite3_vtab_cursor base; /* Base class - must be first */
  3127. int isDesc; /* True to count down rather than up */
  3128. sqlite3_int64 iRowid; /* The rowid */
  3129. sqlite3_int64 iValue; /* Current value ("value") */
  3130. sqlite3_int64 mnValue; /* Mimimum value ("start") */
  3131. sqlite3_int64 mxValue; /* Maximum value ("stop") */
  3132. sqlite3_int64 iStep; /* Increment ("step") */
  3133. };
  3134. /*
  3135. ** The seriesConnect() method is invoked to create a new
  3136. ** series_vtab that describes the generate_series virtual table.
  3137. **
  3138. ** Think of this routine as the constructor for series_vtab objects.
  3139. **
  3140. ** All this routine needs to do is:
  3141. **
  3142. ** (1) Allocate the series_vtab object and initialize all fields.
  3143. **
  3144. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  3145. ** result set of queries against generate_series will look like.
  3146. */
  3147. static int seriesConnect(
  3148. sqlite3 *db,
  3149. void *pUnused,
  3150. int argcUnused, const char *const*argvUnused,
  3151. sqlite3_vtab **ppVtab,
  3152. char **pzErrUnused
  3153. ){
  3154. sqlite3_vtab *pNew;
  3155. int rc;
  3156. /* Column numbers */
  3157. #define SERIES_COLUMN_VALUE 0
  3158. #define SERIES_COLUMN_START 1
  3159. #define SERIES_COLUMN_STOP 2
  3160. #define SERIES_COLUMN_STEP 3
  3161. (void)pUnused;
  3162. (void)argcUnused;
  3163. (void)argvUnused;
  3164. (void)pzErrUnused;
  3165. rc = sqlite3_declare_vtab(db,
  3166. "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
  3167. if( rc==SQLITE_OK ){
  3168. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  3169. if( pNew==0 ) return SQLITE_NOMEM;
  3170. memset(pNew, 0, sizeof(*pNew));
  3171. sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
  3172. }
  3173. return rc;
  3174. }
  3175. /*
  3176. ** This method is the destructor for series_cursor objects.
  3177. */
  3178. static int seriesDisconnect(sqlite3_vtab *pVtab){
  3179. sqlite3_free(pVtab);
  3180. return SQLITE_OK;
  3181. }
  3182. /*
  3183. ** Constructor for a new series_cursor object.
  3184. */
  3185. static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
  3186. series_cursor *pCur;
  3187. (void)pUnused;
  3188. pCur = sqlite3_malloc( sizeof(*pCur) );
  3189. if( pCur==0 ) return SQLITE_NOMEM;
  3190. memset(pCur, 0, sizeof(*pCur));
  3191. *ppCursor = &pCur->base;
  3192. return SQLITE_OK;
  3193. }
  3194. /*
  3195. ** Destructor for a series_cursor.
  3196. */
  3197. static int seriesClose(sqlite3_vtab_cursor *cur){
  3198. sqlite3_free(cur);
  3199. return SQLITE_OK;
  3200. }
  3201. /*
  3202. ** Advance a series_cursor to its next row of output.
  3203. */
  3204. static int seriesNext(sqlite3_vtab_cursor *cur){
  3205. series_cursor *pCur = (series_cursor*)cur;
  3206. if( pCur->isDesc ){
  3207. pCur->iValue -= pCur->iStep;
  3208. }else{
  3209. pCur->iValue += pCur->iStep;
  3210. }
  3211. pCur->iRowid++;
  3212. return SQLITE_OK;
  3213. }
  3214. /*
  3215. ** Return values of columns for the row at which the series_cursor
  3216. ** is currently pointing.
  3217. */
  3218. static int seriesColumn(
  3219. sqlite3_vtab_cursor *cur, /* The cursor */
  3220. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  3221. int i /* Which column to return */
  3222. ){
  3223. series_cursor *pCur = (series_cursor*)cur;
  3224. sqlite3_int64 x = 0;
  3225. switch( i ){
  3226. case SERIES_COLUMN_START: x = pCur->mnValue; break;
  3227. case SERIES_COLUMN_STOP: x = pCur->mxValue; break;
  3228. case SERIES_COLUMN_STEP: x = pCur->iStep; break;
  3229. default: x = pCur->iValue; break;
  3230. }
  3231. sqlite3_result_int64(ctx, x);
  3232. return SQLITE_OK;
  3233. }
  3234. /*
  3235. ** Return the rowid for the current row. In this implementation, the
  3236. ** first row returned is assigned rowid value 1, and each subsequent
  3237. ** row a value 1 more than that of the previous.
  3238. */
  3239. static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  3240. series_cursor *pCur = (series_cursor*)cur;
  3241. *pRowid = pCur->iRowid;
  3242. return SQLITE_OK;
  3243. }
  3244. /*
  3245. ** Return TRUE if the cursor has been moved off of the last
  3246. ** row of output.
  3247. */
  3248. static int seriesEof(sqlite3_vtab_cursor *cur){
  3249. series_cursor *pCur = (series_cursor*)cur;
  3250. if( pCur->isDesc ){
  3251. return pCur->iValue < pCur->mnValue;
  3252. }else{
  3253. return pCur->iValue > pCur->mxValue;
  3254. }
  3255. }
  3256. /* True to cause run-time checking of the start=, stop=, and/or step=
  3257. ** parameters. The only reason to do this is for testing the
  3258. ** constraint checking logic for virtual tables in the SQLite core.
  3259. */
  3260. #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
  3261. # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
  3262. #endif
  3263. /*
  3264. ** This method is called to "rewind" the series_cursor object back
  3265. ** to the first row of output. This method is always called at least
  3266. ** once prior to any call to seriesColumn() or seriesRowid() or
  3267. ** seriesEof().
  3268. **
  3269. ** The query plan selected by seriesBestIndex is passed in the idxNum
  3270. ** parameter. (idxStr is not used in this implementation.) idxNum
  3271. ** is a bitmask showing which constraints are available:
  3272. **
  3273. ** 1: start=VALUE
  3274. ** 2: stop=VALUE
  3275. ** 4: step=VALUE
  3276. **
  3277. ** Also, if bit 8 is set, that means that the series should be output
  3278. ** in descending order rather than in ascending order. If bit 16 is
  3279. ** set, then output must appear in ascending order.
  3280. **
  3281. ** This routine should initialize the cursor and position it so that it
  3282. ** is pointing at the first row, or pointing off the end of the table
  3283. ** (so that seriesEof() will return true) if the table is empty.
  3284. */
  3285. static int seriesFilter(
  3286. sqlite3_vtab_cursor *pVtabCursor,
  3287. int idxNum, const char *idxStrUnused,
  3288. int argc, sqlite3_value **argv
  3289. ){
  3290. series_cursor *pCur = (series_cursor *)pVtabCursor;
  3291. int i = 0;
  3292. (void)idxStrUnused;
  3293. if( idxNum & 1 ){
  3294. pCur->mnValue = sqlite3_value_int64(argv[i++]);
  3295. }else{
  3296. pCur->mnValue = 0;
  3297. }
  3298. if( idxNum & 2 ){
  3299. pCur->mxValue = sqlite3_value_int64(argv[i++]);
  3300. }else{
  3301. pCur->mxValue = 0xffffffff;
  3302. }
  3303. if( idxNum & 4 ){
  3304. pCur->iStep = sqlite3_value_int64(argv[i++]);
  3305. if( pCur->iStep==0 ){
  3306. pCur->iStep = 1;
  3307. }else if( pCur->iStep<0 ){
  3308. pCur->iStep = -pCur->iStep;
  3309. if( (idxNum & 16)==0 ) idxNum |= 8;
  3310. }
  3311. }else{
  3312. pCur->iStep = 1;
  3313. }
  3314. for(i=0; i<argc; i++){
  3315. if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
  3316. /* If any of the constraints have a NULL value, then return no rows.
  3317. ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
  3318. pCur->mnValue = 1;
  3319. pCur->mxValue = 0;
  3320. break;
  3321. }
  3322. }
  3323. if( idxNum & 8 ){
  3324. pCur->isDesc = 1;
  3325. pCur->iValue = pCur->mxValue;
  3326. if( pCur->iStep>0 ){
  3327. pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
  3328. }
  3329. }else{
  3330. pCur->isDesc = 0;
  3331. pCur->iValue = pCur->mnValue;
  3332. }
  3333. pCur->iRowid = 1;
  3334. return SQLITE_OK;
  3335. }
  3336. /*
  3337. ** SQLite will invoke this method one or more times while planning a query
  3338. ** that uses the generate_series virtual table. This routine needs to create
  3339. ** a query plan for each invocation and compute an estimated cost for that
  3340. ** plan.
  3341. **
  3342. ** In this implementation idxNum is used to represent the
  3343. ** query plan. idxStr is unused.
  3344. **
  3345. ** The query plan is represented by bits in idxNum:
  3346. **
  3347. ** (1) start = $value -- constraint exists
  3348. ** (2) stop = $value -- constraint exists
  3349. ** (4) step = $value -- constraint exists
  3350. ** (8) output in descending order
  3351. */
  3352. static int seriesBestIndex(
  3353. sqlite3_vtab *pVTab,
  3354. sqlite3_index_info *pIdxInfo
  3355. ){
  3356. int i, j; /* Loop over constraints */
  3357. int idxNum = 0; /* The query plan bitmask */
  3358. int bStartSeen = 0; /* EQ constraint seen on the START column */
  3359. int unusableMask = 0; /* Mask of unusable constraints */
  3360. int nArg = 0; /* Number of arguments that seriesFilter() expects */
  3361. int aIdx[3]; /* Constraints on start, stop, and step */
  3362. const struct sqlite3_index_constraint *pConstraint;
  3363. /* This implementation assumes that the start, stop, and step columns
  3364. ** are the last three columns in the virtual table. */
  3365. assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
  3366. assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
  3367. aIdx[0] = aIdx[1] = aIdx[2] = -1;
  3368. pConstraint = pIdxInfo->aConstraint;
  3369. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  3370. int iCol; /* 0 for start, 1 for stop, 2 for step */
  3371. int iMask; /* bitmask for those column */
  3372. if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
  3373. iCol = pConstraint->iColumn - SERIES_COLUMN_START;
  3374. assert( iCol>=0 && iCol<=2 );
  3375. iMask = 1 << iCol;
  3376. if( iCol==0 ) bStartSeen = 1;
  3377. if( pConstraint->usable==0 ){
  3378. unusableMask |= iMask;
  3379. continue;
  3380. }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  3381. idxNum |= iMask;
  3382. aIdx[iCol] = i;
  3383. }
  3384. }
  3385. for(i=0; i<3; i++){
  3386. if( (j = aIdx[i])>=0 ){
  3387. pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
  3388. pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
  3389. }
  3390. }
  3391. /* The current generate_column() implementation requires at least one
  3392. ** argument (the START value). Legacy versions assumed START=0 if the
  3393. ** first argument was omitted. Compile with -DZERO_ARGUMENT_GENERATE_SERIES
  3394. ** to obtain the legacy behavior */
  3395. #ifndef ZERO_ARGUMENT_GENERATE_SERIES
  3396. if( !bStartSeen ){
  3397. sqlite3_free(pVTab->zErrMsg);
  3398. pVTab->zErrMsg = sqlite3_mprintf(
  3399. "first argument to \"generate_series()\" missing or unusable");
  3400. return SQLITE_ERROR;
  3401. }
  3402. #endif
  3403. if( (unusableMask & ~idxNum)!=0 ){
  3404. /* The start, stop, and step columns are inputs. Therefore if there
  3405. ** are unusable constraints on any of start, stop, or step then
  3406. ** this plan is unusable */
  3407. return SQLITE_CONSTRAINT;
  3408. }
  3409. if( (idxNum & 3)==3 ){
  3410. /* Both start= and stop= boundaries are available. This is the
  3411. ** the preferred case */
  3412. pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
  3413. pIdxInfo->estimatedRows = 1000;
  3414. if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
  3415. if( pIdxInfo->aOrderBy[0].desc ){
  3416. idxNum |= 8;
  3417. }else{
  3418. idxNum |= 16;
  3419. }
  3420. pIdxInfo->orderByConsumed = 1;
  3421. }
  3422. }else{
  3423. /* If either boundary is missing, we have to generate a huge span
  3424. ** of numbers. Make this case very expensive so that the query
  3425. ** planner will work hard to avoid it. */
  3426. pIdxInfo->estimatedRows = 2147483647;
  3427. }
  3428. pIdxInfo->idxNum = idxNum;
  3429. return SQLITE_OK;
  3430. }
  3431. /*
  3432. ** This following structure defines all the methods for the
  3433. ** generate_series virtual table.
  3434. */
  3435. static sqlite3_module seriesModule = {
  3436. 0, /* iVersion */
  3437. 0, /* xCreate */
  3438. seriesConnect, /* xConnect */
  3439. seriesBestIndex, /* xBestIndex */
  3440. seriesDisconnect, /* xDisconnect */
  3441. 0, /* xDestroy */
  3442. seriesOpen, /* xOpen - open a cursor */
  3443. seriesClose, /* xClose - close a cursor */
  3444. seriesFilter, /* xFilter - configure scan constraints */
  3445. seriesNext, /* xNext - advance a cursor */
  3446. seriesEof, /* xEof - check for end of scan */
  3447. seriesColumn, /* xColumn - read data */
  3448. seriesRowid, /* xRowid - read data */
  3449. 0, /* xUpdate */
  3450. 0, /* xBegin */
  3451. 0, /* xSync */
  3452. 0, /* xCommit */
  3453. 0, /* xRollback */
  3454. 0, /* xFindMethod */
  3455. 0, /* xRename */
  3456. 0, /* xSavepoint */
  3457. 0, /* xRelease */
  3458. 0, /* xRollbackTo */
  3459. 0 /* xShadowName */
  3460. };
  3461. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  3462. #ifdef _WIN32
  3463. #endif
  3464. int sqlite3_series_init(
  3465. sqlite3 *db,
  3466. char **pzErrMsg,
  3467. const sqlite3_api_routines *pApi
  3468. ){
  3469. int rc = SQLITE_OK;
  3470. SQLITE_EXTENSION_INIT2(pApi);
  3471. #ifndef SQLITE_OMIT_VIRTUALTABLE
  3472. if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
  3473. *pzErrMsg = sqlite3_mprintf(
  3474. "generate_series() requires SQLite 3.8.12 or later");
  3475. return SQLITE_ERROR;
  3476. }
  3477. rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
  3478. #endif
  3479. return rc;
  3480. }
  3481. /************************* End ../ext/misc/series.c ********************/
  3482. /************************* Begin ../ext/misc/regexp.c ******************/
  3483. /*
  3484. ** 2012-11-13
  3485. **
  3486. ** The author disclaims copyright to this source code. In place of
  3487. ** a legal notice, here is a blessing:
  3488. **
  3489. ** May you do good and not evil.
  3490. ** May you find forgiveness for yourself and forgive others.
  3491. ** May you share freely, never taking more than you give.
  3492. **
  3493. ******************************************************************************
  3494. **
  3495. ** The code in this file implements a compact but reasonably
  3496. ** efficient regular-expression matcher for posix extended regular
  3497. ** expressions against UTF8 text.
  3498. **
  3499. ** This file is an SQLite extension. It registers a single function
  3500. ** named "regexp(A,B)" where A is the regular expression and B is the
  3501. ** string to be matched. By registering this function, SQLite will also
  3502. ** then implement the "B regexp A" operator. Note that with the function
  3503. ** the regular expression comes first, but with the operator it comes
  3504. ** second.
  3505. **
  3506. ** The following regular expression syntax is supported:
  3507. **
  3508. ** X* zero or more occurrences of X
  3509. ** X+ one or more occurrences of X
  3510. ** X? zero or one occurrences of X
  3511. ** X{p,q} between p and q occurrences of X
  3512. ** (X) match X
  3513. ** X|Y X or Y
  3514. ** ^X X occurring at the beginning of the string
  3515. ** X$ X occurring at the end of the string
  3516. ** . Match any single character
  3517. ** \c Character c where c is one of \{}()[]|*+?.
  3518. ** \c C-language escapes for c in afnrtv. ex: \t or \n
  3519. ** \uXXXX Where XXXX is exactly 4 hex digits, unicode value XXXX
  3520. ** \xXX Where XX is exactly 2 hex digits, unicode value XX
  3521. ** [abc] Any single character from the set abc
  3522. ** [^abc] Any single character not in the set abc
  3523. ** [a-z] Any single character in the range a-z
  3524. ** [^a-z] Any single character not in the range a-z
  3525. ** \b Word boundary
  3526. ** \w Word character. [A-Za-z0-9_]
  3527. ** \W Non-word character
  3528. ** \d Digit
  3529. ** \D Non-digit
  3530. ** \s Whitespace character
  3531. ** \S Non-whitespace character
  3532. **
  3533. ** A nondeterministic finite automaton (NFA) is used for matching, so the
  3534. ** performance is bounded by O(N*M) where N is the size of the regular
  3535. ** expression and M is the size of the input string. The matcher never
  3536. ** exhibits exponential behavior. Note that the X{p,q} operator expands
  3537. ** to p copies of X following by q-p copies of X? and that the size of the
  3538. ** regular expression in the O(N*M) performance bound is computed after
  3539. ** this expansion.
  3540. */
  3541. #include <string.h>
  3542. #include <stdlib.h>
  3543. /* #include "sqlite3ext.h" */
  3544. SQLITE_EXTENSION_INIT1
  3545. /*
  3546. ** The following #defines change the names of some functions implemented in
  3547. ** this file to prevent name collisions with C-library functions of the
  3548. ** same name.
  3549. */
  3550. #define re_match sqlite3re_match
  3551. #define re_compile sqlite3re_compile
  3552. #define re_free sqlite3re_free
  3553. /* The end-of-input character */
  3554. #define RE_EOF 0 /* End of input */
  3555. #define RE_START 0xfffffff /* Start of input - larger than an UTF-8 */
  3556. /* The NFA is implemented as sequence of opcodes taken from the following
  3557. ** set. Each opcode has a single integer argument.
  3558. */
  3559. #define RE_OP_MATCH 1 /* Match the one character in the argument */
  3560. #define RE_OP_ANY 2 /* Match any one character. (Implements ".") */
  3561. #define RE_OP_ANYSTAR 3 /* Special optimized version of .* */
  3562. #define RE_OP_FORK 4 /* Continue to both next and opcode at iArg */
  3563. #define RE_OP_GOTO 5 /* Jump to opcode at iArg */
  3564. #define RE_OP_ACCEPT 6 /* Halt and indicate a successful match */
  3565. #define RE_OP_CC_INC 7 /* Beginning of a [...] character class */
  3566. #define RE_OP_CC_EXC 8 /* Beginning of a [^...] character class */
  3567. #define RE_OP_CC_VALUE 9 /* Single value in a character class */
  3568. #define RE_OP_CC_RANGE 10 /* Range of values in a character class */
  3569. #define RE_OP_WORD 11 /* Perl word character [A-Za-z0-9_] */
  3570. #define RE_OP_NOTWORD 12 /* Not a perl word character */
  3571. #define RE_OP_DIGIT 13 /* digit: [0-9] */
  3572. #define RE_OP_NOTDIGIT 14 /* Not a digit */
  3573. #define RE_OP_SPACE 15 /* space: [ \t\n\r\v\f] */
  3574. #define RE_OP_NOTSPACE 16 /* Not a digit */
  3575. #define RE_OP_BOUNDARY 17 /* Boundary between word and non-word */
  3576. #define RE_OP_ATSTART 18 /* Currently at the start of the string */
  3577. #if defined(SQLITE_DEBUG)
  3578. /* Opcode names used for symbolic debugging */
  3579. static const char *ReOpName[] = {
  3580. "EOF",
  3581. "MATCH",
  3582. "ANY",
  3583. "ANYSTAR",
  3584. "FORK",
  3585. "GOTO",
  3586. "ACCEPT",
  3587. "CC_INC",
  3588. "CC_EXC",
  3589. "CC_VALUE",
  3590. "CC_RANGE",
  3591. "WORD",
  3592. "NOTWORD",
  3593. "DIGIT",
  3594. "NOTDIGIT",
  3595. "SPACE",
  3596. "NOTSPACE",
  3597. "BOUNDARY",
  3598. "ATSTART",
  3599. };
  3600. #endif /* SQLITE_DEBUG */
  3601. /* Each opcode is a "state" in the NFA */
  3602. typedef unsigned short ReStateNumber;
  3603. /* Because this is an NFA and not a DFA, multiple states can be active at
  3604. ** once. An instance of the following object records all active states in
  3605. ** the NFA. The implementation is optimized for the common case where the
  3606. ** number of actives states is small.
  3607. */
  3608. typedef struct ReStateSet {
  3609. unsigned nState; /* Number of current states */
  3610. ReStateNumber *aState; /* Current states */
  3611. } ReStateSet;
  3612. /* An input string read one character at a time.
  3613. */
  3614. typedef struct ReInput ReInput;
  3615. struct ReInput {
  3616. const unsigned char *z; /* All text */
  3617. int i; /* Next byte to read */
  3618. int mx; /* EOF when i>=mx */
  3619. };
  3620. /* A compiled NFA (or an NFA that is in the process of being compiled) is
  3621. ** an instance of the following object.
  3622. */
  3623. typedef struct ReCompiled ReCompiled;
  3624. struct ReCompiled {
  3625. ReInput sIn; /* Regular expression text */
  3626. const char *zErr; /* Error message to return */
  3627. char *aOp; /* Operators for the virtual machine */
  3628. int *aArg; /* Arguments to each operator */
  3629. unsigned (*xNextChar)(ReInput*); /* Next character function */
  3630. unsigned char zInit[12]; /* Initial text to match */
  3631. int nInit; /* Number of bytes in zInit */
  3632. unsigned nState; /* Number of entries in aOp[] and aArg[] */
  3633. unsigned nAlloc; /* Slots allocated for aOp[] and aArg[] */
  3634. };
  3635. /* Add a state to the given state set if it is not already there */
  3636. static void re_add_state(ReStateSet *pSet, int newState){
  3637. unsigned i;
  3638. for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
  3639. pSet->aState[pSet->nState++] = (ReStateNumber)newState;
  3640. }
  3641. /* Extract the next unicode character from *pzIn and return it. Advance
  3642. ** *pzIn to the first byte past the end of the character returned. To
  3643. ** be clear: this routine converts utf8 to unicode. This routine is
  3644. ** optimized for the common case where the next character is a single byte.
  3645. */
  3646. static unsigned re_next_char(ReInput *p){
  3647. unsigned c;
  3648. if( p->i>=p->mx ) return 0;
  3649. c = p->z[p->i++];
  3650. if( c>=0x80 ){
  3651. if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
  3652. c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
  3653. if( c<0x80 ) c = 0xfffd;
  3654. }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
  3655. && (p->z[p->i+1]&0xc0)==0x80 ){
  3656. c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
  3657. p->i += 2;
  3658. if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
  3659. }else if( (c&0xf8)==0xf0 && p->i+3<p->mx && (p->z[p->i]&0xc0)==0x80
  3660. && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
  3661. c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
  3662. | (p->z[p->i+2]&0x3f);
  3663. p->i += 3;
  3664. if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
  3665. }else{
  3666. c = 0xfffd;
  3667. }
  3668. }
  3669. return c;
  3670. }
  3671. static unsigned re_next_char_nocase(ReInput *p){
  3672. unsigned c = re_next_char(p);
  3673. if( c>='A' && c<='Z' ) c += 'a' - 'A';
  3674. return c;
  3675. }
  3676. /* Return true if c is a perl "word" character: [A-Za-z0-9_] */
  3677. static int re_word_char(int c){
  3678. return (c>='0' && c<='9') || (c>='a' && c<='z')
  3679. || (c>='A' && c<='Z') || c=='_';
  3680. }
  3681. /* Return true if c is a "digit" character: [0-9] */
  3682. static int re_digit_char(int c){
  3683. return (c>='0' && c<='9');
  3684. }
  3685. /* Return true if c is a perl "space" character: [ \t\r\n\v\f] */
  3686. static int re_space_char(int c){
  3687. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  3688. }
  3689. /* Run a compiled regular expression on the zero-terminated input
  3690. ** string zIn[]. Return true on a match and false if there is no match.
  3691. */
  3692. static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
  3693. ReStateSet aStateSet[2], *pThis, *pNext;
  3694. ReStateNumber aSpace[100];
  3695. ReStateNumber *pToFree;
  3696. unsigned int i = 0;
  3697. unsigned int iSwap = 0;
  3698. int c = RE_START;
  3699. int cPrev = 0;
  3700. int rc = 0;
  3701. ReInput in;
  3702. in.z = zIn;
  3703. in.i = 0;
  3704. in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
  3705. /* Look for the initial prefix match, if there is one. */
  3706. if( pRe->nInit ){
  3707. unsigned char x = pRe->zInit[0];
  3708. while( in.i+pRe->nInit<=in.mx
  3709. && (zIn[in.i]!=x ||
  3710. strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
  3711. ){
  3712. in.i++;
  3713. }
  3714. if( in.i+pRe->nInit>in.mx ) return 0;
  3715. c = RE_START-1;
  3716. }
  3717. if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
  3718. pToFree = 0;
  3719. aStateSet[0].aState = aSpace;
  3720. }else{
  3721. pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
  3722. if( pToFree==0 ) return -1;
  3723. aStateSet[0].aState = pToFree;
  3724. }
  3725. aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
  3726. pNext = &aStateSet[1];
  3727. pNext->nState = 0;
  3728. re_add_state(pNext, 0);
  3729. while( c!=RE_EOF && pNext->nState>0 ){
  3730. cPrev = c;
  3731. c = pRe->xNextChar(&in);
  3732. pThis = pNext;
  3733. pNext = &aStateSet[iSwap];
  3734. iSwap = 1 - iSwap;
  3735. pNext->nState = 0;
  3736. for(i=0; i<pThis->nState; i++){
  3737. int x = pThis->aState[i];
  3738. switch( pRe->aOp[x] ){
  3739. case RE_OP_MATCH: {
  3740. if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
  3741. break;
  3742. }
  3743. case RE_OP_ATSTART: {
  3744. if( cPrev==RE_START ) re_add_state(pThis, x+1);
  3745. break;
  3746. }
  3747. case RE_OP_ANY: {
  3748. if( c!=0 ) re_add_state(pNext, x+1);
  3749. break;
  3750. }
  3751. case RE_OP_WORD: {
  3752. if( re_word_char(c) ) re_add_state(pNext, x+1);
  3753. break;
  3754. }
  3755. case RE_OP_NOTWORD: {
  3756. if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
  3757. break;
  3758. }
  3759. case RE_OP_DIGIT: {
  3760. if( re_digit_char(c) ) re_add_state(pNext, x+1);
  3761. break;
  3762. }
  3763. case RE_OP_NOTDIGIT: {
  3764. if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
  3765. break;
  3766. }
  3767. case RE_OP_SPACE: {
  3768. if( re_space_char(c) ) re_add_state(pNext, x+1);
  3769. break;
  3770. }
  3771. case RE_OP_NOTSPACE: {
  3772. if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
  3773. break;
  3774. }
  3775. case RE_OP_BOUNDARY: {
  3776. if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
  3777. break;
  3778. }
  3779. case RE_OP_ANYSTAR: {
  3780. re_add_state(pNext, x);
  3781. re_add_state(pThis, x+1);
  3782. break;
  3783. }
  3784. case RE_OP_FORK: {
  3785. re_add_state(pThis, x+pRe->aArg[x]);
  3786. re_add_state(pThis, x+1);
  3787. break;
  3788. }
  3789. case RE_OP_GOTO: {
  3790. re_add_state(pThis, x+pRe->aArg[x]);
  3791. break;
  3792. }
  3793. case RE_OP_ACCEPT: {
  3794. rc = 1;
  3795. goto re_match_end;
  3796. }
  3797. case RE_OP_CC_EXC: {
  3798. if( c==0 ) break;
  3799. /* fall-through */ goto re_op_cc_inc;
  3800. }
  3801. case RE_OP_CC_INC: re_op_cc_inc: {
  3802. int j = 1;
  3803. int n = pRe->aArg[x];
  3804. int hit = 0;
  3805. for(j=1; j>0 && j<n; j++){
  3806. if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
  3807. if( pRe->aArg[x+j]==c ){
  3808. hit = 1;
  3809. j = -1;
  3810. }
  3811. }else{
  3812. if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
  3813. hit = 1;
  3814. j = -1;
  3815. }else{
  3816. j++;
  3817. }
  3818. }
  3819. }
  3820. if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
  3821. if( hit ) re_add_state(pNext, x+n);
  3822. break;
  3823. }
  3824. }
  3825. }
  3826. }
  3827. for(i=0; i<pNext->nState; i++){
  3828. int x = pNext->aState[i];
  3829. while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x];
  3830. if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; }
  3831. }
  3832. re_match_end:
  3833. sqlite3_free(pToFree);
  3834. return rc;
  3835. }
  3836. /* Resize the opcode and argument arrays for an RE under construction.
  3837. */
  3838. static int re_resize(ReCompiled *p, int N){
  3839. char *aOp;
  3840. int *aArg;
  3841. aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
  3842. if( aOp==0 ) return 1;
  3843. p->aOp = aOp;
  3844. aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
  3845. if( aArg==0 ) return 1;
  3846. p->aArg = aArg;
  3847. p->nAlloc = N;
  3848. return 0;
  3849. }
  3850. /* Insert a new opcode and argument into an RE under construction. The
  3851. ** insertion point is just prior to existing opcode iBefore.
  3852. */
  3853. static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
  3854. int i;
  3855. if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
  3856. for(i=p->nState; i>iBefore; i--){
  3857. p->aOp[i] = p->aOp[i-1];
  3858. p->aArg[i] = p->aArg[i-1];
  3859. }
  3860. p->nState++;
  3861. p->aOp[iBefore] = (char)op;
  3862. p->aArg[iBefore] = arg;
  3863. return iBefore;
  3864. }
  3865. /* Append a new opcode and argument to the end of the RE under construction.
  3866. */
  3867. static int re_append(ReCompiled *p, int op, int arg){
  3868. return re_insert(p, p->nState, op, arg);
  3869. }
  3870. /* Make a copy of N opcodes starting at iStart onto the end of the RE
  3871. ** under construction.
  3872. */
  3873. static void re_copy(ReCompiled *p, int iStart, int N){
  3874. if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
  3875. memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
  3876. memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
  3877. p->nState += N;
  3878. }
  3879. /* Return true if c is a hexadecimal digit character: [0-9a-fA-F]
  3880. ** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c). If
  3881. ** c is not a hex digit *pV is unchanged.
  3882. */
  3883. static int re_hex(int c, int *pV){
  3884. if( c>='0' && c<='9' ){
  3885. c -= '0';
  3886. }else if( c>='a' && c<='f' ){
  3887. c -= 'a' - 10;
  3888. }else if( c>='A' && c<='F' ){
  3889. c -= 'A' - 10;
  3890. }else{
  3891. return 0;
  3892. }
  3893. *pV = (*pV)*16 + (c & 0xff);
  3894. return 1;
  3895. }
  3896. /* A backslash character has been seen, read the next character and
  3897. ** return its interpretation.
  3898. */
  3899. static unsigned re_esc_char(ReCompiled *p){
  3900. static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
  3901. static const char zTrans[] = "\a\f\n\r\t\v";
  3902. int i, v = 0;
  3903. char c;
  3904. if( p->sIn.i>=p->sIn.mx ) return 0;
  3905. c = p->sIn.z[p->sIn.i];
  3906. if( c=='u' && p->sIn.i+4<p->sIn.mx ){
  3907. const unsigned char *zIn = p->sIn.z + p->sIn.i;
  3908. if( re_hex(zIn[1],&v)
  3909. && re_hex(zIn[2],&v)
  3910. && re_hex(zIn[3],&v)
  3911. && re_hex(zIn[4],&v)
  3912. ){
  3913. p->sIn.i += 5;
  3914. return v;
  3915. }
  3916. }
  3917. if( c=='x' && p->sIn.i+2<p->sIn.mx ){
  3918. const unsigned char *zIn = p->sIn.z + p->sIn.i;
  3919. if( re_hex(zIn[1],&v)
  3920. && re_hex(zIn[2],&v)
  3921. ){
  3922. p->sIn.i += 3;
  3923. return v;
  3924. }
  3925. }
  3926. for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
  3927. if( zEsc[i] ){
  3928. if( i<6 ) c = zTrans[i];
  3929. p->sIn.i++;
  3930. }else{
  3931. p->zErr = "unknown \\ escape";
  3932. }
  3933. return c;
  3934. }
  3935. /* Forward declaration */
  3936. static const char *re_subcompile_string(ReCompiled*);
  3937. /* Peek at the next byte of input */
  3938. static unsigned char rePeek(ReCompiled *p){
  3939. return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
  3940. }
  3941. /* Compile RE text into a sequence of opcodes. Continue up to the
  3942. ** first unmatched ")" character, then return. If an error is found,
  3943. ** return a pointer to the error message string.
  3944. */
  3945. static const char *re_subcompile_re(ReCompiled *p){
  3946. const char *zErr;
  3947. int iStart, iEnd, iGoto;
  3948. iStart = p->nState;
  3949. zErr = re_subcompile_string(p);
  3950. if( zErr ) return zErr;
  3951. while( rePeek(p)=='|' ){
  3952. iEnd = p->nState;
  3953. re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
  3954. iGoto = re_append(p, RE_OP_GOTO, 0);
  3955. p->sIn.i++;
  3956. zErr = re_subcompile_string(p);
  3957. if( zErr ) return zErr;
  3958. p->aArg[iGoto] = p->nState - iGoto;
  3959. }
  3960. return 0;
  3961. }
  3962. /* Compile an element of regular expression text (anything that can be
  3963. ** an operand to the "|" operator). Return NULL on success or a pointer
  3964. ** to the error message if there is a problem.
  3965. */
  3966. static const char *re_subcompile_string(ReCompiled *p){
  3967. int iPrev = -1;
  3968. int iStart;
  3969. unsigned c;
  3970. const char *zErr;
  3971. while( (c = p->xNextChar(&p->sIn))!=0 ){
  3972. iStart = p->nState;
  3973. switch( c ){
  3974. case '|':
  3975. case ')': {
  3976. p->sIn.i--;
  3977. return 0;
  3978. }
  3979. case '(': {
  3980. zErr = re_subcompile_re(p);
  3981. if( zErr ) return zErr;
  3982. if( rePeek(p)!=')' ) return "unmatched '('";
  3983. p->sIn.i++;
  3984. break;
  3985. }
  3986. case '.': {
  3987. if( rePeek(p)=='*' ){
  3988. re_append(p, RE_OP_ANYSTAR, 0);
  3989. p->sIn.i++;
  3990. }else{
  3991. re_append(p, RE_OP_ANY, 0);
  3992. }
  3993. break;
  3994. }
  3995. case '*': {
  3996. if( iPrev<0 ) return "'*' without operand";
  3997. re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
  3998. re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
  3999. break;
  4000. }
  4001. case '+': {
  4002. if( iPrev<0 ) return "'+' without operand";
  4003. re_append(p, RE_OP_FORK, iPrev - p->nState);
  4004. break;
  4005. }
  4006. case '?': {
  4007. if( iPrev<0 ) return "'?' without operand";
  4008. re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
  4009. break;
  4010. }
  4011. case '$': {
  4012. re_append(p, RE_OP_MATCH, RE_EOF);
  4013. break;
  4014. }
  4015. case '^': {
  4016. re_append(p, RE_OP_ATSTART, 0);
  4017. break;
  4018. }
  4019. case '{': {
  4020. int m = 0, n = 0;
  4021. int sz, j;
  4022. if( iPrev<0 ) return "'{m,n}' without operand";
  4023. while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
  4024. n = m;
  4025. if( c==',' ){
  4026. p->sIn.i++;
  4027. n = 0;
  4028. while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
  4029. }
  4030. if( c!='}' ) return "unmatched '{'";
  4031. if( n>0 && n<m ) return "n less than m in '{m,n}'";
  4032. p->sIn.i++;
  4033. sz = p->nState - iPrev;
  4034. if( m==0 ){
  4035. if( n==0 ) return "both m and n are zero in '{m,n}'";
  4036. re_insert(p, iPrev, RE_OP_FORK, sz+1);
  4037. iPrev++;
  4038. n--;
  4039. }else{
  4040. for(j=1; j<m; j++) re_copy(p, iPrev, sz);
  4041. }
  4042. for(j=m; j<n; j++){
  4043. re_append(p, RE_OP_FORK, sz+1);
  4044. re_copy(p, iPrev, sz);
  4045. }
  4046. if( n==0 && m>0 ){
  4047. re_append(p, RE_OP_FORK, -sz);
  4048. }
  4049. break;
  4050. }
  4051. case '[': {
  4052. int iFirst = p->nState;
  4053. if( rePeek(p)=='^' ){
  4054. re_append(p, RE_OP_CC_EXC, 0);
  4055. p->sIn.i++;
  4056. }else{
  4057. re_append(p, RE_OP_CC_INC, 0);
  4058. }
  4059. while( (c = p->xNextChar(&p->sIn))!=0 ){
  4060. if( c=='[' && rePeek(p)==':' ){
  4061. return "POSIX character classes not supported";
  4062. }
  4063. if( c=='\\' ) c = re_esc_char(p);
  4064. if( rePeek(p)=='-' ){
  4065. re_append(p, RE_OP_CC_RANGE, c);
  4066. p->sIn.i++;
  4067. c = p->xNextChar(&p->sIn);
  4068. if( c=='\\' ) c = re_esc_char(p);
  4069. re_append(p, RE_OP_CC_RANGE, c);
  4070. }else{
  4071. re_append(p, RE_OP_CC_VALUE, c);
  4072. }
  4073. if( rePeek(p)==']' ){ p->sIn.i++; break; }
  4074. }
  4075. if( c==0 ) return "unclosed '['";
  4076. p->aArg[iFirst] = p->nState - iFirst;
  4077. break;
  4078. }
  4079. case '\\': {
  4080. int specialOp = 0;
  4081. switch( rePeek(p) ){
  4082. case 'b': specialOp = RE_OP_BOUNDARY; break;
  4083. case 'd': specialOp = RE_OP_DIGIT; break;
  4084. case 'D': specialOp = RE_OP_NOTDIGIT; break;
  4085. case 's': specialOp = RE_OP_SPACE; break;
  4086. case 'S': specialOp = RE_OP_NOTSPACE; break;
  4087. case 'w': specialOp = RE_OP_WORD; break;
  4088. case 'W': specialOp = RE_OP_NOTWORD; break;
  4089. }
  4090. if( specialOp ){
  4091. p->sIn.i++;
  4092. re_append(p, specialOp, 0);
  4093. }else{
  4094. c = re_esc_char(p);
  4095. re_append(p, RE_OP_MATCH, c);
  4096. }
  4097. break;
  4098. }
  4099. default: {
  4100. re_append(p, RE_OP_MATCH, c);
  4101. break;
  4102. }
  4103. }
  4104. iPrev = iStart;
  4105. }
  4106. return 0;
  4107. }
  4108. /* Free and reclaim all the memory used by a previously compiled
  4109. ** regular expression. Applications should invoke this routine once
  4110. ** for every call to re_compile() to avoid memory leaks.
  4111. */
  4112. static void re_free(ReCompiled *pRe){
  4113. if( pRe ){
  4114. sqlite3_free(pRe->aOp);
  4115. sqlite3_free(pRe->aArg);
  4116. sqlite3_free(pRe);
  4117. }
  4118. }
  4119. /*
  4120. ** Compile a textual regular expression in zIn[] into a compiled regular
  4121. ** expression suitable for us by re_match() and return a pointer to the
  4122. ** compiled regular expression in *ppRe. Return NULL on success or an
  4123. ** error message if something goes wrong.
  4124. */
  4125. static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
  4126. ReCompiled *pRe;
  4127. const char *zErr;
  4128. int i, j;
  4129. *ppRe = 0;
  4130. pRe = sqlite3_malloc( sizeof(*pRe) );
  4131. if( pRe==0 ){
  4132. return "out of memory";
  4133. }
  4134. memset(pRe, 0, sizeof(*pRe));
  4135. pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
  4136. if( re_resize(pRe, 30) ){
  4137. re_free(pRe);
  4138. return "out of memory";
  4139. }
  4140. if( zIn[0]=='^' ){
  4141. zIn++;
  4142. }else{
  4143. re_append(pRe, RE_OP_ANYSTAR, 0);
  4144. }
  4145. pRe->sIn.z = (unsigned char*)zIn;
  4146. pRe->sIn.i = 0;
  4147. pRe->sIn.mx = (int)strlen(zIn);
  4148. zErr = re_subcompile_re(pRe);
  4149. if( zErr ){
  4150. re_free(pRe);
  4151. return zErr;
  4152. }
  4153. if( pRe->sIn.i>=pRe->sIn.mx ){
  4154. re_append(pRe, RE_OP_ACCEPT, 0);
  4155. *ppRe = pRe;
  4156. }else{
  4157. re_free(pRe);
  4158. return "unrecognized character";
  4159. }
  4160. /* The following is a performance optimization. If the regex begins with
  4161. ** ".*" (if the input regex lacks an initial "^") and afterwards there are
  4162. ** one or more matching characters, enter those matching characters into
  4163. ** zInit[]. The re_match() routine can then search ahead in the input
  4164. ** string looking for the initial match without having to run the whole
  4165. ** regex engine over the string. Do not worry able trying to match
  4166. ** unicode characters beyond plane 0 - those are very rare and this is
  4167. ** just an optimization. */
  4168. if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
  4169. for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
  4170. unsigned x = pRe->aArg[i];
  4171. if( x<=127 ){
  4172. pRe->zInit[j++] = (unsigned char)x;
  4173. }else if( x<=0xfff ){
  4174. pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
  4175. pRe->zInit[j++] = 0x80 | (x&0x3f);
  4176. }else if( x<=0xffff ){
  4177. pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12));
  4178. pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
  4179. pRe->zInit[j++] = 0x80 | (x&0x3f);
  4180. }else{
  4181. break;
  4182. }
  4183. }
  4184. if( j>0 && pRe->zInit[j-1]==0 ) j--;
  4185. pRe->nInit = j;
  4186. }
  4187. return pRe->zErr;
  4188. }
  4189. /*
  4190. ** Implementation of the regexp() SQL function. This function implements
  4191. ** the build-in REGEXP operator. The first argument to the function is the
  4192. ** pattern and the second argument is the string. So, the SQL statements:
  4193. **
  4194. ** A REGEXP B
  4195. **
  4196. ** is implemented as regexp(B,A).
  4197. */
  4198. static void re_sql_func(
  4199. sqlite3_context *context,
  4200. int argc,
  4201. sqlite3_value **argv
  4202. ){
  4203. ReCompiled *pRe; /* Compiled regular expression */
  4204. const char *zPattern; /* The regular expression */
  4205. const unsigned char *zStr;/* String being searched */
  4206. const char *zErr; /* Compile error message */
  4207. int setAux = 0; /* True to invoke sqlite3_set_auxdata() */
  4208. (void)argc; /* Unused */
  4209. pRe = sqlite3_get_auxdata(context, 0);
  4210. if( pRe==0 ){
  4211. zPattern = (const char*)sqlite3_value_text(argv[0]);
  4212. if( zPattern==0 ) return;
  4213. zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
  4214. if( zErr ){
  4215. re_free(pRe);
  4216. sqlite3_result_error(context, zErr, -1);
  4217. return;
  4218. }
  4219. if( pRe==0 ){
  4220. sqlite3_result_error_nomem(context);
  4221. return;
  4222. }
  4223. setAux = 1;
  4224. }
  4225. zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
  4226. if( zStr!=0 ){
  4227. sqlite3_result_int(context, re_match(pRe, zStr, -1));
  4228. }
  4229. if( setAux ){
  4230. sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free);
  4231. }
  4232. }
  4233. #if defined(SQLITE_DEBUG)
  4234. /*
  4235. ** This function is used for testing and debugging only. It is only available
  4236. ** if the SQLITE_DEBUG compile-time option is used.
  4237. **
  4238. ** Compile a regular expression and then convert the compiled expression into
  4239. ** text and return that text.
  4240. */
  4241. static void re_bytecode_func(
  4242. sqlite3_context *context,
  4243. int argc,
  4244. sqlite3_value **argv
  4245. ){
  4246. const char *zPattern;
  4247. const char *zErr;
  4248. ReCompiled *pRe;
  4249. sqlite3_str *pStr;
  4250. int i;
  4251. int n;
  4252. char *z;
  4253. zPattern = (const char*)sqlite3_value_text(argv[0]);
  4254. if( zPattern==0 ) return;
  4255. zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
  4256. if( zErr ){
  4257. re_free(pRe);
  4258. sqlite3_result_error(context, zErr, -1);
  4259. return;
  4260. }
  4261. if( pRe==0 ){
  4262. sqlite3_result_error_nomem(context);
  4263. return;
  4264. }
  4265. pStr = sqlite3_str_new(0);
  4266. if( pStr==0 ) goto re_bytecode_func_err;
  4267. if( pRe->nInit>0 ){
  4268. sqlite3_str_appendf(pStr, "INIT ");
  4269. for(i=0; i<pRe->nInit; i++){
  4270. sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]);
  4271. }
  4272. sqlite3_str_appendf(pStr, "\n");
  4273. }
  4274. for(i=0; (unsigned)i<pRe->nState; i++){
  4275. sqlite3_str_appendf(pStr, "%-8s %4d\n",
  4276. ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]);
  4277. }
  4278. n = sqlite3_str_length(pStr);
  4279. z = sqlite3_str_finish(pStr);
  4280. if( n==0 ){
  4281. sqlite3_free(z);
  4282. }else{
  4283. sqlite3_result_text(context, z, n-1, sqlite3_free);
  4284. }
  4285. re_bytecode_func_err:
  4286. re_free(pRe);
  4287. }
  4288. #endif /* SQLITE_DEBUG */
  4289. /*
  4290. ** Invoke this routine to register the regexp() function with the
  4291. ** SQLite database connection.
  4292. */
  4293. #ifdef _WIN32
  4294. #endif
  4295. int sqlite3_regexp_init(
  4296. sqlite3 *db,
  4297. char **pzErrMsg,
  4298. const sqlite3_api_routines *pApi
  4299. ){
  4300. int rc = SQLITE_OK;
  4301. SQLITE_EXTENSION_INIT2(pApi);
  4302. (void)pzErrMsg; /* Unused */
  4303. rc = sqlite3_create_function(db, "regexp", 2,
  4304. SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
  4305. 0, re_sql_func, 0, 0);
  4306. if( rc==SQLITE_OK ){
  4307. /* The regexpi(PATTERN,STRING) function is a case-insensitive version
  4308. ** of regexp(PATTERN,STRING). */
  4309. rc = sqlite3_create_function(db, "regexpi", 2,
  4310. SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
  4311. (void*)db, re_sql_func, 0, 0);
  4312. #if defined(SQLITE_DEBUG)
  4313. if( rc==SQLITE_OK ){
  4314. rc = sqlite3_create_function(db, "regexp_bytecode", 1,
  4315. SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
  4316. 0, re_bytecode_func, 0, 0);
  4317. }
  4318. #endif /* SQLITE_DEBUG */
  4319. }
  4320. return rc;
  4321. }
  4322. /************************* End ../ext/misc/regexp.c ********************/
  4323. #ifndef SQLITE_SHELL_FIDDLE
  4324. /************************* Begin ../ext/misc/fileio.c ******************/
  4325. /*
  4326. ** 2014-06-13
  4327. **
  4328. ** The author disclaims copyright to this source code. In place of
  4329. ** a legal notice, here is a blessing:
  4330. **
  4331. ** May you do good and not evil.
  4332. ** May you find forgiveness for yourself and forgive others.
  4333. ** May you share freely, never taking more than you give.
  4334. **
  4335. ******************************************************************************
  4336. **
  4337. ** This SQLite extension implements SQL functions readfile() and
  4338. ** writefile(), and eponymous virtual type "fsdir".
  4339. **
  4340. ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
  4341. **
  4342. ** If neither of the optional arguments is present, then this UDF
  4343. ** function writes blob DATA to file FILE. If successful, the number
  4344. ** of bytes written is returned. If an error occurs, NULL is returned.
  4345. **
  4346. ** If the first option argument - MODE - is present, then it must
  4347. ** be passed an integer value that corresponds to a POSIX mode
  4348. ** value (file type + permissions, as returned in the stat.st_mode
  4349. ** field by the stat() system call). Three types of files may
  4350. ** be written/created:
  4351. **
  4352. ** regular files: (mode & 0170000)==0100000
  4353. ** symbolic links: (mode & 0170000)==0120000
  4354. ** directories: (mode & 0170000)==0040000
  4355. **
  4356. ** For a directory, the DATA is ignored. For a symbolic link, it is
  4357. ** interpreted as text and used as the target of the link. For a
  4358. ** regular file, it is interpreted as a blob and written into the
  4359. ** named file. Regardless of the type of file, its permissions are
  4360. ** set to (mode & 0777) before returning.
  4361. **
  4362. ** If the optional MTIME argument is present, then it is interpreted
  4363. ** as an integer - the number of seconds since the unix epoch. The
  4364. ** modification-time of the target file is set to this value before
  4365. ** returning.
  4366. **
  4367. ** If three or more arguments are passed to this function and an
  4368. ** error is encountered, an exception is raised.
  4369. **
  4370. ** READFILE(FILE):
  4371. **
  4372. ** Read and return the contents of file FILE (type blob) from disk.
  4373. **
  4374. ** FSDIR:
  4375. **
  4376. ** Used as follows:
  4377. **
  4378. ** SELECT * FROM fsdir($path [, $dir]);
  4379. **
  4380. ** Parameter $path is an absolute or relative pathname. If the file that it
  4381. ** refers to does not exist, it is an error. If the path refers to a regular
  4382. ** file or symbolic link, it returns a single row. Or, if the path refers
  4383. ** to a directory, it returns one row for the directory, and one row for each
  4384. ** file within the hierarchy rooted at $path.
  4385. **
  4386. ** Each row has the following columns:
  4387. **
  4388. ** name: Path to file or directory (text value).
  4389. ** mode: Value of stat.st_mode for directory entry (an integer).
  4390. ** mtime: Value of stat.st_mtime for directory entry (an integer).
  4391. ** data: For a regular file, a blob containing the file data. For a
  4392. ** symlink, a text value containing the text of the link. For a
  4393. ** directory, NULL.
  4394. **
  4395. ** If a non-NULL value is specified for the optional $dir parameter and
  4396. ** $path is a relative path, then $path is interpreted relative to $dir.
  4397. ** And the paths returned in the "name" column of the table are also
  4398. ** relative to directory $dir.
  4399. **
  4400. ** Notes on building this extension for Windows:
  4401. ** Unless linked statically with the SQLite library, a preprocessor
  4402. ** symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
  4403. ** DLL form of this extension for WIN32. See its use below for details.
  4404. */
  4405. /* #include "sqlite3ext.h" */
  4406. SQLITE_EXTENSION_INIT1
  4407. #include <stdio.h>
  4408. #include <string.h>
  4409. #include <assert.h>
  4410. #include <sys/types.h>
  4411. #include <sys/stat.h>
  4412. #include <fcntl.h>
  4413. #if !defined(_WIN32) && !defined(WIN32)
  4414. # include <unistd.h>
  4415. # include <dirent.h>
  4416. # include <utime.h>
  4417. # include <sys/time.h>
  4418. #else
  4419. # include "windows.h"
  4420. # include <io.h>
  4421. # include <direct.h>
  4422. /* # include "test_windirent.h" */
  4423. # define dirent DIRENT
  4424. # ifndef chmod
  4425. # define chmod _chmod
  4426. # endif
  4427. # ifndef stat
  4428. # define stat _stat
  4429. # endif
  4430. # define mkdir(path,mode) _mkdir(path)
  4431. # define lstat(path,buf) stat(path,buf)
  4432. #endif
  4433. #include <time.h>
  4434. #include <errno.h>
  4435. /*
  4436. ** Structure of the fsdir() table-valued function
  4437. */
  4438. /* 0 1 2 3 4 5 */
  4439. #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
  4440. #define FSDIR_COLUMN_NAME 0 /* Name of the file */
  4441. #define FSDIR_COLUMN_MODE 1 /* Access mode */
  4442. #define FSDIR_COLUMN_MTIME 2 /* Last modification time */
  4443. #define FSDIR_COLUMN_DATA 3 /* File content */
  4444. #define FSDIR_COLUMN_PATH 4 /* Path to top of search */
  4445. #define FSDIR_COLUMN_DIR 5 /* Path is relative to this directory */
  4446. /*
  4447. ** Set the result stored by context ctx to a blob containing the
  4448. ** contents of file zName. Or, leave the result unchanged (NULL)
  4449. ** if the file does not exist or is unreadable.
  4450. **
  4451. ** If the file exceeds the SQLite blob size limit, through an
  4452. ** SQLITE_TOOBIG error.
  4453. **
  4454. ** Throw an SQLITE_IOERR if there are difficulties pulling the file
  4455. ** off of disk.
  4456. */
  4457. static void readFileContents(sqlite3_context *ctx, const char *zName){
  4458. FILE *in;
  4459. sqlite3_int64 nIn;
  4460. void *pBuf;
  4461. sqlite3 *db;
  4462. int mxBlob;
  4463. in = fopen(zName, "rb");
  4464. if( in==0 ){
  4465. /* File does not exist or is unreadable. Leave the result set to NULL. */
  4466. return;
  4467. }
  4468. fseek(in, 0, SEEK_END);
  4469. nIn = ftell(in);
  4470. rewind(in);
  4471. db = sqlite3_context_db_handle(ctx);
  4472. mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
  4473. if( nIn>mxBlob ){
  4474. sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
  4475. fclose(in);
  4476. return;
  4477. }
  4478. pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
  4479. if( pBuf==0 ){
  4480. sqlite3_result_error_nomem(ctx);
  4481. fclose(in);
  4482. return;
  4483. }
  4484. if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
  4485. sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
  4486. }else{
  4487. sqlite3_result_error_code(ctx, SQLITE_IOERR);
  4488. sqlite3_free(pBuf);
  4489. }
  4490. fclose(in);
  4491. }
  4492. /*
  4493. ** Implementation of the "readfile(X)" SQL function. The entire content
  4494. ** of the file named X is read and returned as a BLOB. NULL is returned
  4495. ** if the file does not exist or is unreadable.
  4496. */
  4497. static void readfileFunc(
  4498. sqlite3_context *context,
  4499. int argc,
  4500. sqlite3_value **argv
  4501. ){
  4502. const char *zName;
  4503. (void)(argc); /* Unused parameter */
  4504. zName = (const char*)sqlite3_value_text(argv[0]);
  4505. if( zName==0 ) return;
  4506. readFileContents(context, zName);
  4507. }
  4508. /*
  4509. ** Set the error message contained in context ctx to the results of
  4510. ** vprintf(zFmt, ...).
  4511. */
  4512. static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
  4513. char *zMsg = 0;
  4514. va_list ap;
  4515. va_start(ap, zFmt);
  4516. zMsg = sqlite3_vmprintf(zFmt, ap);
  4517. sqlite3_result_error(ctx, zMsg, -1);
  4518. sqlite3_free(zMsg);
  4519. va_end(ap);
  4520. }
  4521. #if defined(_WIN32)
  4522. /*
  4523. ** This function is designed to convert a Win32 FILETIME structure into the
  4524. ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
  4525. */
  4526. static sqlite3_uint64 fileTimeToUnixTime(
  4527. LPFILETIME pFileTime
  4528. ){
  4529. SYSTEMTIME epochSystemTime;
  4530. ULARGE_INTEGER epochIntervals;
  4531. FILETIME epochFileTime;
  4532. ULARGE_INTEGER fileIntervals;
  4533. memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
  4534. epochSystemTime.wYear = 1970;
  4535. epochSystemTime.wMonth = 1;
  4536. epochSystemTime.wDay = 1;
  4537. SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
  4538. epochIntervals.LowPart = epochFileTime.dwLowDateTime;
  4539. epochIntervals.HighPart = epochFileTime.dwHighDateTime;
  4540. fileIntervals.LowPart = pFileTime->dwLowDateTime;
  4541. fileIntervals.HighPart = pFileTime->dwHighDateTime;
  4542. return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
  4543. }
  4544. #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
  4545. # /* To allow a standalone DLL, use this next replacement function: */
  4546. # undef sqlite3_win32_utf8_to_unicode
  4547. # define sqlite3_win32_utf8_to_unicode utf8_to_utf16
  4548. #
  4549. LPWSTR utf8_to_utf16(const char *z){
  4550. int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0);
  4551. LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR));
  4552. if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) )
  4553. return rv;
  4554. sqlite3_free(rv);
  4555. return 0;
  4556. }
  4557. #endif
  4558. /*
  4559. ** This function attempts to normalize the time values found in the stat()
  4560. ** buffer to UTC. This is necessary on Win32, where the runtime library
  4561. ** appears to return these values as local times.
  4562. */
  4563. static void statTimesToUtc(
  4564. const char *zPath,
  4565. struct stat *pStatBuf
  4566. ){
  4567. HANDLE hFindFile;
  4568. WIN32_FIND_DATAW fd;
  4569. LPWSTR zUnicodeName;
  4570. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
  4571. zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
  4572. if( zUnicodeName ){
  4573. memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
  4574. hFindFile = FindFirstFileW(zUnicodeName, &fd);
  4575. if( hFindFile!=NULL ){
  4576. pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
  4577. pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
  4578. pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
  4579. FindClose(hFindFile);
  4580. }
  4581. sqlite3_free(zUnicodeName);
  4582. }
  4583. }
  4584. #endif
  4585. /*
  4586. ** This function is used in place of stat(). On Windows, special handling
  4587. ** is required in order for the included time to be returned as UTC. On all
  4588. ** other systems, this function simply calls stat().
  4589. */
  4590. static int fileStat(
  4591. const char *zPath,
  4592. struct stat *pStatBuf
  4593. ){
  4594. #if defined(_WIN32)
  4595. int rc = stat(zPath, pStatBuf);
  4596. if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
  4597. return rc;
  4598. #else
  4599. return stat(zPath, pStatBuf);
  4600. #endif
  4601. }
  4602. /*
  4603. ** This function is used in place of lstat(). On Windows, special handling
  4604. ** is required in order for the included time to be returned as UTC. On all
  4605. ** other systems, this function simply calls lstat().
  4606. */
  4607. static int fileLinkStat(
  4608. const char *zPath,
  4609. struct stat *pStatBuf
  4610. ){
  4611. #if defined(_WIN32)
  4612. int rc = lstat(zPath, pStatBuf);
  4613. if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
  4614. return rc;
  4615. #else
  4616. return lstat(zPath, pStatBuf);
  4617. #endif
  4618. }
  4619. /*
  4620. ** Argument zFile is the name of a file that will be created and/or written
  4621. ** by SQL function writefile(). This function ensures that the directory
  4622. ** zFile will be written to exists, creating it if required. The permissions
  4623. ** for any path components created by this function are set in accordance
  4624. ** with the current umask.
  4625. **
  4626. ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
  4627. ** SQLITE_OK is returned if the directory is successfully created, or
  4628. ** SQLITE_ERROR otherwise.
  4629. */
  4630. static int makeDirectory(
  4631. const char *zFile
  4632. ){
  4633. char *zCopy = sqlite3_mprintf("%s", zFile);
  4634. int rc = SQLITE_OK;
  4635. if( zCopy==0 ){
  4636. rc = SQLITE_NOMEM;
  4637. }else{
  4638. int nCopy = (int)strlen(zCopy);
  4639. int i = 1;
  4640. while( rc==SQLITE_OK ){
  4641. struct stat sStat;
  4642. int rc2;
  4643. for(; zCopy[i]!='/' && i<nCopy; i++);
  4644. if( i==nCopy ) break;
  4645. zCopy[i] = '\0';
  4646. rc2 = fileStat(zCopy, &sStat);
  4647. if( rc2!=0 ){
  4648. if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
  4649. }else{
  4650. if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
  4651. }
  4652. zCopy[i] = '/';
  4653. i++;
  4654. }
  4655. sqlite3_free(zCopy);
  4656. }
  4657. return rc;
  4658. }
  4659. /*
  4660. ** This function does the work for the writefile() UDF. Refer to
  4661. ** header comments at the top of this file for details.
  4662. */
  4663. static int writeFile(
  4664. sqlite3_context *pCtx, /* Context to return bytes written in */
  4665. const char *zFile, /* File to write */
  4666. sqlite3_value *pData, /* Data to write */
  4667. mode_t mode, /* MODE parameter passed to writefile() */
  4668. sqlite3_int64 mtime /* MTIME parameter (or -1 to not set time) */
  4669. ){
  4670. if( zFile==0 ) return 1;
  4671. #if !defined(_WIN32) && !defined(WIN32)
  4672. if( S_ISLNK(mode) ){
  4673. const char *zTo = (const char*)sqlite3_value_text(pData);
  4674. if( zTo==0 || symlink(zTo, zFile)<0 ) return 1;
  4675. }else
  4676. #endif
  4677. {
  4678. if( S_ISDIR(mode) ){
  4679. if( mkdir(zFile, mode) ){
  4680. /* The mkdir() call to create the directory failed. This might not
  4681. ** be an error though - if there is already a directory at the same
  4682. ** path and either the permissions already match or can be changed
  4683. ** to do so using chmod(), it is not an error. */
  4684. struct stat sStat;
  4685. if( errno!=EEXIST
  4686. || 0!=fileStat(zFile, &sStat)
  4687. || !S_ISDIR(sStat.st_mode)
  4688. || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
  4689. ){
  4690. return 1;
  4691. }
  4692. }
  4693. }else{
  4694. sqlite3_int64 nWrite = 0;
  4695. const char *z;
  4696. int rc = 0;
  4697. FILE *out = fopen(zFile, "wb");
  4698. if( out==0 ) return 1;
  4699. z = (const char*)sqlite3_value_blob(pData);
  4700. if( z ){
  4701. sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
  4702. nWrite = sqlite3_value_bytes(pData);
  4703. if( nWrite!=n ){
  4704. rc = 1;
  4705. }
  4706. }
  4707. fclose(out);
  4708. if( rc==0 && mode && chmod(zFile, mode & 0777) ){
  4709. rc = 1;
  4710. }
  4711. if( rc ) return 2;
  4712. sqlite3_result_int64(pCtx, nWrite);
  4713. }
  4714. }
  4715. if( mtime>=0 ){
  4716. #if defined(_WIN32)
  4717. #if !SQLITE_OS_WINRT
  4718. /* Windows */
  4719. FILETIME lastAccess;
  4720. FILETIME lastWrite;
  4721. SYSTEMTIME currentTime;
  4722. LONGLONG intervals;
  4723. HANDLE hFile;
  4724. LPWSTR zUnicodeName;
  4725. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
  4726. GetSystemTime(&currentTime);
  4727. SystemTimeToFileTime(&currentTime, &lastAccess);
  4728. intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
  4729. lastWrite.dwLowDateTime = (DWORD)intervals;
  4730. lastWrite.dwHighDateTime = intervals >> 32;
  4731. zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
  4732. if( zUnicodeName==0 ){
  4733. return 1;
  4734. }
  4735. hFile = CreateFileW(
  4736. zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
  4737. FILE_FLAG_BACKUP_SEMANTICS, NULL
  4738. );
  4739. sqlite3_free(zUnicodeName);
  4740. if( hFile!=INVALID_HANDLE_VALUE ){
  4741. BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
  4742. CloseHandle(hFile);
  4743. return !bResult;
  4744. }else{
  4745. return 1;
  4746. }
  4747. #endif
  4748. #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
  4749. /* Recent unix */
  4750. struct timespec times[2];
  4751. times[0].tv_nsec = times[1].tv_nsec = 0;
  4752. times[0].tv_sec = time(0);
  4753. times[1].tv_sec = mtime;
  4754. if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
  4755. return 1;
  4756. }
  4757. #else
  4758. /* Legacy unix */
  4759. struct timeval times[2];
  4760. times[0].tv_usec = times[1].tv_usec = 0;
  4761. times[0].tv_sec = time(0);
  4762. times[1].tv_sec = mtime;
  4763. if( utimes(zFile, times) ){
  4764. return 1;
  4765. }
  4766. #endif
  4767. }
  4768. return 0;
  4769. }
  4770. /*
  4771. ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
  4772. ** Refer to header comments at the top of this file for details.
  4773. */
  4774. static void writefileFunc(
  4775. sqlite3_context *context,
  4776. int argc,
  4777. sqlite3_value **argv
  4778. ){
  4779. const char *zFile;
  4780. mode_t mode = 0;
  4781. int res;
  4782. sqlite3_int64 mtime = -1;
  4783. if( argc<2 || argc>4 ){
  4784. sqlite3_result_error(context,
  4785. "wrong number of arguments to function writefile()", -1
  4786. );
  4787. return;
  4788. }
  4789. zFile = (const char*)sqlite3_value_text(argv[0]);
  4790. if( zFile==0 ) return;
  4791. if( argc>=3 ){
  4792. mode = (mode_t)sqlite3_value_int(argv[2]);
  4793. }
  4794. if( argc==4 ){
  4795. mtime = sqlite3_value_int64(argv[3]);
  4796. }
  4797. res = writeFile(context, zFile, argv[1], mode, mtime);
  4798. if( res==1 && errno==ENOENT ){
  4799. if( makeDirectory(zFile)==SQLITE_OK ){
  4800. res = writeFile(context, zFile, argv[1], mode, mtime);
  4801. }
  4802. }
  4803. if( argc>2 && res!=0 ){
  4804. if( S_ISLNK(mode) ){
  4805. ctxErrorMsg(context, "failed to create symlink: %s", zFile);
  4806. }else if( S_ISDIR(mode) ){
  4807. ctxErrorMsg(context, "failed to create directory: %s", zFile);
  4808. }else{
  4809. ctxErrorMsg(context, "failed to write file: %s", zFile);
  4810. }
  4811. }
  4812. }
  4813. /*
  4814. ** SQL function: lsmode(MODE)
  4815. **
  4816. ** Given a numberic st_mode from stat(), convert it into a human-readable
  4817. ** text string in the style of "ls -l".
  4818. */
  4819. static void lsModeFunc(
  4820. sqlite3_context *context,
  4821. int argc,
  4822. sqlite3_value **argv
  4823. ){
  4824. int i;
  4825. int iMode = sqlite3_value_int(argv[0]);
  4826. char z[16];
  4827. (void)argc;
  4828. if( S_ISLNK(iMode) ){
  4829. z[0] = 'l';
  4830. }else if( S_ISREG(iMode) ){
  4831. z[0] = '-';
  4832. }else if( S_ISDIR(iMode) ){
  4833. z[0] = 'd';
  4834. }else{
  4835. z[0] = '?';
  4836. }
  4837. for(i=0; i<3; i++){
  4838. int m = (iMode >> ((2-i)*3));
  4839. char *a = &z[1 + i*3];
  4840. a[0] = (m & 0x4) ? 'r' : '-';
  4841. a[1] = (m & 0x2) ? 'w' : '-';
  4842. a[2] = (m & 0x1) ? 'x' : '-';
  4843. }
  4844. z[10] = '\0';
  4845. sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
  4846. }
  4847. #ifndef SQLITE_OMIT_VIRTUALTABLE
  4848. /*
  4849. ** Cursor type for recursively iterating through a directory structure.
  4850. */
  4851. typedef struct fsdir_cursor fsdir_cursor;
  4852. typedef struct FsdirLevel FsdirLevel;
  4853. struct FsdirLevel {
  4854. DIR *pDir; /* From opendir() */
  4855. char *zDir; /* Name of directory (nul-terminated) */
  4856. };
  4857. struct fsdir_cursor {
  4858. sqlite3_vtab_cursor base; /* Base class - must be first */
  4859. int nLvl; /* Number of entries in aLvl[] array */
  4860. int iLvl; /* Index of current entry */
  4861. FsdirLevel *aLvl; /* Hierarchy of directories being traversed */
  4862. const char *zBase;
  4863. int nBase;
  4864. struct stat sStat; /* Current lstat() results */
  4865. char *zPath; /* Path to current entry */
  4866. sqlite3_int64 iRowid; /* Current rowid */
  4867. };
  4868. typedef struct fsdir_tab fsdir_tab;
  4869. struct fsdir_tab {
  4870. sqlite3_vtab base; /* Base class - must be first */
  4871. };
  4872. /*
  4873. ** Construct a new fsdir virtual table object.
  4874. */
  4875. static int fsdirConnect(
  4876. sqlite3 *db,
  4877. void *pAux,
  4878. int argc, const char *const*argv,
  4879. sqlite3_vtab **ppVtab,
  4880. char **pzErr
  4881. ){
  4882. fsdir_tab *pNew = 0;
  4883. int rc;
  4884. (void)pAux;
  4885. (void)argc;
  4886. (void)argv;
  4887. (void)pzErr;
  4888. rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
  4889. if( rc==SQLITE_OK ){
  4890. pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
  4891. if( pNew==0 ) return SQLITE_NOMEM;
  4892. memset(pNew, 0, sizeof(*pNew));
  4893. sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
  4894. }
  4895. *ppVtab = (sqlite3_vtab*)pNew;
  4896. return rc;
  4897. }
  4898. /*
  4899. ** This method is the destructor for fsdir vtab objects.
  4900. */
  4901. static int fsdirDisconnect(sqlite3_vtab *pVtab){
  4902. sqlite3_free(pVtab);
  4903. return SQLITE_OK;
  4904. }
  4905. /*
  4906. ** Constructor for a new fsdir_cursor object.
  4907. */
  4908. static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  4909. fsdir_cursor *pCur;
  4910. (void)p;
  4911. pCur = sqlite3_malloc( sizeof(*pCur) );
  4912. if( pCur==0 ) return SQLITE_NOMEM;
  4913. memset(pCur, 0, sizeof(*pCur));
  4914. pCur->iLvl = -1;
  4915. *ppCursor = &pCur->base;
  4916. return SQLITE_OK;
  4917. }
  4918. /*
  4919. ** Reset a cursor back to the state it was in when first returned
  4920. ** by fsdirOpen().
  4921. */
  4922. static void fsdirResetCursor(fsdir_cursor *pCur){
  4923. int i;
  4924. for(i=0; i<=pCur->iLvl; i++){
  4925. FsdirLevel *pLvl = &pCur->aLvl[i];
  4926. if( pLvl->pDir ) closedir(pLvl->pDir);
  4927. sqlite3_free(pLvl->zDir);
  4928. }
  4929. sqlite3_free(pCur->zPath);
  4930. sqlite3_free(pCur->aLvl);
  4931. pCur->aLvl = 0;
  4932. pCur->zPath = 0;
  4933. pCur->zBase = 0;
  4934. pCur->nBase = 0;
  4935. pCur->nLvl = 0;
  4936. pCur->iLvl = -1;
  4937. pCur->iRowid = 1;
  4938. }
  4939. /*
  4940. ** Destructor for an fsdir_cursor.
  4941. */
  4942. static int fsdirClose(sqlite3_vtab_cursor *cur){
  4943. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  4944. fsdirResetCursor(pCur);
  4945. sqlite3_free(pCur);
  4946. return SQLITE_OK;
  4947. }
  4948. /*
  4949. ** Set the error message for the virtual table associated with cursor
  4950. ** pCur to the results of vprintf(zFmt, ...).
  4951. */
  4952. static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
  4953. va_list ap;
  4954. va_start(ap, zFmt);
  4955. pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
  4956. va_end(ap);
  4957. }
  4958. /*
  4959. ** Advance an fsdir_cursor to its next row of output.
  4960. */
  4961. static int fsdirNext(sqlite3_vtab_cursor *cur){
  4962. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  4963. mode_t m = pCur->sStat.st_mode;
  4964. pCur->iRowid++;
  4965. if( S_ISDIR(m) ){
  4966. /* Descend into this directory */
  4967. int iNew = pCur->iLvl + 1;
  4968. FsdirLevel *pLvl;
  4969. if( iNew>=pCur->nLvl ){
  4970. int nNew = iNew+1;
  4971. sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
  4972. FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
  4973. if( aNew==0 ) return SQLITE_NOMEM;
  4974. memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
  4975. pCur->aLvl = aNew;
  4976. pCur->nLvl = nNew;
  4977. }
  4978. pCur->iLvl = iNew;
  4979. pLvl = &pCur->aLvl[iNew];
  4980. pLvl->zDir = pCur->zPath;
  4981. pCur->zPath = 0;
  4982. pLvl->pDir = opendir(pLvl->zDir);
  4983. if( pLvl->pDir==0 ){
  4984. fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
  4985. return SQLITE_ERROR;
  4986. }
  4987. }
  4988. while( pCur->iLvl>=0 ){
  4989. FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
  4990. struct dirent *pEntry = readdir(pLvl->pDir);
  4991. if( pEntry ){
  4992. if( pEntry->d_name[0]=='.' ){
  4993. if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
  4994. if( pEntry->d_name[1]=='\0' ) continue;
  4995. }
  4996. sqlite3_free(pCur->zPath);
  4997. pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
  4998. if( pCur->zPath==0 ) return SQLITE_NOMEM;
  4999. if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
  5000. fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
  5001. return SQLITE_ERROR;
  5002. }
  5003. return SQLITE_OK;
  5004. }
  5005. closedir(pLvl->pDir);
  5006. sqlite3_free(pLvl->zDir);
  5007. pLvl->pDir = 0;
  5008. pLvl->zDir = 0;
  5009. pCur->iLvl--;
  5010. }
  5011. /* EOF */
  5012. sqlite3_free(pCur->zPath);
  5013. pCur->zPath = 0;
  5014. return SQLITE_OK;
  5015. }
  5016. /*
  5017. ** Return values of columns for the row at which the series_cursor
  5018. ** is currently pointing.
  5019. */
  5020. static int fsdirColumn(
  5021. sqlite3_vtab_cursor *cur, /* The cursor */
  5022. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  5023. int i /* Which column to return */
  5024. ){
  5025. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  5026. switch( i ){
  5027. case FSDIR_COLUMN_NAME: {
  5028. sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
  5029. break;
  5030. }
  5031. case FSDIR_COLUMN_MODE:
  5032. sqlite3_result_int64(ctx, pCur->sStat.st_mode);
  5033. break;
  5034. case FSDIR_COLUMN_MTIME:
  5035. sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
  5036. break;
  5037. case FSDIR_COLUMN_DATA: {
  5038. mode_t m = pCur->sStat.st_mode;
  5039. if( S_ISDIR(m) ){
  5040. sqlite3_result_null(ctx);
  5041. #if !defined(_WIN32) && !defined(WIN32)
  5042. }else if( S_ISLNK(m) ){
  5043. char aStatic[64];
  5044. char *aBuf = aStatic;
  5045. sqlite3_int64 nBuf = 64;
  5046. int n;
  5047. while( 1 ){
  5048. n = readlink(pCur->zPath, aBuf, nBuf);
  5049. if( n<nBuf ) break;
  5050. if( aBuf!=aStatic ) sqlite3_free(aBuf);
  5051. nBuf = nBuf*2;
  5052. aBuf = sqlite3_malloc64(nBuf);
  5053. if( aBuf==0 ){
  5054. sqlite3_result_error_nomem(ctx);
  5055. return SQLITE_NOMEM;
  5056. }
  5057. }
  5058. sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
  5059. if( aBuf!=aStatic ) sqlite3_free(aBuf);
  5060. #endif
  5061. }else{
  5062. readFileContents(ctx, pCur->zPath);
  5063. }
  5064. }
  5065. case FSDIR_COLUMN_PATH:
  5066. default: {
  5067. /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
  5068. ** always return their values as NULL */
  5069. break;
  5070. }
  5071. }
  5072. return SQLITE_OK;
  5073. }
  5074. /*
  5075. ** Return the rowid for the current row. In this implementation, the
  5076. ** first row returned is assigned rowid value 1, and each subsequent
  5077. ** row a value 1 more than that of the previous.
  5078. */
  5079. static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  5080. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  5081. *pRowid = pCur->iRowid;
  5082. return SQLITE_OK;
  5083. }
  5084. /*
  5085. ** Return TRUE if the cursor has been moved off of the last
  5086. ** row of output.
  5087. */
  5088. static int fsdirEof(sqlite3_vtab_cursor *cur){
  5089. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  5090. return (pCur->zPath==0);
  5091. }
  5092. /*
  5093. ** xFilter callback.
  5094. **
  5095. ** idxNum==1 PATH parameter only
  5096. ** idxNum==2 Both PATH and DIR supplied
  5097. */
  5098. static int fsdirFilter(
  5099. sqlite3_vtab_cursor *cur,
  5100. int idxNum, const char *idxStr,
  5101. int argc, sqlite3_value **argv
  5102. ){
  5103. const char *zDir = 0;
  5104. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  5105. (void)idxStr;
  5106. fsdirResetCursor(pCur);
  5107. if( idxNum==0 ){
  5108. fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
  5109. return SQLITE_ERROR;
  5110. }
  5111. assert( argc==idxNum && (argc==1 || argc==2) );
  5112. zDir = (const char*)sqlite3_value_text(argv[0]);
  5113. if( zDir==0 ){
  5114. fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
  5115. return SQLITE_ERROR;
  5116. }
  5117. if( argc==2 ){
  5118. pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
  5119. }
  5120. if( pCur->zBase ){
  5121. pCur->nBase = (int)strlen(pCur->zBase)+1;
  5122. pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
  5123. }else{
  5124. pCur->zPath = sqlite3_mprintf("%s", zDir);
  5125. }
  5126. if( pCur->zPath==0 ){
  5127. return SQLITE_NOMEM;
  5128. }
  5129. if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
  5130. fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
  5131. return SQLITE_ERROR;
  5132. }
  5133. return SQLITE_OK;
  5134. }
  5135. /*
  5136. ** SQLite will invoke this method one or more times while planning a query
  5137. ** that uses the generate_series virtual table. This routine needs to create
  5138. ** a query plan for each invocation and compute an estimated cost for that
  5139. ** plan.
  5140. **
  5141. ** In this implementation idxNum is used to represent the
  5142. ** query plan. idxStr is unused.
  5143. **
  5144. ** The query plan is represented by values of idxNum:
  5145. **
  5146. ** (1) The path value is supplied by argv[0]
  5147. ** (2) Path is in argv[0] and dir is in argv[1]
  5148. */
  5149. static int fsdirBestIndex(
  5150. sqlite3_vtab *tab,
  5151. sqlite3_index_info *pIdxInfo
  5152. ){
  5153. int i; /* Loop over constraints */
  5154. int idxPath = -1; /* Index in pIdxInfo->aConstraint of PATH= */
  5155. int idxDir = -1; /* Index in pIdxInfo->aConstraint of DIR= */
  5156. int seenPath = 0; /* True if an unusable PATH= constraint is seen */
  5157. int seenDir = 0; /* True if an unusable DIR= constraint is seen */
  5158. const struct sqlite3_index_constraint *pConstraint;
  5159. (void)tab;
  5160. pConstraint = pIdxInfo->aConstraint;
  5161. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  5162. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  5163. switch( pConstraint->iColumn ){
  5164. case FSDIR_COLUMN_PATH: {
  5165. if( pConstraint->usable ){
  5166. idxPath = i;
  5167. seenPath = 0;
  5168. }else if( idxPath<0 ){
  5169. seenPath = 1;
  5170. }
  5171. break;
  5172. }
  5173. case FSDIR_COLUMN_DIR: {
  5174. if( pConstraint->usable ){
  5175. idxDir = i;
  5176. seenDir = 0;
  5177. }else if( idxDir<0 ){
  5178. seenDir = 1;
  5179. }
  5180. break;
  5181. }
  5182. }
  5183. }
  5184. if( seenPath || seenDir ){
  5185. /* If input parameters are unusable, disallow this plan */
  5186. return SQLITE_CONSTRAINT;
  5187. }
  5188. if( idxPath<0 ){
  5189. pIdxInfo->idxNum = 0;
  5190. /* The pIdxInfo->estimatedCost should have been initialized to a huge
  5191. ** number. Leave it unchanged. */
  5192. pIdxInfo->estimatedRows = 0x7fffffff;
  5193. }else{
  5194. pIdxInfo->aConstraintUsage[idxPath].omit = 1;
  5195. pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
  5196. if( idxDir>=0 ){
  5197. pIdxInfo->aConstraintUsage[idxDir].omit = 1;
  5198. pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
  5199. pIdxInfo->idxNum = 2;
  5200. pIdxInfo->estimatedCost = 10.0;
  5201. }else{
  5202. pIdxInfo->idxNum = 1;
  5203. pIdxInfo->estimatedCost = 100.0;
  5204. }
  5205. }
  5206. return SQLITE_OK;
  5207. }
  5208. /*
  5209. ** Register the "fsdir" virtual table.
  5210. */
  5211. static int fsdirRegister(sqlite3 *db){
  5212. static sqlite3_module fsdirModule = {
  5213. 0, /* iVersion */
  5214. 0, /* xCreate */
  5215. fsdirConnect, /* xConnect */
  5216. fsdirBestIndex, /* xBestIndex */
  5217. fsdirDisconnect, /* xDisconnect */
  5218. 0, /* xDestroy */
  5219. fsdirOpen, /* xOpen - open a cursor */
  5220. fsdirClose, /* xClose - close a cursor */
  5221. fsdirFilter, /* xFilter - configure scan constraints */
  5222. fsdirNext, /* xNext - advance a cursor */
  5223. fsdirEof, /* xEof - check for end of scan */
  5224. fsdirColumn, /* xColumn - read data */
  5225. fsdirRowid, /* xRowid - read data */
  5226. 0, /* xUpdate */
  5227. 0, /* xBegin */
  5228. 0, /* xSync */
  5229. 0, /* xCommit */
  5230. 0, /* xRollback */
  5231. 0, /* xFindMethod */
  5232. 0, /* xRename */
  5233. 0, /* xSavepoint */
  5234. 0, /* xRelease */
  5235. 0, /* xRollbackTo */
  5236. 0, /* xShadowName */
  5237. };
  5238. int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
  5239. return rc;
  5240. }
  5241. #else /* SQLITE_OMIT_VIRTUALTABLE */
  5242. # define fsdirRegister(x) SQLITE_OK
  5243. #endif
  5244. #ifdef _WIN32
  5245. #endif
  5246. int sqlite3_fileio_init(
  5247. sqlite3 *db,
  5248. char **pzErrMsg,
  5249. const sqlite3_api_routines *pApi
  5250. ){
  5251. int rc = SQLITE_OK;
  5252. SQLITE_EXTENSION_INIT2(pApi);
  5253. (void)pzErrMsg; /* Unused parameter */
  5254. rc = sqlite3_create_function(db, "readfile", 1,
  5255. SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
  5256. readfileFunc, 0, 0);
  5257. if( rc==SQLITE_OK ){
  5258. rc = sqlite3_create_function(db, "writefile", -1,
  5259. SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
  5260. writefileFunc, 0, 0);
  5261. }
  5262. if( rc==SQLITE_OK ){
  5263. rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
  5264. lsModeFunc, 0, 0);
  5265. }
  5266. if( rc==SQLITE_OK ){
  5267. rc = fsdirRegister(db);
  5268. }
  5269. return rc;
  5270. }
  5271. #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
  5272. /* To allow a standalone DLL, make test_windirent.c use the same
  5273. * redefined SQLite API calls as the above extension code does.
  5274. * Just pull in this .c to accomplish this. As a beneficial side
  5275. * effect, this extension becomes a single translation unit. */
  5276. # include "test_windirent.c"
  5277. #endif
  5278. /************************* End ../ext/misc/fileio.c ********************/
  5279. /************************* Begin ../ext/misc/completion.c ******************/
  5280. /*
  5281. ** 2017-07-10
  5282. **
  5283. ** The author disclaims copyright to this source code. In place of
  5284. ** a legal notice, here is a blessing:
  5285. **
  5286. ** May you do good and not evil.
  5287. ** May you find forgiveness for yourself and forgive others.
  5288. ** May you share freely, never taking more than you give.
  5289. **
  5290. *************************************************************************
  5291. **
  5292. ** This file implements an eponymous virtual table that returns suggested
  5293. ** completions for a partial SQL input.
  5294. **
  5295. ** Suggested usage:
  5296. **
  5297. ** SELECT DISTINCT candidate COLLATE nocase
  5298. ** FROM completion($prefix,$wholeline)
  5299. ** ORDER BY 1;
  5300. **
  5301. ** The two query parameters are optional. $prefix is the text of the
  5302. ** current word being typed and that is to be completed. $wholeline is
  5303. ** the complete input line, used for context.
  5304. **
  5305. ** The raw completion() table might return the same candidate multiple
  5306. ** times, for example if the same column name is used to two or more
  5307. ** tables. And the candidates are returned in an arbitrary order. Hence,
  5308. ** the DISTINCT and ORDER BY are recommended.
  5309. **
  5310. ** This virtual table operates at the speed of human typing, and so there
  5311. ** is no attempt to make it fast. Even a slow implementation will be much
  5312. ** faster than any human can type.
  5313. **
  5314. */
  5315. /* #include "sqlite3ext.h" */
  5316. SQLITE_EXTENSION_INIT1
  5317. #include <assert.h>
  5318. #include <string.h>
  5319. #include <ctype.h>
  5320. #ifndef SQLITE_OMIT_VIRTUALTABLE
  5321. /* completion_vtab is a subclass of sqlite3_vtab which will
  5322. ** serve as the underlying representation of a completion virtual table
  5323. */
  5324. typedef struct completion_vtab completion_vtab;
  5325. struct completion_vtab {
  5326. sqlite3_vtab base; /* Base class - must be first */
  5327. sqlite3 *db; /* Database connection for this completion vtab */
  5328. };
  5329. /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
  5330. ** serve as the underlying representation of a cursor that scans
  5331. ** over rows of the result
  5332. */
  5333. typedef struct completion_cursor completion_cursor;
  5334. struct completion_cursor {
  5335. sqlite3_vtab_cursor base; /* Base class - must be first */
  5336. sqlite3 *db; /* Database connection for this cursor */
  5337. int nPrefix, nLine; /* Number of bytes in zPrefix and zLine */
  5338. char *zPrefix; /* The prefix for the word we want to complete */
  5339. char *zLine; /* The whole that we want to complete */
  5340. const char *zCurrentRow; /* Current output row */
  5341. int szRow; /* Length of the zCurrentRow string */
  5342. sqlite3_stmt *pStmt; /* Current statement */
  5343. sqlite3_int64 iRowid; /* The rowid */
  5344. int ePhase; /* Current phase */
  5345. int j; /* inter-phase counter */
  5346. };
  5347. /* Values for ePhase:
  5348. */
  5349. #define COMPLETION_FIRST_PHASE 1
  5350. #define COMPLETION_KEYWORDS 1
  5351. #define COMPLETION_PRAGMAS 2
  5352. #define COMPLETION_FUNCTIONS 3
  5353. #define COMPLETION_COLLATIONS 4
  5354. #define COMPLETION_INDEXES 5
  5355. #define COMPLETION_TRIGGERS 6
  5356. #define COMPLETION_DATABASES 7
  5357. #define COMPLETION_TABLES 8 /* Also VIEWs and TRIGGERs */
  5358. #define COMPLETION_COLUMNS 9
  5359. #define COMPLETION_MODULES 10
  5360. #define COMPLETION_EOF 11
  5361. /*
  5362. ** The completionConnect() method is invoked to create a new
  5363. ** completion_vtab that describes the completion virtual table.
  5364. **
  5365. ** Think of this routine as the constructor for completion_vtab objects.
  5366. **
  5367. ** All this routine needs to do is:
  5368. **
  5369. ** (1) Allocate the completion_vtab object and initialize all fields.
  5370. **
  5371. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  5372. ** result set of queries against completion will look like.
  5373. */
  5374. static int completionConnect(
  5375. sqlite3 *db,
  5376. void *pAux,
  5377. int argc, const char *const*argv,
  5378. sqlite3_vtab **ppVtab,
  5379. char **pzErr
  5380. ){
  5381. completion_vtab *pNew;
  5382. int rc;
  5383. (void)(pAux); /* Unused parameter */
  5384. (void)(argc); /* Unused parameter */
  5385. (void)(argv); /* Unused parameter */
  5386. (void)(pzErr); /* Unused parameter */
  5387. /* Column numbers */
  5388. #define COMPLETION_COLUMN_CANDIDATE 0 /* Suggested completion of the input */
  5389. #define COMPLETION_COLUMN_PREFIX 1 /* Prefix of the word to be completed */
  5390. #define COMPLETION_COLUMN_WHOLELINE 2 /* Entire line seen so far */
  5391. #define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */
  5392. sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
  5393. rc = sqlite3_declare_vtab(db,
  5394. "CREATE TABLE x("
  5395. " candidate TEXT,"
  5396. " prefix TEXT HIDDEN,"
  5397. " wholeline TEXT HIDDEN,"
  5398. " phase INT HIDDEN" /* Used for debugging only */
  5399. ")");
  5400. if( rc==SQLITE_OK ){
  5401. pNew = sqlite3_malloc( sizeof(*pNew) );
  5402. *ppVtab = (sqlite3_vtab*)pNew;
  5403. if( pNew==0 ) return SQLITE_NOMEM;
  5404. memset(pNew, 0, sizeof(*pNew));
  5405. pNew->db = db;
  5406. }
  5407. return rc;
  5408. }
  5409. /*
  5410. ** This method is the destructor for completion_cursor objects.
  5411. */
  5412. static int completionDisconnect(sqlite3_vtab *pVtab){
  5413. sqlite3_free(pVtab);
  5414. return SQLITE_OK;
  5415. }
  5416. /*
  5417. ** Constructor for a new completion_cursor object.
  5418. */
  5419. static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  5420. completion_cursor *pCur;
  5421. pCur = sqlite3_malloc( sizeof(*pCur) );
  5422. if( pCur==0 ) return SQLITE_NOMEM;
  5423. memset(pCur, 0, sizeof(*pCur));
  5424. pCur->db = ((completion_vtab*)p)->db;
  5425. *ppCursor = &pCur->base;
  5426. return SQLITE_OK;
  5427. }
  5428. /*
  5429. ** Reset the completion_cursor.
  5430. */
  5431. static void completionCursorReset(completion_cursor *pCur){
  5432. sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0;
  5433. sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0;
  5434. sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
  5435. pCur->j = 0;
  5436. }
  5437. /*
  5438. ** Destructor for a completion_cursor.
  5439. */
  5440. static int completionClose(sqlite3_vtab_cursor *cur){
  5441. completionCursorReset((completion_cursor*)cur);
  5442. sqlite3_free(cur);
  5443. return SQLITE_OK;
  5444. }
  5445. /*
  5446. ** Advance a completion_cursor to its next row of output.
  5447. **
  5448. ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
  5449. ** record the current state of the scan. This routine sets ->zCurrentRow
  5450. ** to the current row of output and then returns. If no more rows remain,
  5451. ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
  5452. ** table that has reached the end of its scan.
  5453. **
  5454. ** The current implementation just lists potential identifiers and
  5455. ** keywords and filters them by zPrefix. Future enhancements should
  5456. ** take zLine into account to try to restrict the set of identifiers and
  5457. ** keywords based on what would be legal at the current point of input.
  5458. */
  5459. static int completionNext(sqlite3_vtab_cursor *cur){
  5460. completion_cursor *pCur = (completion_cursor*)cur;
  5461. int eNextPhase = 0; /* Next phase to try if current phase reaches end */
  5462. int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */
  5463. pCur->iRowid++;
  5464. while( pCur->ePhase!=COMPLETION_EOF ){
  5465. switch( pCur->ePhase ){
  5466. case COMPLETION_KEYWORDS: {
  5467. if( pCur->j >= sqlite3_keyword_count() ){
  5468. pCur->zCurrentRow = 0;
  5469. pCur->ePhase = COMPLETION_DATABASES;
  5470. }else{
  5471. sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
  5472. }
  5473. iCol = -1;
  5474. break;
  5475. }
  5476. case COMPLETION_DATABASES: {
  5477. if( pCur->pStmt==0 ){
  5478. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
  5479. &pCur->pStmt, 0);
  5480. }
  5481. iCol = 1;
  5482. eNextPhase = COMPLETION_TABLES;
  5483. break;
  5484. }
  5485. case COMPLETION_TABLES: {
  5486. if( pCur->pStmt==0 ){
  5487. sqlite3_stmt *pS2;
  5488. char *zSql = 0;
  5489. const char *zSep = "";
  5490. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
  5491. while( sqlite3_step(pS2)==SQLITE_ROW ){
  5492. const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
  5493. zSql = sqlite3_mprintf(
  5494. "%z%s"
  5495. "SELECT name FROM \"%w\".sqlite_schema",
  5496. zSql, zSep, zDb
  5497. );
  5498. if( zSql==0 ) return SQLITE_NOMEM;
  5499. zSep = " UNION ";
  5500. }
  5501. sqlite3_finalize(pS2);
  5502. sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
  5503. sqlite3_free(zSql);
  5504. }
  5505. iCol = 0;
  5506. eNextPhase = COMPLETION_COLUMNS;
  5507. break;
  5508. }
  5509. case COMPLETION_COLUMNS: {
  5510. if( pCur->pStmt==0 ){
  5511. sqlite3_stmt *pS2;
  5512. char *zSql = 0;
  5513. const char *zSep = "";
  5514. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
  5515. while( sqlite3_step(pS2)==SQLITE_ROW ){
  5516. const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
  5517. zSql = sqlite3_mprintf(
  5518. "%z%s"
  5519. "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
  5520. " JOIN pragma_table_info(sm.name,%Q) AS pti"
  5521. " WHERE sm.type='table'",
  5522. zSql, zSep, zDb, zDb
  5523. );
  5524. if( zSql==0 ) return SQLITE_NOMEM;
  5525. zSep = " UNION ";
  5526. }
  5527. sqlite3_finalize(pS2);
  5528. sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
  5529. sqlite3_free(zSql);
  5530. }
  5531. iCol = 0;
  5532. eNextPhase = COMPLETION_EOF;
  5533. break;
  5534. }
  5535. }
  5536. if( iCol<0 ){
  5537. /* This case is when the phase presets zCurrentRow */
  5538. if( pCur->zCurrentRow==0 ) continue;
  5539. }else{
  5540. if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
  5541. /* Extract the next row of content */
  5542. pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
  5543. pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
  5544. }else{
  5545. /* When all rows are finished, advance to the next phase */
  5546. sqlite3_finalize(pCur->pStmt);
  5547. pCur->pStmt = 0;
  5548. pCur->ePhase = eNextPhase;
  5549. continue;
  5550. }
  5551. }
  5552. if( pCur->nPrefix==0 ) break;
  5553. if( pCur->nPrefix<=pCur->szRow
  5554. && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
  5555. ){
  5556. break;
  5557. }
  5558. }
  5559. return SQLITE_OK;
  5560. }
  5561. /*
  5562. ** Return values of columns for the row at which the completion_cursor
  5563. ** is currently pointing.
  5564. */
  5565. static int completionColumn(
  5566. sqlite3_vtab_cursor *cur, /* The cursor */
  5567. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  5568. int i /* Which column to return */
  5569. ){
  5570. completion_cursor *pCur = (completion_cursor*)cur;
  5571. switch( i ){
  5572. case COMPLETION_COLUMN_CANDIDATE: {
  5573. sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
  5574. break;
  5575. }
  5576. case COMPLETION_COLUMN_PREFIX: {
  5577. sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
  5578. break;
  5579. }
  5580. case COMPLETION_COLUMN_WHOLELINE: {
  5581. sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
  5582. break;
  5583. }
  5584. case COMPLETION_COLUMN_PHASE: {
  5585. sqlite3_result_int(ctx, pCur->ePhase);
  5586. break;
  5587. }
  5588. }
  5589. return SQLITE_OK;
  5590. }
  5591. /*
  5592. ** Return the rowid for the current row. In this implementation, the
  5593. ** rowid is the same as the output value.
  5594. */
  5595. static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  5596. completion_cursor *pCur = (completion_cursor*)cur;
  5597. *pRowid = pCur->iRowid;
  5598. return SQLITE_OK;
  5599. }
  5600. /*
  5601. ** Return TRUE if the cursor has been moved off of the last
  5602. ** row of output.
  5603. */
  5604. static int completionEof(sqlite3_vtab_cursor *cur){
  5605. completion_cursor *pCur = (completion_cursor*)cur;
  5606. return pCur->ePhase >= COMPLETION_EOF;
  5607. }
  5608. /*
  5609. ** This method is called to "rewind" the completion_cursor object back
  5610. ** to the first row of output. This method is always called at least
  5611. ** once prior to any call to completionColumn() or completionRowid() or
  5612. ** completionEof().
  5613. */
  5614. static int completionFilter(
  5615. sqlite3_vtab_cursor *pVtabCursor,
  5616. int idxNum, const char *idxStr,
  5617. int argc, sqlite3_value **argv
  5618. ){
  5619. completion_cursor *pCur = (completion_cursor *)pVtabCursor;
  5620. int iArg = 0;
  5621. (void)(idxStr); /* Unused parameter */
  5622. (void)(argc); /* Unused parameter */
  5623. completionCursorReset(pCur);
  5624. if( idxNum & 1 ){
  5625. pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
  5626. if( pCur->nPrefix>0 ){
  5627. pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
  5628. if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
  5629. }
  5630. iArg = 1;
  5631. }
  5632. if( idxNum & 2 ){
  5633. pCur->nLine = sqlite3_value_bytes(argv[iArg]);
  5634. if( pCur->nLine>0 ){
  5635. pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
  5636. if( pCur->zLine==0 ) return SQLITE_NOMEM;
  5637. }
  5638. }
  5639. if( pCur->zLine!=0 && pCur->zPrefix==0 ){
  5640. int i = pCur->nLine;
  5641. while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
  5642. i--;
  5643. }
  5644. pCur->nPrefix = pCur->nLine - i;
  5645. if( pCur->nPrefix>0 ){
  5646. pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
  5647. if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
  5648. }
  5649. }
  5650. pCur->iRowid = 0;
  5651. pCur->ePhase = COMPLETION_FIRST_PHASE;
  5652. return completionNext(pVtabCursor);
  5653. }
  5654. /*
  5655. ** SQLite will invoke this method one or more times while planning a query
  5656. ** that uses the completion virtual table. This routine needs to create
  5657. ** a query plan for each invocation and compute an estimated cost for that
  5658. ** plan.
  5659. **
  5660. ** There are two hidden parameters that act as arguments to the table-valued
  5661. ** function: "prefix" and "wholeline". Bit 0 of idxNum is set if "prefix"
  5662. ** is available and bit 1 is set if "wholeline" is available.
  5663. */
  5664. static int completionBestIndex(
  5665. sqlite3_vtab *tab,
  5666. sqlite3_index_info *pIdxInfo
  5667. ){
  5668. int i; /* Loop over constraints */
  5669. int idxNum = 0; /* The query plan bitmask */
  5670. int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */
  5671. int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
  5672. int nArg = 0; /* Number of arguments that completeFilter() expects */
  5673. const struct sqlite3_index_constraint *pConstraint;
  5674. (void)(tab); /* Unused parameter */
  5675. pConstraint = pIdxInfo->aConstraint;
  5676. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  5677. if( pConstraint->usable==0 ) continue;
  5678. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  5679. switch( pConstraint->iColumn ){
  5680. case COMPLETION_COLUMN_PREFIX:
  5681. prefixIdx = i;
  5682. idxNum |= 1;
  5683. break;
  5684. case COMPLETION_COLUMN_WHOLELINE:
  5685. wholelineIdx = i;
  5686. idxNum |= 2;
  5687. break;
  5688. }
  5689. }
  5690. if( prefixIdx>=0 ){
  5691. pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
  5692. pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
  5693. }
  5694. if( wholelineIdx>=0 ){
  5695. pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
  5696. pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
  5697. }
  5698. pIdxInfo->idxNum = idxNum;
  5699. pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
  5700. pIdxInfo->estimatedRows = 500 - 100*nArg;
  5701. return SQLITE_OK;
  5702. }
  5703. /*
  5704. ** This following structure defines all the methods for the
  5705. ** completion virtual table.
  5706. */
  5707. static sqlite3_module completionModule = {
  5708. 0, /* iVersion */
  5709. 0, /* xCreate */
  5710. completionConnect, /* xConnect */
  5711. completionBestIndex, /* xBestIndex */
  5712. completionDisconnect, /* xDisconnect */
  5713. 0, /* xDestroy */
  5714. completionOpen, /* xOpen - open a cursor */
  5715. completionClose, /* xClose - close a cursor */
  5716. completionFilter, /* xFilter - configure scan constraints */
  5717. completionNext, /* xNext - advance a cursor */
  5718. completionEof, /* xEof - check for end of scan */
  5719. completionColumn, /* xColumn - read data */
  5720. completionRowid, /* xRowid - read data */
  5721. 0, /* xUpdate */
  5722. 0, /* xBegin */
  5723. 0, /* xSync */
  5724. 0, /* xCommit */
  5725. 0, /* xRollback */
  5726. 0, /* xFindMethod */
  5727. 0, /* xRename */
  5728. 0, /* xSavepoint */
  5729. 0, /* xRelease */
  5730. 0, /* xRollbackTo */
  5731. 0 /* xShadowName */
  5732. };
  5733. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  5734. int sqlite3CompletionVtabInit(sqlite3 *db){
  5735. int rc = SQLITE_OK;
  5736. #ifndef SQLITE_OMIT_VIRTUALTABLE
  5737. rc = sqlite3_create_module(db, "completion", &completionModule, 0);
  5738. #endif
  5739. return rc;
  5740. }
  5741. #ifdef _WIN32
  5742. #endif
  5743. int sqlite3_completion_init(
  5744. sqlite3 *db,
  5745. char **pzErrMsg,
  5746. const sqlite3_api_routines *pApi
  5747. ){
  5748. int rc = SQLITE_OK;
  5749. SQLITE_EXTENSION_INIT2(pApi);
  5750. (void)(pzErrMsg); /* Unused parameter */
  5751. #ifndef SQLITE_OMIT_VIRTUALTABLE
  5752. rc = sqlite3CompletionVtabInit(db);
  5753. #endif
  5754. return rc;
  5755. }
  5756. /************************* End ../ext/misc/completion.c ********************/
  5757. /************************* Begin ../ext/misc/appendvfs.c ******************/
  5758. /*
  5759. ** 2017-10-20
  5760. **
  5761. ** The author disclaims copyright to this source code. In place of
  5762. ** a legal notice, here is a blessing:
  5763. **
  5764. ** May you do good and not evil.
  5765. ** May you find forgiveness for yourself and forgive others.
  5766. ** May you share freely, never taking more than you give.
  5767. **
  5768. ******************************************************************************
  5769. **
  5770. ** This file implements a VFS shim that allows an SQLite database to be
  5771. ** appended onto the end of some other file, such as an executable.
  5772. **
  5773. ** A special record must appear at the end of the file that identifies the
  5774. ** file as an appended database and provides the offset to the first page
  5775. ** of the exposed content. (Or, it is the length of the content prefix.)
  5776. ** For best performance page 1 should be located at a disk page boundary,
  5777. ** though that is not required.
  5778. **
  5779. ** When opening a database using this VFS, the connection might treat
  5780. ** the file as an ordinary SQLite database, or it might treat it as a
  5781. ** database appended onto some other file. The decision is made by
  5782. ** applying the following rules in order:
  5783. **
  5784. ** (1) An empty file is an ordinary database.
  5785. **
  5786. ** (2) If the file ends with the appendvfs trailer string
  5787. ** "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
  5788. **
  5789. ** (3) If the file begins with the standard SQLite prefix string
  5790. ** "SQLite format 3", that file is an ordinary database.
  5791. **
  5792. ** (4) If none of the above apply and the SQLITE_OPEN_CREATE flag is
  5793. ** set, then a new database is appended to the already existing file.
  5794. **
  5795. ** (5) Otherwise, SQLITE_CANTOPEN is returned.
  5796. **
  5797. ** To avoid unnecessary complications with the PENDING_BYTE, the size of
  5798. ** the file containing the database is limited to 1GiB. (1073741824 bytes)
  5799. ** This VFS will not read or write past the 1GiB mark. This restriction
  5800. ** might be lifted in future versions. For now, if you need a larger
  5801. ** database, then keep it in a separate file.
  5802. **
  5803. ** If the file being opened is a plain database (not an appended one), then
  5804. ** this shim is a pass-through into the default underlying VFS. (rule 3)
  5805. **/
  5806. /* #include "sqlite3ext.h" */
  5807. SQLITE_EXTENSION_INIT1
  5808. #include <string.h>
  5809. #include <assert.h>
  5810. /* The append mark at the end of the database is:
  5811. **
  5812. ** Start-Of-SQLite3-NNNNNNNN
  5813. ** 123456789 123456789 12345
  5814. **
  5815. ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
  5816. ** the offset to page 1, and also the length of the prefix content.
  5817. */
  5818. #define APND_MARK_PREFIX "Start-Of-SQLite3-"
  5819. #define APND_MARK_PREFIX_SZ 17
  5820. #define APND_MARK_FOS_SZ 8
  5821. #define APND_MARK_SIZE (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
  5822. /*
  5823. ** Maximum size of the combined prefix + database + append-mark. This
  5824. ** must be less than 0x40000000 to avoid locking issues on Windows.
  5825. */
  5826. #define APND_MAX_SIZE (0x40000000)
  5827. /*
  5828. ** Try to align the database to an even multiple of APND_ROUNDUP bytes.
  5829. */
  5830. #ifndef APND_ROUNDUP
  5831. #define APND_ROUNDUP 4096
  5832. #endif
  5833. #define APND_ALIGN_MASK ((sqlite3_int64)(APND_ROUNDUP-1))
  5834. #define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
  5835. /*
  5836. ** Forward declaration of objects used by this utility
  5837. */
  5838. typedef struct sqlite3_vfs ApndVfs;
  5839. typedef struct ApndFile ApndFile;
  5840. /* Access to a lower-level VFS that (might) implement dynamic loading,
  5841. ** access to randomness, etc.
  5842. */
  5843. #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
  5844. #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
  5845. /* An open appendvfs file
  5846. **
  5847. ** An instance of this structure describes the appended database file.
  5848. ** A separate sqlite3_file object is always appended. The appended
  5849. ** sqlite3_file object (which can be accessed using ORIGFILE()) describes
  5850. ** the entire file, including the prefix, the database, and the
  5851. ** append-mark.
  5852. **
  5853. ** The structure of an AppendVFS database is like this:
  5854. **
  5855. ** +-------------+---------+----------+-------------+
  5856. ** | prefix-file | padding | database | append-mark |
  5857. ** +-------------+---------+----------+-------------+
  5858. ** ^ ^
  5859. ** | |
  5860. ** iPgOne iMark
  5861. **
  5862. **
  5863. ** "prefix file" - file onto which the database has been appended.
  5864. ** "padding" - zero or more bytes inserted so that "database"
  5865. ** starts on an APND_ROUNDUP boundary
  5866. ** "database" - The SQLite database file
  5867. ** "append-mark" - The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
  5868. ** the offset from the start of prefix-file to the start
  5869. ** of "database".
  5870. **
  5871. ** The size of the database is iMark - iPgOne.
  5872. **
  5873. ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
  5874. ** of iPgOne stored as a big-ending 64-bit integer.
  5875. **
  5876. ** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
  5877. ** Or, iMark is -1 to indicate that it has not yet been written.
  5878. */
  5879. struct ApndFile {
  5880. sqlite3_file base; /* Subclass. MUST BE FIRST! */
  5881. sqlite3_int64 iPgOne; /* Offset to the start of the database */
  5882. sqlite3_int64 iMark; /* Offset of the append mark. -1 if unwritten */
  5883. /* Always followed by another sqlite3_file that describes the whole file */
  5884. };
  5885. /*
  5886. ** Methods for ApndFile
  5887. */
  5888. static int apndClose(sqlite3_file*);
  5889. static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  5890. static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
  5891. static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
  5892. static int apndSync(sqlite3_file*, int flags);
  5893. static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
  5894. static int apndLock(sqlite3_file*, int);
  5895. static int apndUnlock(sqlite3_file*, int);
  5896. static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
  5897. static int apndFileControl(sqlite3_file*, int op, void *pArg);
  5898. static int apndSectorSize(sqlite3_file*);
  5899. static int apndDeviceCharacteristics(sqlite3_file*);
  5900. static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  5901. static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
  5902. static void apndShmBarrier(sqlite3_file*);
  5903. static int apndShmUnmap(sqlite3_file*, int deleteFlag);
  5904. static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  5905. static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  5906. /*
  5907. ** Methods for ApndVfs
  5908. */
  5909. static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
  5910. static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
  5911. static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
  5912. static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
  5913. static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
  5914. static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
  5915. static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
  5916. static void apndDlClose(sqlite3_vfs*, void*);
  5917. static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
  5918. static int apndSleep(sqlite3_vfs*, int microseconds);
  5919. static int apndCurrentTime(sqlite3_vfs*, double*);
  5920. static int apndGetLastError(sqlite3_vfs*, int, char *);
  5921. static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
  5922. static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
  5923. static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
  5924. static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
  5925. static sqlite3_vfs apnd_vfs = {
  5926. 3, /* iVersion (set when registered) */
  5927. 0, /* szOsFile (set when registered) */
  5928. 1024, /* mxPathname */
  5929. 0, /* pNext */
  5930. "apndvfs", /* zName */
  5931. 0, /* pAppData (set when registered) */
  5932. apndOpen, /* xOpen */
  5933. apndDelete, /* xDelete */
  5934. apndAccess, /* xAccess */
  5935. apndFullPathname, /* xFullPathname */
  5936. apndDlOpen, /* xDlOpen */
  5937. apndDlError, /* xDlError */
  5938. apndDlSym, /* xDlSym */
  5939. apndDlClose, /* xDlClose */
  5940. apndRandomness, /* xRandomness */
  5941. apndSleep, /* xSleep */
  5942. apndCurrentTime, /* xCurrentTime */
  5943. apndGetLastError, /* xGetLastError */
  5944. apndCurrentTimeInt64, /* xCurrentTimeInt64 */
  5945. apndSetSystemCall, /* xSetSystemCall */
  5946. apndGetSystemCall, /* xGetSystemCall */
  5947. apndNextSystemCall /* xNextSystemCall */
  5948. };
  5949. static const sqlite3_io_methods apnd_io_methods = {
  5950. 3, /* iVersion */
  5951. apndClose, /* xClose */
  5952. apndRead, /* xRead */
  5953. apndWrite, /* xWrite */
  5954. apndTruncate, /* xTruncate */
  5955. apndSync, /* xSync */
  5956. apndFileSize, /* xFileSize */
  5957. apndLock, /* xLock */
  5958. apndUnlock, /* xUnlock */
  5959. apndCheckReservedLock, /* xCheckReservedLock */
  5960. apndFileControl, /* xFileControl */
  5961. apndSectorSize, /* xSectorSize */
  5962. apndDeviceCharacteristics, /* xDeviceCharacteristics */
  5963. apndShmMap, /* xShmMap */
  5964. apndShmLock, /* xShmLock */
  5965. apndShmBarrier, /* xShmBarrier */
  5966. apndShmUnmap, /* xShmUnmap */
  5967. apndFetch, /* xFetch */
  5968. apndUnfetch /* xUnfetch */
  5969. };
  5970. /*
  5971. ** Close an apnd-file.
  5972. */
  5973. static int apndClose(sqlite3_file *pFile){
  5974. pFile = ORIGFILE(pFile);
  5975. return pFile->pMethods->xClose(pFile);
  5976. }
  5977. /*
  5978. ** Read data from an apnd-file.
  5979. */
  5980. static int apndRead(
  5981. sqlite3_file *pFile,
  5982. void *zBuf,
  5983. int iAmt,
  5984. sqlite_int64 iOfst
  5985. ){
  5986. ApndFile *paf = (ApndFile *)pFile;
  5987. pFile = ORIGFILE(pFile);
  5988. return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
  5989. }
  5990. /*
  5991. ** Add the append-mark onto what should become the end of the file.
  5992. * If and only if this succeeds, internal ApndFile.iMark is updated.
  5993. * Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
  5994. */
  5995. static int apndWriteMark(
  5996. ApndFile *paf,
  5997. sqlite3_file *pFile,
  5998. sqlite_int64 iWriteEnd
  5999. ){
  6000. sqlite_int64 iPgOne = paf->iPgOne;
  6001. unsigned char a[APND_MARK_SIZE];
  6002. int i = APND_MARK_FOS_SZ;
  6003. int rc;
  6004. assert(pFile == ORIGFILE(paf));
  6005. memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
  6006. while( --i >= 0 ){
  6007. a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
  6008. iPgOne >>= 8;
  6009. }
  6010. iWriteEnd += paf->iPgOne;
  6011. if( SQLITE_OK==(rc = pFile->pMethods->xWrite
  6012. (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
  6013. paf->iMark = iWriteEnd;
  6014. }
  6015. return rc;
  6016. }
  6017. /*
  6018. ** Write data to an apnd-file.
  6019. */
  6020. static int apndWrite(
  6021. sqlite3_file *pFile,
  6022. const void *zBuf,
  6023. int iAmt,
  6024. sqlite_int64 iOfst
  6025. ){
  6026. ApndFile *paf = (ApndFile *)pFile;
  6027. sqlite_int64 iWriteEnd = iOfst + iAmt;
  6028. if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
  6029. pFile = ORIGFILE(pFile);
  6030. /* If append-mark is absent or will be overwritten, write it. */
  6031. if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
  6032. int rc = apndWriteMark(paf, pFile, iWriteEnd);
  6033. if( SQLITE_OK!=rc ) return rc;
  6034. }
  6035. return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
  6036. }
  6037. /*
  6038. ** Truncate an apnd-file.
  6039. */
  6040. static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
  6041. ApndFile *paf = (ApndFile *)pFile;
  6042. pFile = ORIGFILE(pFile);
  6043. /* The append mark goes out first so truncate failure does not lose it. */
  6044. if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
  6045. /* Truncate underlying file just past append mark */
  6046. return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
  6047. }
  6048. /*
  6049. ** Sync an apnd-file.
  6050. */
  6051. static int apndSync(sqlite3_file *pFile, int flags){
  6052. pFile = ORIGFILE(pFile);
  6053. return pFile->pMethods->xSync(pFile, flags);
  6054. }
  6055. /*
  6056. ** Return the current file-size of an apnd-file.
  6057. ** If the append mark is not yet there, the file-size is 0.
  6058. */
  6059. static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  6060. ApndFile *paf = (ApndFile *)pFile;
  6061. *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
  6062. return SQLITE_OK;
  6063. }
  6064. /*
  6065. ** Lock an apnd-file.
  6066. */
  6067. static int apndLock(sqlite3_file *pFile, int eLock){
  6068. pFile = ORIGFILE(pFile);
  6069. return pFile->pMethods->xLock(pFile, eLock);
  6070. }
  6071. /*
  6072. ** Unlock an apnd-file.
  6073. */
  6074. static int apndUnlock(sqlite3_file *pFile, int eLock){
  6075. pFile = ORIGFILE(pFile);
  6076. return pFile->pMethods->xUnlock(pFile, eLock);
  6077. }
  6078. /*
  6079. ** Check if another file-handle holds a RESERVED lock on an apnd-file.
  6080. */
  6081. static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  6082. pFile = ORIGFILE(pFile);
  6083. return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
  6084. }
  6085. /*
  6086. ** File control method. For custom operations on an apnd-file.
  6087. */
  6088. static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
  6089. ApndFile *paf = (ApndFile *)pFile;
  6090. int rc;
  6091. pFile = ORIGFILE(pFile);
  6092. if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
  6093. rc = pFile->pMethods->xFileControl(pFile, op, pArg);
  6094. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  6095. *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
  6096. }
  6097. return rc;
  6098. }
  6099. /*
  6100. ** Return the sector-size in bytes for an apnd-file.
  6101. */
  6102. static int apndSectorSize(sqlite3_file *pFile){
  6103. pFile = ORIGFILE(pFile);
  6104. return pFile->pMethods->xSectorSize(pFile);
  6105. }
  6106. /*
  6107. ** Return the device characteristic flags supported by an apnd-file.
  6108. */
  6109. static int apndDeviceCharacteristics(sqlite3_file *pFile){
  6110. pFile = ORIGFILE(pFile);
  6111. return pFile->pMethods->xDeviceCharacteristics(pFile);
  6112. }
  6113. /* Create a shared memory file mapping */
  6114. static int apndShmMap(
  6115. sqlite3_file *pFile,
  6116. int iPg,
  6117. int pgsz,
  6118. int bExtend,
  6119. void volatile **pp
  6120. ){
  6121. pFile = ORIGFILE(pFile);
  6122. return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
  6123. }
  6124. /* Perform locking on a shared-memory segment */
  6125. static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
  6126. pFile = ORIGFILE(pFile);
  6127. return pFile->pMethods->xShmLock(pFile,offset,n,flags);
  6128. }
  6129. /* Memory barrier operation on shared memory */
  6130. static void apndShmBarrier(sqlite3_file *pFile){
  6131. pFile = ORIGFILE(pFile);
  6132. pFile->pMethods->xShmBarrier(pFile);
  6133. }
  6134. /* Unmap a shared memory segment */
  6135. static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
  6136. pFile = ORIGFILE(pFile);
  6137. return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
  6138. }
  6139. /* Fetch a page of a memory-mapped file */
  6140. static int apndFetch(
  6141. sqlite3_file *pFile,
  6142. sqlite3_int64 iOfst,
  6143. int iAmt,
  6144. void **pp
  6145. ){
  6146. ApndFile *p = (ApndFile *)pFile;
  6147. if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
  6148. return SQLITE_IOERR; /* Cannot read what is not yet there. */
  6149. }
  6150. pFile = ORIGFILE(pFile);
  6151. return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
  6152. }
  6153. /* Release a memory-mapped page */
  6154. static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
  6155. ApndFile *p = (ApndFile *)pFile;
  6156. pFile = ORIGFILE(pFile);
  6157. return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
  6158. }
  6159. /*
  6160. ** Try to read the append-mark off the end of a file. Return the
  6161. ** start of the appended database if the append-mark is present.
  6162. ** If there is no valid append-mark, return -1;
  6163. **
  6164. ** An append-mark is only valid if the NNNNNNNN start-of-database offset
  6165. ** indicates that the appended database contains at least one page. The
  6166. ** start-of-database value must be a multiple of 512.
  6167. */
  6168. static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
  6169. int rc, i;
  6170. sqlite3_int64 iMark;
  6171. int msbs = 8 * (APND_MARK_FOS_SZ-1);
  6172. unsigned char a[APND_MARK_SIZE];
  6173. if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
  6174. rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
  6175. if( rc ) return -1;
  6176. if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
  6177. iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
  6178. for(i=1; i<8; i++){
  6179. msbs -= 8;
  6180. iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
  6181. }
  6182. if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
  6183. if( iMark & 0x1ff ) return -1;
  6184. return iMark;
  6185. }
  6186. static const char apvfsSqliteHdr[] = "SQLite format 3";
  6187. /*
  6188. ** Check to see if the file is an appendvfs SQLite database file.
  6189. ** Return true iff it is such. Parameter sz is the file's size.
  6190. */
  6191. static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
  6192. int rc;
  6193. char zHdr[16];
  6194. sqlite3_int64 iMark = apndReadMark(sz, pFile);
  6195. if( iMark>=0 ){
  6196. /* If file has the correct end-marker, the expected odd size, and the
  6197. ** SQLite DB type marker where the end-marker puts it, then it
  6198. ** is an appendvfs database.
  6199. */
  6200. rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
  6201. if( SQLITE_OK==rc
  6202. && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
  6203. && (sz & 0x1ff) == APND_MARK_SIZE
  6204. && sz>=512+APND_MARK_SIZE
  6205. ){
  6206. return 1; /* It's an appendvfs database */
  6207. }
  6208. }
  6209. return 0;
  6210. }
  6211. /*
  6212. ** Check to see if the file is an ordinary SQLite database file.
  6213. ** Return true iff so. Parameter sz is the file's size.
  6214. */
  6215. static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
  6216. char zHdr[16];
  6217. if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
  6218. || (sz & 0x1ff) != 0
  6219. || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
  6220. || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
  6221. ){
  6222. return 0;
  6223. }else{
  6224. return 1;
  6225. }
  6226. }
  6227. /*
  6228. ** Open an apnd file handle.
  6229. */
  6230. static int apndOpen(
  6231. sqlite3_vfs *pApndVfs,
  6232. const char *zName,
  6233. sqlite3_file *pFile,
  6234. int flags,
  6235. int *pOutFlags
  6236. ){
  6237. ApndFile *pApndFile = (ApndFile*)pFile;
  6238. sqlite3_file *pBaseFile = ORIGFILE(pFile);
  6239. sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
  6240. int rc;
  6241. sqlite3_int64 sz = 0;
  6242. if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
  6243. /* The appendvfs is not to be used for transient or temporary databases.
  6244. ** Just use the base VFS open to initialize the given file object and
  6245. ** open the underlying file. (Appendvfs is then unused for this file.)
  6246. */
  6247. return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
  6248. }
  6249. memset(pApndFile, 0, sizeof(ApndFile));
  6250. pFile->pMethods = &apnd_io_methods;
  6251. pApndFile->iMark = -1; /* Append mark not yet written */
  6252. rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
  6253. if( rc==SQLITE_OK ){
  6254. rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
  6255. if( rc ){
  6256. pBaseFile->pMethods->xClose(pBaseFile);
  6257. }
  6258. }
  6259. if( rc ){
  6260. pFile->pMethods = 0;
  6261. return rc;
  6262. }
  6263. if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
  6264. /* The file being opened appears to be just an ordinary DB. Copy
  6265. ** the base dispatch-table so this instance mimics the base VFS.
  6266. */
  6267. memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
  6268. return SQLITE_OK;
  6269. }
  6270. pApndFile->iPgOne = apndReadMark(sz, pFile);
  6271. if( pApndFile->iPgOne>=0 ){
  6272. pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
  6273. return SQLITE_OK;
  6274. }
  6275. if( (flags & SQLITE_OPEN_CREATE)==0 ){
  6276. pBaseFile->pMethods->xClose(pBaseFile);
  6277. rc = SQLITE_CANTOPEN;
  6278. pFile->pMethods = 0;
  6279. }else{
  6280. /* Round newly added appendvfs location to #define'd page boundary.
  6281. ** Note that nothing has yet been written to the underlying file.
  6282. ** The append mark will be written along with first content write.
  6283. ** Until then, paf->iMark value indicates it is not yet written.
  6284. */
  6285. pApndFile->iPgOne = APND_START_ROUNDUP(sz);
  6286. }
  6287. return rc;
  6288. }
  6289. /*
  6290. ** Delete an apnd file.
  6291. ** For an appendvfs, this could mean delete the appendvfs portion,
  6292. ** leaving the appendee as it was before it gained an appendvfs.
  6293. ** For now, this code deletes the underlying file too.
  6294. */
  6295. static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  6296. return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
  6297. }
  6298. /*
  6299. ** All other VFS methods are pass-thrus.
  6300. */
  6301. static int apndAccess(
  6302. sqlite3_vfs *pVfs,
  6303. const char *zPath,
  6304. int flags,
  6305. int *pResOut
  6306. ){
  6307. return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
  6308. }
  6309. static int apndFullPathname(
  6310. sqlite3_vfs *pVfs,
  6311. const char *zPath,
  6312. int nOut,
  6313. char *zOut
  6314. ){
  6315. return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
  6316. }
  6317. static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  6318. return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
  6319. }
  6320. static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  6321. ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
  6322. }
  6323. static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
  6324. return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
  6325. }
  6326. static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
  6327. ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
  6328. }
  6329. static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  6330. return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
  6331. }
  6332. static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
  6333. return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
  6334. }
  6335. static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  6336. return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
  6337. }
  6338. static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  6339. return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
  6340. }
  6341. static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
  6342. return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
  6343. }
  6344. static int apndSetSystemCall(
  6345. sqlite3_vfs *pVfs,
  6346. const char *zName,
  6347. sqlite3_syscall_ptr pCall
  6348. ){
  6349. return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
  6350. }
  6351. static sqlite3_syscall_ptr apndGetSystemCall(
  6352. sqlite3_vfs *pVfs,
  6353. const char *zName
  6354. ){
  6355. return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
  6356. }
  6357. static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
  6358. return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
  6359. }
  6360. #ifdef _WIN32
  6361. #endif
  6362. /*
  6363. ** This routine is called when the extension is loaded.
  6364. ** Register the new VFS.
  6365. */
  6366. int sqlite3_appendvfs_init(
  6367. sqlite3 *db,
  6368. char **pzErrMsg,
  6369. const sqlite3_api_routines *pApi
  6370. ){
  6371. int rc = SQLITE_OK;
  6372. sqlite3_vfs *pOrig;
  6373. SQLITE_EXTENSION_INIT2(pApi);
  6374. (void)pzErrMsg;
  6375. (void)db;
  6376. pOrig = sqlite3_vfs_find(0);
  6377. if( pOrig==0 ) return SQLITE_ERROR;
  6378. apnd_vfs.iVersion = pOrig->iVersion;
  6379. apnd_vfs.pAppData = pOrig;
  6380. apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
  6381. rc = sqlite3_vfs_register(&apnd_vfs, 0);
  6382. #ifdef APPENDVFS_TEST
  6383. if( rc==SQLITE_OK ){
  6384. rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
  6385. }
  6386. #endif
  6387. if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
  6388. return rc;
  6389. }
  6390. /************************* End ../ext/misc/appendvfs.c ********************/
  6391. #endif
  6392. #ifdef SQLITE_HAVE_ZLIB
  6393. /************************* Begin ../ext/misc/zipfile.c ******************/
  6394. /*
  6395. ** 2017-12-26
  6396. **
  6397. ** The author disclaims copyright to this source code. In place of
  6398. ** a legal notice, here is a blessing:
  6399. **
  6400. ** May you do good and not evil.
  6401. ** May you find forgiveness for yourself and forgive others.
  6402. ** May you share freely, never taking more than you give.
  6403. **
  6404. ******************************************************************************
  6405. **
  6406. ** This file implements a virtual table for reading and writing ZIP archive
  6407. ** files.
  6408. **
  6409. ** Usage example:
  6410. **
  6411. ** SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
  6412. **
  6413. ** Current limitations:
  6414. **
  6415. ** * No support for encryption
  6416. ** * No support for ZIP archives spanning multiple files
  6417. ** * No support for zip64 extensions
  6418. ** * Only the "inflate/deflate" (zlib) compression method is supported
  6419. */
  6420. /* #include "sqlite3ext.h" */
  6421. SQLITE_EXTENSION_INIT1
  6422. #include <stdio.h>
  6423. #include <string.h>
  6424. #include <assert.h>
  6425. #include <zlib.h>
  6426. #ifndef SQLITE_OMIT_VIRTUALTABLE
  6427. #ifndef SQLITE_AMALGAMATION
  6428. #ifndef UINT32_TYPE
  6429. # ifdef HAVE_UINT32_T
  6430. # define UINT32_TYPE uint32_t
  6431. # else
  6432. # define UINT32_TYPE unsigned int
  6433. # endif
  6434. #endif
  6435. #ifndef UINT16_TYPE
  6436. # ifdef HAVE_UINT16_T
  6437. # define UINT16_TYPE uint16_t
  6438. # else
  6439. # define UINT16_TYPE unsigned short int
  6440. # endif
  6441. #endif
  6442. /* typedef sqlite3_int64 i64; */
  6443. /* typedef unsigned char u8; */
  6444. /* typedef UINT32_TYPE u32; // 4-byte unsigned integer // */
  6445. /* typedef UINT16_TYPE u16; // 2-byte unsigned integer // */
  6446. #define MIN(a,b) ((a)<(b) ? (a) : (b))
  6447. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  6448. # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
  6449. #endif
  6450. #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
  6451. # define ALWAYS(X) (1)
  6452. # define NEVER(X) (0)
  6453. #elif !defined(NDEBUG)
  6454. # define ALWAYS(X) ((X)?1:(assert(0),0))
  6455. # define NEVER(X) ((X)?(assert(0),1):0)
  6456. #else
  6457. # define ALWAYS(X) (X)
  6458. # define NEVER(X) (X)
  6459. #endif
  6460. #endif /* SQLITE_AMALGAMATION */
  6461. /*
  6462. ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
  6463. **
  6464. ** In some ways it would be better to obtain these values from system
  6465. ** header files. But, the dependency is undesirable and (a) these
  6466. ** have been stable for decades, (b) the values are part of POSIX and
  6467. ** are also made explicit in [man stat], and (c) are part of the
  6468. ** file format for zip archives.
  6469. */
  6470. #ifndef S_IFDIR
  6471. # define S_IFDIR 0040000
  6472. #endif
  6473. #ifndef S_IFREG
  6474. # define S_IFREG 0100000
  6475. #endif
  6476. #ifndef S_IFLNK
  6477. # define S_IFLNK 0120000
  6478. #endif
  6479. static const char ZIPFILE_SCHEMA[] =
  6480. "CREATE TABLE y("
  6481. "name PRIMARY KEY," /* 0: Name of file in zip archive */
  6482. "mode," /* 1: POSIX mode for file */
  6483. "mtime," /* 2: Last modification time (secs since 1970)*/
  6484. "sz," /* 3: Size of object */
  6485. "rawdata," /* 4: Raw data */
  6486. "data," /* 5: Uncompressed data */
  6487. "method," /* 6: Compression method (integer) */
  6488. "z HIDDEN" /* 7: Name of zip file */
  6489. ") WITHOUT ROWID;";
  6490. #define ZIPFILE_F_COLUMN_IDX 7 /* Index of column "file" in the above */
  6491. #define ZIPFILE_BUFFER_SIZE (64*1024)
  6492. /*
  6493. ** Magic numbers used to read and write zip files.
  6494. **
  6495. ** ZIPFILE_NEWENTRY_MADEBY:
  6496. ** Use this value for the "version-made-by" field in new zip file
  6497. ** entries. The upper byte indicates "unix", and the lower byte
  6498. ** indicates that the zip file matches pkzip specification 3.0.
  6499. ** This is what info-zip seems to do.
  6500. **
  6501. ** ZIPFILE_NEWENTRY_REQUIRED:
  6502. ** Value for "version-required-to-extract" field of new entries.
  6503. ** Version 2.0 is required to support folders and deflate compression.
  6504. **
  6505. ** ZIPFILE_NEWENTRY_FLAGS:
  6506. ** Value for "general-purpose-bit-flags" field of new entries. Bit
  6507. ** 11 means "utf-8 filename and comment".
  6508. **
  6509. ** ZIPFILE_SIGNATURE_CDS:
  6510. ** First 4 bytes of a valid CDS record.
  6511. **
  6512. ** ZIPFILE_SIGNATURE_LFH:
  6513. ** First 4 bytes of a valid LFH record.
  6514. **
  6515. ** ZIPFILE_SIGNATURE_EOCD
  6516. ** First 4 bytes of a valid EOCD record.
  6517. */
  6518. #define ZIPFILE_EXTRA_TIMESTAMP 0x5455
  6519. #define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30)
  6520. #define ZIPFILE_NEWENTRY_REQUIRED 20
  6521. #define ZIPFILE_NEWENTRY_FLAGS 0x800
  6522. #define ZIPFILE_SIGNATURE_CDS 0x02014b50
  6523. #define ZIPFILE_SIGNATURE_LFH 0x04034b50
  6524. #define ZIPFILE_SIGNATURE_EOCD 0x06054b50
  6525. /*
  6526. ** The sizes of the fixed-size part of each of the three main data
  6527. ** structures in a zip archive.
  6528. */
  6529. #define ZIPFILE_LFH_FIXED_SZ 30
  6530. #define ZIPFILE_EOCD_FIXED_SZ 22
  6531. #define ZIPFILE_CDS_FIXED_SZ 46
  6532. /*
  6533. *** 4.3.16 End of central directory record:
  6534. ***
  6535. *** end of central dir signature 4 bytes (0x06054b50)
  6536. *** number of this disk 2 bytes
  6537. *** number of the disk with the
  6538. *** start of the central directory 2 bytes
  6539. *** total number of entries in the
  6540. *** central directory on this disk 2 bytes
  6541. *** total number of entries in
  6542. *** the central directory 2 bytes
  6543. *** size of the central directory 4 bytes
  6544. *** offset of start of central
  6545. *** directory with respect to
  6546. *** the starting disk number 4 bytes
  6547. *** .ZIP file comment length 2 bytes
  6548. *** .ZIP file comment (variable size)
  6549. */
  6550. typedef struct ZipfileEOCD ZipfileEOCD;
  6551. struct ZipfileEOCD {
  6552. u16 iDisk;
  6553. u16 iFirstDisk;
  6554. u16 nEntry;
  6555. u16 nEntryTotal;
  6556. u32 nSize;
  6557. u32 iOffset;
  6558. };
  6559. /*
  6560. *** 4.3.12 Central directory structure:
  6561. ***
  6562. *** ...
  6563. ***
  6564. *** central file header signature 4 bytes (0x02014b50)
  6565. *** version made by 2 bytes
  6566. *** version needed to extract 2 bytes
  6567. *** general purpose bit flag 2 bytes
  6568. *** compression method 2 bytes
  6569. *** last mod file time 2 bytes
  6570. *** last mod file date 2 bytes
  6571. *** crc-32 4 bytes
  6572. *** compressed size 4 bytes
  6573. *** uncompressed size 4 bytes
  6574. *** file name length 2 bytes
  6575. *** extra field length 2 bytes
  6576. *** file comment length 2 bytes
  6577. *** disk number start 2 bytes
  6578. *** internal file attributes 2 bytes
  6579. *** external file attributes 4 bytes
  6580. *** relative offset of local header 4 bytes
  6581. */
  6582. typedef struct ZipfileCDS ZipfileCDS;
  6583. struct ZipfileCDS {
  6584. u16 iVersionMadeBy;
  6585. u16 iVersionExtract;
  6586. u16 flags;
  6587. u16 iCompression;
  6588. u16 mTime;
  6589. u16 mDate;
  6590. u32 crc32;
  6591. u32 szCompressed;
  6592. u32 szUncompressed;
  6593. u16 nFile;
  6594. u16 nExtra;
  6595. u16 nComment;
  6596. u16 iDiskStart;
  6597. u16 iInternalAttr;
  6598. u32 iExternalAttr;
  6599. u32 iOffset;
  6600. char *zFile; /* Filename (sqlite3_malloc()) */
  6601. };
  6602. /*
  6603. *** 4.3.7 Local file header:
  6604. ***
  6605. *** local file header signature 4 bytes (0x04034b50)
  6606. *** version needed to extract 2 bytes
  6607. *** general purpose bit flag 2 bytes
  6608. *** compression method 2 bytes
  6609. *** last mod file time 2 bytes
  6610. *** last mod file date 2 bytes
  6611. *** crc-32 4 bytes
  6612. *** compressed size 4 bytes
  6613. *** uncompressed size 4 bytes
  6614. *** file name length 2 bytes
  6615. *** extra field length 2 bytes
  6616. ***
  6617. */
  6618. typedef struct ZipfileLFH ZipfileLFH;
  6619. struct ZipfileLFH {
  6620. u16 iVersionExtract;
  6621. u16 flags;
  6622. u16 iCompression;
  6623. u16 mTime;
  6624. u16 mDate;
  6625. u32 crc32;
  6626. u32 szCompressed;
  6627. u32 szUncompressed;
  6628. u16 nFile;
  6629. u16 nExtra;
  6630. };
  6631. typedef struct ZipfileEntry ZipfileEntry;
  6632. struct ZipfileEntry {
  6633. ZipfileCDS cds; /* Parsed CDS record */
  6634. u32 mUnixTime; /* Modification time, in UNIX format */
  6635. u8 *aExtra; /* cds.nExtra+cds.nComment bytes of extra data */
  6636. i64 iDataOff; /* Offset to data in file (if aData==0) */
  6637. u8 *aData; /* cds.szCompressed bytes of compressed data */
  6638. ZipfileEntry *pNext; /* Next element in in-memory CDS */
  6639. };
  6640. /*
  6641. ** Cursor type for zipfile tables.
  6642. */
  6643. typedef struct ZipfileCsr ZipfileCsr;
  6644. struct ZipfileCsr {
  6645. sqlite3_vtab_cursor base; /* Base class - must be first */
  6646. i64 iId; /* Cursor ID */
  6647. u8 bEof; /* True when at EOF */
  6648. u8 bNoop; /* If next xNext() call is no-op */
  6649. /* Used outside of write transactions */
  6650. FILE *pFile; /* Zip file */
  6651. i64 iNextOff; /* Offset of next record in central directory */
  6652. ZipfileEOCD eocd; /* Parse of central directory record */
  6653. ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */
  6654. ZipfileEntry *pCurrent; /* Current entry */
  6655. ZipfileCsr *pCsrNext; /* Next cursor on same virtual table */
  6656. };
  6657. typedef struct ZipfileTab ZipfileTab;
  6658. struct ZipfileTab {
  6659. sqlite3_vtab base; /* Base class - must be first */
  6660. char *zFile; /* Zip file this table accesses (may be NULL) */
  6661. sqlite3 *db; /* Host database connection */
  6662. u8 *aBuffer; /* Temporary buffer used for various tasks */
  6663. ZipfileCsr *pCsrList; /* List of cursors */
  6664. i64 iNextCsrid;
  6665. /* The following are used by write transactions only */
  6666. ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
  6667. ZipfileEntry *pLastEntry; /* Last element in pFirstEntry list */
  6668. FILE *pWriteFd; /* File handle open on zip archive */
  6669. i64 szCurrent; /* Current size of zip archive */
  6670. i64 szOrig; /* Size of archive at start of transaction */
  6671. };
  6672. /*
  6673. ** Set the error message contained in context ctx to the results of
  6674. ** vprintf(zFmt, ...).
  6675. */
  6676. static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
  6677. char *zMsg = 0;
  6678. va_list ap;
  6679. va_start(ap, zFmt);
  6680. zMsg = sqlite3_vmprintf(zFmt, ap);
  6681. sqlite3_result_error(ctx, zMsg, -1);
  6682. sqlite3_free(zMsg);
  6683. va_end(ap);
  6684. }
  6685. /*
  6686. ** If string zIn is quoted, dequote it in place. Otherwise, if the string
  6687. ** is not quoted, do nothing.
  6688. */
  6689. static void zipfileDequote(char *zIn){
  6690. char q = zIn[0];
  6691. if( q=='"' || q=='\'' || q=='`' || q=='[' ){
  6692. int iIn = 1;
  6693. int iOut = 0;
  6694. if( q=='[' ) q = ']';
  6695. while( ALWAYS(zIn[iIn]) ){
  6696. char c = zIn[iIn++];
  6697. if( c==q && zIn[iIn++]!=q ) break;
  6698. zIn[iOut++] = c;
  6699. }
  6700. zIn[iOut] = '\0';
  6701. }
  6702. }
  6703. /*
  6704. ** Construct a new ZipfileTab virtual table object.
  6705. **
  6706. ** argv[0] -> module name ("zipfile")
  6707. ** argv[1] -> database name
  6708. ** argv[2] -> table name
  6709. ** argv[...] -> "column name" and other module argument fields.
  6710. */
  6711. static int zipfileConnect(
  6712. sqlite3 *db,
  6713. void *pAux,
  6714. int argc, const char *const*argv,
  6715. sqlite3_vtab **ppVtab,
  6716. char **pzErr
  6717. ){
  6718. int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
  6719. int nFile = 0;
  6720. const char *zFile = 0;
  6721. ZipfileTab *pNew = 0;
  6722. int rc;
  6723. /* If the table name is not "zipfile", require that the argument be
  6724. ** specified. This stops zipfile tables from being created as:
  6725. **
  6726. ** CREATE VIRTUAL TABLE zzz USING zipfile();
  6727. **
  6728. ** It does not prevent:
  6729. **
  6730. ** CREATE VIRTUAL TABLE zipfile USING zipfile();
  6731. */
  6732. assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
  6733. if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
  6734. *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
  6735. return SQLITE_ERROR;
  6736. }
  6737. if( argc>3 ){
  6738. zFile = argv[3];
  6739. nFile = (int)strlen(zFile)+1;
  6740. }
  6741. rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
  6742. if( rc==SQLITE_OK ){
  6743. pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
  6744. if( pNew==0 ) return SQLITE_NOMEM;
  6745. memset(pNew, 0, nByte+nFile);
  6746. pNew->db = db;
  6747. pNew->aBuffer = (u8*)&pNew[1];
  6748. if( zFile ){
  6749. pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
  6750. memcpy(pNew->zFile, zFile, nFile);
  6751. zipfileDequote(pNew->zFile);
  6752. }
  6753. }
  6754. sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
  6755. *ppVtab = (sqlite3_vtab*)pNew;
  6756. return rc;
  6757. }
  6758. /*
  6759. ** Free the ZipfileEntry structure indicated by the only argument.
  6760. */
  6761. static void zipfileEntryFree(ZipfileEntry *p){
  6762. if( p ){
  6763. sqlite3_free(p->cds.zFile);
  6764. sqlite3_free(p);
  6765. }
  6766. }
  6767. /*
  6768. ** Release resources that should be freed at the end of a write
  6769. ** transaction.
  6770. */
  6771. static void zipfileCleanupTransaction(ZipfileTab *pTab){
  6772. ZipfileEntry *pEntry;
  6773. ZipfileEntry *pNext;
  6774. if( pTab->pWriteFd ){
  6775. fclose(pTab->pWriteFd);
  6776. pTab->pWriteFd = 0;
  6777. }
  6778. for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
  6779. pNext = pEntry->pNext;
  6780. zipfileEntryFree(pEntry);
  6781. }
  6782. pTab->pFirstEntry = 0;
  6783. pTab->pLastEntry = 0;
  6784. pTab->szCurrent = 0;
  6785. pTab->szOrig = 0;
  6786. }
  6787. /*
  6788. ** This method is the destructor for zipfile vtab objects.
  6789. */
  6790. static int zipfileDisconnect(sqlite3_vtab *pVtab){
  6791. zipfileCleanupTransaction((ZipfileTab*)pVtab);
  6792. sqlite3_free(pVtab);
  6793. return SQLITE_OK;
  6794. }
  6795. /*
  6796. ** Constructor for a new ZipfileCsr object.
  6797. */
  6798. static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
  6799. ZipfileTab *pTab = (ZipfileTab*)p;
  6800. ZipfileCsr *pCsr;
  6801. pCsr = sqlite3_malloc(sizeof(*pCsr));
  6802. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  6803. if( pCsr==0 ){
  6804. return SQLITE_NOMEM;
  6805. }
  6806. memset(pCsr, 0, sizeof(*pCsr));
  6807. pCsr->iId = ++pTab->iNextCsrid;
  6808. pCsr->pCsrNext = pTab->pCsrList;
  6809. pTab->pCsrList = pCsr;
  6810. return SQLITE_OK;
  6811. }
  6812. /*
  6813. ** Reset a cursor back to the state it was in when first returned
  6814. ** by zipfileOpen().
  6815. */
  6816. static void zipfileResetCursor(ZipfileCsr *pCsr){
  6817. ZipfileEntry *p;
  6818. ZipfileEntry *pNext;
  6819. pCsr->bEof = 0;
  6820. if( pCsr->pFile ){
  6821. fclose(pCsr->pFile);
  6822. pCsr->pFile = 0;
  6823. zipfileEntryFree(pCsr->pCurrent);
  6824. pCsr->pCurrent = 0;
  6825. }
  6826. for(p=pCsr->pFreeEntry; p; p=pNext){
  6827. pNext = p->pNext;
  6828. zipfileEntryFree(p);
  6829. }
  6830. }
  6831. /*
  6832. ** Destructor for an ZipfileCsr.
  6833. */
  6834. static int zipfileClose(sqlite3_vtab_cursor *cur){
  6835. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  6836. ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
  6837. ZipfileCsr **pp;
  6838. zipfileResetCursor(pCsr);
  6839. /* Remove this cursor from the ZipfileTab.pCsrList list. */
  6840. for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
  6841. *pp = pCsr->pCsrNext;
  6842. sqlite3_free(pCsr);
  6843. return SQLITE_OK;
  6844. }
  6845. /*
  6846. ** Set the error message for the virtual table associated with cursor
  6847. ** pCsr to the results of vprintf(zFmt, ...).
  6848. */
  6849. static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
  6850. va_list ap;
  6851. va_start(ap, zFmt);
  6852. sqlite3_free(pTab->base.zErrMsg);
  6853. pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
  6854. va_end(ap);
  6855. }
  6856. static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
  6857. va_list ap;
  6858. va_start(ap, zFmt);
  6859. sqlite3_free(pCsr->base.pVtab->zErrMsg);
  6860. pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
  6861. va_end(ap);
  6862. }
  6863. /*
  6864. ** Read nRead bytes of data from offset iOff of file pFile into buffer
  6865. ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
  6866. ** otherwise.
  6867. **
  6868. ** If an error does occur, output variable (*pzErrmsg) may be set to point
  6869. ** to an English language error message. It is the responsibility of the
  6870. ** caller to eventually free this buffer using
  6871. ** sqlite3_free().
  6872. */
  6873. static int zipfileReadData(
  6874. FILE *pFile, /* Read from this file */
  6875. u8 *aRead, /* Read into this buffer */
  6876. int nRead, /* Number of bytes to read */
  6877. i64 iOff, /* Offset to read from */
  6878. char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */
  6879. ){
  6880. size_t n;
  6881. fseek(pFile, (long)iOff, SEEK_SET);
  6882. n = fread(aRead, 1, nRead, pFile);
  6883. if( (int)n!=nRead ){
  6884. *pzErrmsg = sqlite3_mprintf("error in fread()");
  6885. return SQLITE_ERROR;
  6886. }
  6887. return SQLITE_OK;
  6888. }
  6889. static int zipfileAppendData(
  6890. ZipfileTab *pTab,
  6891. const u8 *aWrite,
  6892. int nWrite
  6893. ){
  6894. if( nWrite>0 ){
  6895. size_t n = nWrite;
  6896. fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
  6897. n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
  6898. if( (int)n!=nWrite ){
  6899. pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
  6900. return SQLITE_ERROR;
  6901. }
  6902. pTab->szCurrent += nWrite;
  6903. }
  6904. return SQLITE_OK;
  6905. }
  6906. /*
  6907. ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
  6908. */
  6909. static u16 zipfileGetU16(const u8 *aBuf){
  6910. return (aBuf[1] << 8) + aBuf[0];
  6911. }
  6912. /*
  6913. ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
  6914. */
  6915. static u32 zipfileGetU32(const u8 *aBuf){
  6916. if( aBuf==0 ) return 0;
  6917. return ((u32)(aBuf[3]) << 24)
  6918. + ((u32)(aBuf[2]) << 16)
  6919. + ((u32)(aBuf[1]) << 8)
  6920. + ((u32)(aBuf[0]) << 0);
  6921. }
  6922. /*
  6923. ** Write a 16-bit little endiate integer into buffer aBuf.
  6924. */
  6925. static void zipfilePutU16(u8 *aBuf, u16 val){
  6926. aBuf[0] = val & 0xFF;
  6927. aBuf[1] = (val>>8) & 0xFF;
  6928. }
  6929. /*
  6930. ** Write a 32-bit little endiate integer into buffer aBuf.
  6931. */
  6932. static void zipfilePutU32(u8 *aBuf, u32 val){
  6933. aBuf[0] = val & 0xFF;
  6934. aBuf[1] = (val>>8) & 0xFF;
  6935. aBuf[2] = (val>>16) & 0xFF;
  6936. aBuf[3] = (val>>24) & 0xFF;
  6937. }
  6938. #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
  6939. #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
  6940. #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
  6941. #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
  6942. /*
  6943. ** Magic numbers used to read CDS records.
  6944. */
  6945. #define ZIPFILE_CDS_NFILE_OFF 28
  6946. #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
  6947. /*
  6948. ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
  6949. ** if the record is not well-formed, or SQLITE_OK otherwise.
  6950. */
  6951. static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
  6952. u8 *aRead = aBuf;
  6953. u32 sig = zipfileRead32(aRead);
  6954. int rc = SQLITE_OK;
  6955. if( sig!=ZIPFILE_SIGNATURE_CDS ){
  6956. rc = SQLITE_ERROR;
  6957. }else{
  6958. pCDS->iVersionMadeBy = zipfileRead16(aRead);
  6959. pCDS->iVersionExtract = zipfileRead16(aRead);
  6960. pCDS->flags = zipfileRead16(aRead);
  6961. pCDS->iCompression = zipfileRead16(aRead);
  6962. pCDS->mTime = zipfileRead16(aRead);
  6963. pCDS->mDate = zipfileRead16(aRead);
  6964. pCDS->crc32 = zipfileRead32(aRead);
  6965. pCDS->szCompressed = zipfileRead32(aRead);
  6966. pCDS->szUncompressed = zipfileRead32(aRead);
  6967. assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
  6968. pCDS->nFile = zipfileRead16(aRead);
  6969. pCDS->nExtra = zipfileRead16(aRead);
  6970. pCDS->nComment = zipfileRead16(aRead);
  6971. pCDS->iDiskStart = zipfileRead16(aRead);
  6972. pCDS->iInternalAttr = zipfileRead16(aRead);
  6973. pCDS->iExternalAttr = zipfileRead32(aRead);
  6974. pCDS->iOffset = zipfileRead32(aRead);
  6975. assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
  6976. }
  6977. return rc;
  6978. }
  6979. /*
  6980. ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
  6981. ** if the record is not well-formed, or SQLITE_OK otherwise.
  6982. */
  6983. static int zipfileReadLFH(
  6984. u8 *aBuffer,
  6985. ZipfileLFH *pLFH
  6986. ){
  6987. u8 *aRead = aBuffer;
  6988. int rc = SQLITE_OK;
  6989. u32 sig = zipfileRead32(aRead);
  6990. if( sig!=ZIPFILE_SIGNATURE_LFH ){
  6991. rc = SQLITE_ERROR;
  6992. }else{
  6993. pLFH->iVersionExtract = zipfileRead16(aRead);
  6994. pLFH->flags = zipfileRead16(aRead);
  6995. pLFH->iCompression = zipfileRead16(aRead);
  6996. pLFH->mTime = zipfileRead16(aRead);
  6997. pLFH->mDate = zipfileRead16(aRead);
  6998. pLFH->crc32 = zipfileRead32(aRead);
  6999. pLFH->szCompressed = zipfileRead32(aRead);
  7000. pLFH->szUncompressed = zipfileRead32(aRead);
  7001. pLFH->nFile = zipfileRead16(aRead);
  7002. pLFH->nExtra = zipfileRead16(aRead);
  7003. }
  7004. return rc;
  7005. }
  7006. /*
  7007. ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
  7008. ** Scan through this buffer to find an "extra-timestamp" field. If one
  7009. ** exists, extract the 32-bit modification-timestamp from it and store
  7010. ** the value in output parameter *pmTime.
  7011. **
  7012. ** Zero is returned if no extra-timestamp record could be found (and so
  7013. ** *pmTime is left unchanged), or non-zero otherwise.
  7014. **
  7015. ** The general format of an extra field is:
  7016. **
  7017. ** Header ID 2 bytes
  7018. ** Data Size 2 bytes
  7019. ** Data N bytes
  7020. */
  7021. static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
  7022. int ret = 0;
  7023. u8 *p = aExtra;
  7024. u8 *pEnd = &aExtra[nExtra];
  7025. while( p<pEnd ){
  7026. u16 id = zipfileRead16(p);
  7027. u16 nByte = zipfileRead16(p);
  7028. switch( id ){
  7029. case ZIPFILE_EXTRA_TIMESTAMP: {
  7030. u8 b = p[0];
  7031. if( b & 0x01 ){ /* 0x01 -> modtime is present */
  7032. *pmTime = zipfileGetU32(&p[1]);
  7033. ret = 1;
  7034. }
  7035. break;
  7036. }
  7037. }
  7038. p += nByte;
  7039. }
  7040. return ret;
  7041. }
  7042. /*
  7043. ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
  7044. ** fields of the CDS structure passed as the only argument to a 32-bit
  7045. ** UNIX seconds-since-the-epoch timestamp. Return the result.
  7046. **
  7047. ** "Standard" MS-DOS time format:
  7048. **
  7049. ** File modification time:
  7050. ** Bits 00-04: seconds divided by 2
  7051. ** Bits 05-10: minute
  7052. ** Bits 11-15: hour
  7053. ** File modification date:
  7054. ** Bits 00-04: day
  7055. ** Bits 05-08: month (1-12)
  7056. ** Bits 09-15: years from 1980
  7057. **
  7058. ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
  7059. */
  7060. static u32 zipfileMtime(ZipfileCDS *pCDS){
  7061. int Y,M,D,X1,X2,A,B,sec,min,hr;
  7062. i64 JDsec;
  7063. Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
  7064. M = ((pCDS->mDate >> 5) & 0x0F);
  7065. D = (pCDS->mDate & 0x1F);
  7066. sec = (pCDS->mTime & 0x1F)*2;
  7067. min = (pCDS->mTime >> 5) & 0x3F;
  7068. hr = (pCDS->mTime >> 11) & 0x1F;
  7069. if( M<=2 ){
  7070. Y--;
  7071. M += 12;
  7072. }
  7073. X1 = 36525*(Y+4716)/100;
  7074. X2 = 306001*(M+1)/10000;
  7075. A = Y/100;
  7076. B = 2 - A + (A/4);
  7077. JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
  7078. return (u32)(JDsec - (i64)24405875*(i64)8640);
  7079. }
  7080. /*
  7081. ** The opposite of zipfileMtime(). This function populates the mTime and
  7082. ** mDate fields of the CDS structure passed as the first argument according
  7083. ** to the UNIX timestamp value passed as the second.
  7084. */
  7085. static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
  7086. /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
  7087. i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
  7088. int A, B, C, D, E;
  7089. int yr, mon, day;
  7090. int hr, min, sec;
  7091. A = (int)((JD - 1867216.25)/36524.25);
  7092. A = (int)(JD + 1 + A - (A/4));
  7093. B = A + 1524;
  7094. C = (int)((B - 122.1)/365.25);
  7095. D = (36525*(C&32767))/100;
  7096. E = (int)((B-D)/30.6001);
  7097. day = B - D - (int)(30.6001*E);
  7098. mon = (E<14 ? E-1 : E-13);
  7099. yr = mon>2 ? C-4716 : C-4715;
  7100. hr = (mUnixTime % (24*60*60)) / (60*60);
  7101. min = (mUnixTime % (60*60)) / 60;
  7102. sec = (mUnixTime % 60);
  7103. if( yr>=1980 ){
  7104. pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
  7105. pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
  7106. }else{
  7107. pCds->mDate = pCds->mTime = 0;
  7108. }
  7109. assert( mUnixTime<315507600
  7110. || mUnixTime==zipfileMtime(pCds)
  7111. || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
  7112. /* || (mUnixTime % 2) */
  7113. );
  7114. }
  7115. /*
  7116. ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
  7117. ** size) containing an entire zip archive image. Or, if aBlob is NULL,
  7118. ** then pFile is a file-handle open on a zip file. In either case, this
  7119. ** function creates a ZipfileEntry object based on the zip archive entry
  7120. ** for which the CDS record is at offset iOff.
  7121. **
  7122. ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
  7123. ** the new object. Otherwise, an SQLite error code is returned and the
  7124. ** final value of (*ppEntry) undefined.
  7125. */
  7126. static int zipfileGetEntry(
  7127. ZipfileTab *pTab, /* Store any error message here */
  7128. const u8 *aBlob, /* Pointer to in-memory file image */
  7129. int nBlob, /* Size of aBlob[] in bytes */
  7130. FILE *pFile, /* If aBlob==0, read from this file */
  7131. i64 iOff, /* Offset of CDS record */
  7132. ZipfileEntry **ppEntry /* OUT: Pointer to new object */
  7133. ){
  7134. u8 *aRead;
  7135. char **pzErr = &pTab->base.zErrMsg;
  7136. int rc = SQLITE_OK;
  7137. if( aBlob==0 ){
  7138. aRead = pTab->aBuffer;
  7139. rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
  7140. }else{
  7141. aRead = (u8*)&aBlob[iOff];
  7142. }
  7143. if( rc==SQLITE_OK ){
  7144. sqlite3_int64 nAlloc;
  7145. ZipfileEntry *pNew;
  7146. int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
  7147. int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
  7148. nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
  7149. nAlloc = sizeof(ZipfileEntry) + nExtra;
  7150. if( aBlob ){
  7151. nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
  7152. }
  7153. pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
  7154. if( pNew==0 ){
  7155. rc = SQLITE_NOMEM;
  7156. }else{
  7157. memset(pNew, 0, sizeof(ZipfileEntry));
  7158. rc = zipfileReadCDS(aRead, &pNew->cds);
  7159. if( rc!=SQLITE_OK ){
  7160. *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
  7161. }else if( aBlob==0 ){
  7162. rc = zipfileReadData(
  7163. pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
  7164. );
  7165. }else{
  7166. aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
  7167. }
  7168. }
  7169. if( rc==SQLITE_OK ){
  7170. u32 *pt = &pNew->mUnixTime;
  7171. pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
  7172. pNew->aExtra = (u8*)&pNew[1];
  7173. memcpy(pNew->aExtra, &aRead[nFile], nExtra);
  7174. if( pNew->cds.zFile==0 ){
  7175. rc = SQLITE_NOMEM;
  7176. }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
  7177. pNew->mUnixTime = zipfileMtime(&pNew->cds);
  7178. }
  7179. }
  7180. if( rc==SQLITE_OK ){
  7181. static const int szFix = ZIPFILE_LFH_FIXED_SZ;
  7182. ZipfileLFH lfh;
  7183. if( pFile ){
  7184. rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
  7185. }else{
  7186. aRead = (u8*)&aBlob[pNew->cds.iOffset];
  7187. }
  7188. if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
  7189. if( rc==SQLITE_OK ){
  7190. pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
  7191. pNew->iDataOff += lfh.nFile + lfh.nExtra;
  7192. if( aBlob && pNew->cds.szCompressed ){
  7193. pNew->aData = &pNew->aExtra[nExtra];
  7194. memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
  7195. }
  7196. }else{
  7197. *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
  7198. (int)pNew->cds.iOffset
  7199. );
  7200. }
  7201. }
  7202. if( rc!=SQLITE_OK ){
  7203. zipfileEntryFree(pNew);
  7204. }else{
  7205. *ppEntry = pNew;
  7206. }
  7207. }
  7208. return rc;
  7209. }
  7210. /*
  7211. ** Advance an ZipfileCsr to its next row of output.
  7212. */
  7213. static int zipfileNext(sqlite3_vtab_cursor *cur){
  7214. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  7215. int rc = SQLITE_OK;
  7216. if( pCsr->pFile ){
  7217. i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
  7218. zipfileEntryFree(pCsr->pCurrent);
  7219. pCsr->pCurrent = 0;
  7220. if( pCsr->iNextOff>=iEof ){
  7221. pCsr->bEof = 1;
  7222. }else{
  7223. ZipfileEntry *p = 0;
  7224. ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
  7225. rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
  7226. if( rc==SQLITE_OK ){
  7227. pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
  7228. pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
  7229. }
  7230. pCsr->pCurrent = p;
  7231. }
  7232. }else{
  7233. if( !pCsr->bNoop ){
  7234. pCsr->pCurrent = pCsr->pCurrent->pNext;
  7235. }
  7236. if( pCsr->pCurrent==0 ){
  7237. pCsr->bEof = 1;
  7238. }
  7239. }
  7240. pCsr->bNoop = 0;
  7241. return rc;
  7242. }
  7243. static void zipfileFree(void *p) {
  7244. sqlite3_free(p);
  7245. }
  7246. /*
  7247. ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
  7248. ** size is nOut bytes. This function uncompresses the data and sets the
  7249. ** return value in context pCtx to the result (a blob).
  7250. **
  7251. ** If an error occurs, an error code is left in pCtx instead.
  7252. */
  7253. static void zipfileInflate(
  7254. sqlite3_context *pCtx, /* Store result here */
  7255. const u8 *aIn, /* Compressed data */
  7256. int nIn, /* Size of buffer aIn[] in bytes */
  7257. int nOut /* Expected output size */
  7258. ){
  7259. u8 *aRes = sqlite3_malloc(nOut);
  7260. if( aRes==0 ){
  7261. sqlite3_result_error_nomem(pCtx);
  7262. }else{
  7263. int err;
  7264. z_stream str;
  7265. memset(&str, 0, sizeof(str));
  7266. str.next_in = (Byte*)aIn;
  7267. str.avail_in = nIn;
  7268. str.next_out = (Byte*)aRes;
  7269. str.avail_out = nOut;
  7270. err = inflateInit2(&str, -15);
  7271. if( err!=Z_OK ){
  7272. zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
  7273. }else{
  7274. err = inflate(&str, Z_NO_FLUSH);
  7275. if( err!=Z_STREAM_END ){
  7276. zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
  7277. }else{
  7278. sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
  7279. aRes = 0;
  7280. }
  7281. }
  7282. sqlite3_free(aRes);
  7283. inflateEnd(&str);
  7284. }
  7285. }
  7286. /*
  7287. ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
  7288. ** compresses it and sets (*ppOut) to point to a buffer containing the
  7289. ** compressed data. The caller is responsible for eventually calling
  7290. ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
  7291. ** is set to the size of buffer (*ppOut) in bytes.
  7292. **
  7293. ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
  7294. ** code is returned and an error message left in virtual-table handle
  7295. ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
  7296. ** case.
  7297. */
  7298. static int zipfileDeflate(
  7299. const u8 *aIn, int nIn, /* Input */
  7300. u8 **ppOut, int *pnOut, /* Output */
  7301. char **pzErr /* OUT: Error message */
  7302. ){
  7303. int rc = SQLITE_OK;
  7304. sqlite3_int64 nAlloc;
  7305. z_stream str;
  7306. u8 *aOut;
  7307. memset(&str, 0, sizeof(str));
  7308. str.next_in = (Bytef*)aIn;
  7309. str.avail_in = nIn;
  7310. deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
  7311. nAlloc = deflateBound(&str, nIn);
  7312. aOut = (u8*)sqlite3_malloc64(nAlloc);
  7313. if( aOut==0 ){
  7314. rc = SQLITE_NOMEM;
  7315. }else{
  7316. int res;
  7317. str.next_out = aOut;
  7318. str.avail_out = nAlloc;
  7319. res = deflate(&str, Z_FINISH);
  7320. if( res==Z_STREAM_END ){
  7321. *ppOut = aOut;
  7322. *pnOut = (int)str.total_out;
  7323. }else{
  7324. sqlite3_free(aOut);
  7325. *pzErr = sqlite3_mprintf("zipfile: deflate() error");
  7326. rc = SQLITE_ERROR;
  7327. }
  7328. deflateEnd(&str);
  7329. }
  7330. return rc;
  7331. }
  7332. /*
  7333. ** Return values of columns for the row at which the series_cursor
  7334. ** is currently pointing.
  7335. */
  7336. static int zipfileColumn(
  7337. sqlite3_vtab_cursor *cur, /* The cursor */
  7338. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  7339. int i /* Which column to return */
  7340. ){
  7341. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  7342. ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
  7343. int rc = SQLITE_OK;
  7344. switch( i ){
  7345. case 0: /* name */
  7346. sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
  7347. break;
  7348. case 1: /* mode */
  7349. /* TODO: Whether or not the following is correct surely depends on
  7350. ** the platform on which the archive was created. */
  7351. sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
  7352. break;
  7353. case 2: { /* mtime */
  7354. sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
  7355. break;
  7356. }
  7357. case 3: { /* sz */
  7358. if( sqlite3_vtab_nochange(ctx)==0 ){
  7359. sqlite3_result_int64(ctx, pCDS->szUncompressed);
  7360. }
  7361. break;
  7362. }
  7363. case 4: /* rawdata */
  7364. if( sqlite3_vtab_nochange(ctx) ) break;
  7365. case 5: { /* data */
  7366. if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
  7367. int sz = pCDS->szCompressed;
  7368. int szFinal = pCDS->szUncompressed;
  7369. if( szFinal>0 ){
  7370. u8 *aBuf;
  7371. u8 *aFree = 0;
  7372. if( pCsr->pCurrent->aData ){
  7373. aBuf = pCsr->pCurrent->aData;
  7374. }else{
  7375. aBuf = aFree = sqlite3_malloc64(sz);
  7376. if( aBuf==0 ){
  7377. rc = SQLITE_NOMEM;
  7378. }else{
  7379. FILE *pFile = pCsr->pFile;
  7380. if( pFile==0 ){
  7381. pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
  7382. }
  7383. rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
  7384. &pCsr->base.pVtab->zErrMsg
  7385. );
  7386. }
  7387. }
  7388. if( rc==SQLITE_OK ){
  7389. if( i==5 && pCDS->iCompression ){
  7390. zipfileInflate(ctx, aBuf, sz, szFinal);
  7391. }else{
  7392. sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
  7393. }
  7394. }
  7395. sqlite3_free(aFree);
  7396. }else{
  7397. /* Figure out if this is a directory or a zero-sized file. Consider
  7398. ** it to be a directory either if the mode suggests so, or if
  7399. ** the final character in the name is '/'. */
  7400. u32 mode = pCDS->iExternalAttr >> 16;
  7401. if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
  7402. sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
  7403. }
  7404. }
  7405. }
  7406. break;
  7407. }
  7408. case 6: /* method */
  7409. sqlite3_result_int(ctx, pCDS->iCompression);
  7410. break;
  7411. default: /* z */
  7412. assert( i==7 );
  7413. sqlite3_result_int64(ctx, pCsr->iId);
  7414. break;
  7415. }
  7416. return rc;
  7417. }
  7418. /*
  7419. ** Return TRUE if the cursor is at EOF.
  7420. */
  7421. static int zipfileEof(sqlite3_vtab_cursor *cur){
  7422. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  7423. return pCsr->bEof;
  7424. }
  7425. /*
  7426. ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
  7427. ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
  7428. ** is guaranteed to be a file-handle open on a zip file.
  7429. **
  7430. ** This function attempts to locate the EOCD record within the zip archive
  7431. ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
  7432. ** returned if successful. Otherwise, an SQLite error code is returned and
  7433. ** an English language error message may be left in virtual-table pTab.
  7434. */
  7435. static int zipfileReadEOCD(
  7436. ZipfileTab *pTab, /* Return errors here */
  7437. const u8 *aBlob, /* Pointer to in-memory file image */
  7438. int nBlob, /* Size of aBlob[] in bytes */
  7439. FILE *pFile, /* Read from this file if aBlob==0 */
  7440. ZipfileEOCD *pEOCD /* Object to populate */
  7441. ){
  7442. u8 *aRead = pTab->aBuffer; /* Temporary buffer */
  7443. int nRead; /* Bytes to read from file */
  7444. int rc = SQLITE_OK;
  7445. memset(pEOCD, 0, sizeof(ZipfileEOCD));
  7446. if( aBlob==0 ){
  7447. i64 iOff; /* Offset to read from */
  7448. i64 szFile; /* Total size of file in bytes */
  7449. fseek(pFile, 0, SEEK_END);
  7450. szFile = (i64)ftell(pFile);
  7451. if( szFile==0 ){
  7452. return SQLITE_OK;
  7453. }
  7454. nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
  7455. iOff = szFile - nRead;
  7456. rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
  7457. }else{
  7458. nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
  7459. aRead = (u8*)&aBlob[nBlob-nRead];
  7460. }
  7461. if( rc==SQLITE_OK ){
  7462. int i;
  7463. /* Scan backwards looking for the signature bytes */
  7464. for(i=nRead-20; i>=0; i--){
  7465. if( aRead[i]==0x50 && aRead[i+1]==0x4b
  7466. && aRead[i+2]==0x05 && aRead[i+3]==0x06
  7467. ){
  7468. break;
  7469. }
  7470. }
  7471. if( i<0 ){
  7472. pTab->base.zErrMsg = sqlite3_mprintf(
  7473. "cannot find end of central directory record"
  7474. );
  7475. return SQLITE_ERROR;
  7476. }
  7477. aRead += i+4;
  7478. pEOCD->iDisk = zipfileRead16(aRead);
  7479. pEOCD->iFirstDisk = zipfileRead16(aRead);
  7480. pEOCD->nEntry = zipfileRead16(aRead);
  7481. pEOCD->nEntryTotal = zipfileRead16(aRead);
  7482. pEOCD->nSize = zipfileRead32(aRead);
  7483. pEOCD->iOffset = zipfileRead32(aRead);
  7484. }
  7485. return rc;
  7486. }
  7487. /*
  7488. ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
  7489. ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
  7490. ** to the end of the list. Otherwise, it is added to the list immediately
  7491. ** before pBefore (which is guaranteed to be a part of said list).
  7492. */
  7493. static void zipfileAddEntry(
  7494. ZipfileTab *pTab,
  7495. ZipfileEntry *pBefore,
  7496. ZipfileEntry *pNew
  7497. ){
  7498. assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
  7499. assert( pNew->pNext==0 );
  7500. if( pBefore==0 ){
  7501. if( pTab->pFirstEntry==0 ){
  7502. pTab->pFirstEntry = pTab->pLastEntry = pNew;
  7503. }else{
  7504. assert( pTab->pLastEntry->pNext==0 );
  7505. pTab->pLastEntry->pNext = pNew;
  7506. pTab->pLastEntry = pNew;
  7507. }
  7508. }else{
  7509. ZipfileEntry **pp;
  7510. for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
  7511. pNew->pNext = pBefore;
  7512. *pp = pNew;
  7513. }
  7514. }
  7515. static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
  7516. ZipfileEOCD eocd;
  7517. int rc;
  7518. int i;
  7519. i64 iOff;
  7520. rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
  7521. iOff = eocd.iOffset;
  7522. for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
  7523. ZipfileEntry *pNew = 0;
  7524. rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
  7525. if( rc==SQLITE_OK ){
  7526. zipfileAddEntry(pTab, 0, pNew);
  7527. iOff += ZIPFILE_CDS_FIXED_SZ;
  7528. iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
  7529. }
  7530. }
  7531. return rc;
  7532. }
  7533. /*
  7534. ** xFilter callback.
  7535. */
  7536. static int zipfileFilter(
  7537. sqlite3_vtab_cursor *cur,
  7538. int idxNum, const char *idxStr,
  7539. int argc, sqlite3_value **argv
  7540. ){
  7541. ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
  7542. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  7543. const char *zFile = 0; /* Zip file to scan */
  7544. int rc = SQLITE_OK; /* Return Code */
  7545. int bInMemory = 0; /* True for an in-memory zipfile */
  7546. zipfileResetCursor(pCsr);
  7547. if( pTab->zFile ){
  7548. zFile = pTab->zFile;
  7549. }else if( idxNum==0 ){
  7550. zipfileCursorErr(pCsr, "zipfile() function requires an argument");
  7551. return SQLITE_ERROR;
  7552. }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
  7553. static const u8 aEmptyBlob = 0;
  7554. const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
  7555. int nBlob = sqlite3_value_bytes(argv[0]);
  7556. assert( pTab->pFirstEntry==0 );
  7557. if( aBlob==0 ){
  7558. aBlob = &aEmptyBlob;
  7559. nBlob = 0;
  7560. }
  7561. rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
  7562. pCsr->pFreeEntry = pTab->pFirstEntry;
  7563. pTab->pFirstEntry = pTab->pLastEntry = 0;
  7564. if( rc!=SQLITE_OK ) return rc;
  7565. bInMemory = 1;
  7566. }else{
  7567. zFile = (const char*)sqlite3_value_text(argv[0]);
  7568. }
  7569. if( 0==pTab->pWriteFd && 0==bInMemory ){
  7570. pCsr->pFile = fopen(zFile, "rb");
  7571. if( pCsr->pFile==0 ){
  7572. zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
  7573. rc = SQLITE_ERROR;
  7574. }else{
  7575. rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
  7576. if( rc==SQLITE_OK ){
  7577. if( pCsr->eocd.nEntry==0 ){
  7578. pCsr->bEof = 1;
  7579. }else{
  7580. pCsr->iNextOff = pCsr->eocd.iOffset;
  7581. rc = zipfileNext(cur);
  7582. }
  7583. }
  7584. }
  7585. }else{
  7586. pCsr->bNoop = 1;
  7587. pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
  7588. rc = zipfileNext(cur);
  7589. }
  7590. return rc;
  7591. }
  7592. /*
  7593. ** xBestIndex callback.
  7594. */
  7595. static int zipfileBestIndex(
  7596. sqlite3_vtab *tab,
  7597. sqlite3_index_info *pIdxInfo
  7598. ){
  7599. int i;
  7600. int idx = -1;
  7601. int unusable = 0;
  7602. for(i=0; i<pIdxInfo->nConstraint; i++){
  7603. const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
  7604. if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
  7605. if( pCons->usable==0 ){
  7606. unusable = 1;
  7607. }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  7608. idx = i;
  7609. }
  7610. }
  7611. pIdxInfo->estimatedCost = 1000.0;
  7612. if( idx>=0 ){
  7613. pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
  7614. pIdxInfo->aConstraintUsage[idx].omit = 1;
  7615. pIdxInfo->idxNum = 1;
  7616. }else if( unusable ){
  7617. return SQLITE_CONSTRAINT;
  7618. }
  7619. return SQLITE_OK;
  7620. }
  7621. static ZipfileEntry *zipfileNewEntry(const char *zPath){
  7622. ZipfileEntry *pNew;
  7623. pNew = sqlite3_malloc(sizeof(ZipfileEntry));
  7624. if( pNew ){
  7625. memset(pNew, 0, sizeof(ZipfileEntry));
  7626. pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
  7627. if( pNew->cds.zFile==0 ){
  7628. sqlite3_free(pNew);
  7629. pNew = 0;
  7630. }
  7631. }
  7632. return pNew;
  7633. }
  7634. static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
  7635. ZipfileCDS *pCds = &pEntry->cds;
  7636. u8 *a = aBuf;
  7637. pCds->nExtra = 9;
  7638. /* Write the LFH itself */
  7639. zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
  7640. zipfileWrite16(a, pCds->iVersionExtract);
  7641. zipfileWrite16(a, pCds->flags);
  7642. zipfileWrite16(a, pCds->iCompression);
  7643. zipfileWrite16(a, pCds->mTime);
  7644. zipfileWrite16(a, pCds->mDate);
  7645. zipfileWrite32(a, pCds->crc32);
  7646. zipfileWrite32(a, pCds->szCompressed);
  7647. zipfileWrite32(a, pCds->szUncompressed);
  7648. zipfileWrite16(a, (u16)pCds->nFile);
  7649. zipfileWrite16(a, pCds->nExtra);
  7650. assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
  7651. /* Add the file name */
  7652. memcpy(a, pCds->zFile, (int)pCds->nFile);
  7653. a += (int)pCds->nFile;
  7654. /* The "extra" data */
  7655. zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
  7656. zipfileWrite16(a, 5);
  7657. *a++ = 0x01;
  7658. zipfileWrite32(a, pEntry->mUnixTime);
  7659. return a-aBuf;
  7660. }
  7661. static int zipfileAppendEntry(
  7662. ZipfileTab *pTab,
  7663. ZipfileEntry *pEntry,
  7664. const u8 *pData,
  7665. int nData
  7666. ){
  7667. u8 *aBuf = pTab->aBuffer;
  7668. int nBuf;
  7669. int rc;
  7670. nBuf = zipfileSerializeLFH(pEntry, aBuf);
  7671. rc = zipfileAppendData(pTab, aBuf, nBuf);
  7672. if( rc==SQLITE_OK ){
  7673. pEntry->iDataOff = pTab->szCurrent;
  7674. rc = zipfileAppendData(pTab, pData, nData);
  7675. }
  7676. return rc;
  7677. }
  7678. static int zipfileGetMode(
  7679. sqlite3_value *pVal,
  7680. int bIsDir, /* If true, default to directory */
  7681. u32 *pMode, /* OUT: Mode value */
  7682. char **pzErr /* OUT: Error message */
  7683. ){
  7684. const char *z = (const char*)sqlite3_value_text(pVal);
  7685. u32 mode = 0;
  7686. if( z==0 ){
  7687. mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
  7688. }else if( z[0]>='0' && z[0]<='9' ){
  7689. mode = (unsigned int)sqlite3_value_int(pVal);
  7690. }else{
  7691. const char zTemplate[11] = "-rwxrwxrwx";
  7692. int i;
  7693. if( strlen(z)!=10 ) goto parse_error;
  7694. switch( z[0] ){
  7695. case '-': mode |= S_IFREG; break;
  7696. case 'd': mode |= S_IFDIR; break;
  7697. case 'l': mode |= S_IFLNK; break;
  7698. default: goto parse_error;
  7699. }
  7700. for(i=1; i<10; i++){
  7701. if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
  7702. else if( z[i]!='-' ) goto parse_error;
  7703. }
  7704. }
  7705. if( ((mode & S_IFDIR)==0)==bIsDir ){
  7706. /* The "mode" attribute is a directory, but data has been specified.
  7707. ** Or vice-versa - no data but "mode" is a file or symlink. */
  7708. *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
  7709. return SQLITE_CONSTRAINT;
  7710. }
  7711. *pMode = mode;
  7712. return SQLITE_OK;
  7713. parse_error:
  7714. *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
  7715. return SQLITE_ERROR;
  7716. }
  7717. /*
  7718. ** Both (const char*) arguments point to nul-terminated strings. Argument
  7719. ** nB is the value of strlen(zB). This function returns 0 if the strings are
  7720. ** identical, ignoring any trailing '/' character in either path. */
  7721. static int zipfileComparePath(const char *zA, const char *zB, int nB){
  7722. int nA = (int)strlen(zA);
  7723. if( nA>0 && zA[nA-1]=='/' ) nA--;
  7724. if( nB>0 && zB[nB-1]=='/' ) nB--;
  7725. if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
  7726. return 1;
  7727. }
  7728. static int zipfileBegin(sqlite3_vtab *pVtab){
  7729. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  7730. int rc = SQLITE_OK;
  7731. assert( pTab->pWriteFd==0 );
  7732. if( pTab->zFile==0 || pTab->zFile[0]==0 ){
  7733. pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
  7734. return SQLITE_ERROR;
  7735. }
  7736. /* Open a write fd on the file. Also load the entire central directory
  7737. ** structure into memory. During the transaction any new file data is
  7738. ** appended to the archive file, but the central directory is accumulated
  7739. ** in main-memory until the transaction is committed. */
  7740. pTab->pWriteFd = fopen(pTab->zFile, "ab+");
  7741. if( pTab->pWriteFd==0 ){
  7742. pTab->base.zErrMsg = sqlite3_mprintf(
  7743. "zipfile: failed to open file %s for writing", pTab->zFile
  7744. );
  7745. rc = SQLITE_ERROR;
  7746. }else{
  7747. fseek(pTab->pWriteFd, 0, SEEK_END);
  7748. pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
  7749. rc = zipfileLoadDirectory(pTab, 0, 0);
  7750. }
  7751. if( rc!=SQLITE_OK ){
  7752. zipfileCleanupTransaction(pTab);
  7753. }
  7754. return rc;
  7755. }
  7756. /*
  7757. ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
  7758. ** time(2)).
  7759. */
  7760. static u32 zipfileTime(void){
  7761. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  7762. u32 ret;
  7763. if( pVfs==0 ) return 0;
  7764. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  7765. i64 ms;
  7766. pVfs->xCurrentTimeInt64(pVfs, &ms);
  7767. ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
  7768. }else{
  7769. double day;
  7770. pVfs->xCurrentTime(pVfs, &day);
  7771. ret = (u32)((day - 2440587.5) * 86400);
  7772. }
  7773. return ret;
  7774. }
  7775. /*
  7776. ** Return a 32-bit timestamp in UNIX epoch format.
  7777. **
  7778. ** If the value passed as the only argument is either NULL or an SQL NULL,
  7779. ** return the current time. Otherwise, return the value stored in (*pVal)
  7780. ** cast to a 32-bit unsigned integer.
  7781. */
  7782. static u32 zipfileGetTime(sqlite3_value *pVal){
  7783. if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
  7784. return zipfileTime();
  7785. }
  7786. return (u32)sqlite3_value_int64(pVal);
  7787. }
  7788. /*
  7789. ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
  7790. ** linked list. Remove it from the list and free the object.
  7791. */
  7792. static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
  7793. if( pOld ){
  7794. ZipfileEntry **pp;
  7795. for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
  7796. *pp = (*pp)->pNext;
  7797. zipfileEntryFree(pOld);
  7798. }
  7799. }
  7800. /*
  7801. ** xUpdate method.
  7802. */
  7803. static int zipfileUpdate(
  7804. sqlite3_vtab *pVtab,
  7805. int nVal,
  7806. sqlite3_value **apVal,
  7807. sqlite_int64 *pRowid
  7808. ){
  7809. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  7810. int rc = SQLITE_OK; /* Return Code */
  7811. ZipfileEntry *pNew = 0; /* New in-memory CDS entry */
  7812. u32 mode = 0; /* Mode for new entry */
  7813. u32 mTime = 0; /* Modification time for new entry */
  7814. i64 sz = 0; /* Uncompressed size */
  7815. const char *zPath = 0; /* Path for new entry */
  7816. int nPath = 0; /* strlen(zPath) */
  7817. const u8 *pData = 0; /* Pointer to buffer containing content */
  7818. int nData = 0; /* Size of pData buffer in bytes */
  7819. int iMethod = 0; /* Compression method for new entry */
  7820. u8 *pFree = 0; /* Free this */
  7821. char *zFree = 0; /* Also free this */
  7822. ZipfileEntry *pOld = 0;
  7823. ZipfileEntry *pOld2 = 0;
  7824. int bUpdate = 0; /* True for an update that modifies "name" */
  7825. int bIsDir = 0;
  7826. u32 iCrc32 = 0;
  7827. if( pTab->pWriteFd==0 ){
  7828. rc = zipfileBegin(pVtab);
  7829. if( rc!=SQLITE_OK ) return rc;
  7830. }
  7831. /* If this is a DELETE or UPDATE, find the archive entry to delete. */
  7832. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  7833. const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
  7834. int nDelete = (int)strlen(zDelete);
  7835. if( nVal>1 ){
  7836. const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
  7837. if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
  7838. bUpdate = 1;
  7839. }
  7840. }
  7841. for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
  7842. if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
  7843. break;
  7844. }
  7845. assert( pOld->pNext );
  7846. }
  7847. }
  7848. if( nVal>1 ){
  7849. /* Check that "sz" and "rawdata" are both NULL: */
  7850. if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
  7851. zipfileTableErr(pTab, "sz must be NULL");
  7852. rc = SQLITE_CONSTRAINT;
  7853. }
  7854. if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
  7855. zipfileTableErr(pTab, "rawdata must be NULL");
  7856. rc = SQLITE_CONSTRAINT;
  7857. }
  7858. if( rc==SQLITE_OK ){
  7859. if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
  7860. /* data=NULL. A directory */
  7861. bIsDir = 1;
  7862. }else{
  7863. /* Value specified for "data", and possibly "method". This must be
  7864. ** a regular file or a symlink. */
  7865. const u8 *aIn = sqlite3_value_blob(apVal[7]);
  7866. int nIn = sqlite3_value_bytes(apVal[7]);
  7867. int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
  7868. iMethod = sqlite3_value_int(apVal[8]);
  7869. sz = nIn;
  7870. pData = aIn;
  7871. nData = nIn;
  7872. if( iMethod!=0 && iMethod!=8 ){
  7873. zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
  7874. rc = SQLITE_CONSTRAINT;
  7875. }else{
  7876. if( bAuto || iMethod ){
  7877. int nCmp;
  7878. rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
  7879. if( rc==SQLITE_OK ){
  7880. if( iMethod || nCmp<nIn ){
  7881. iMethod = 8;
  7882. pData = pFree;
  7883. nData = nCmp;
  7884. }
  7885. }
  7886. }
  7887. iCrc32 = crc32(0, aIn, nIn);
  7888. }
  7889. }
  7890. }
  7891. if( rc==SQLITE_OK ){
  7892. rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
  7893. }
  7894. if( rc==SQLITE_OK ){
  7895. zPath = (const char*)sqlite3_value_text(apVal[2]);
  7896. if( zPath==0 ) zPath = "";
  7897. nPath = (int)strlen(zPath);
  7898. mTime = zipfileGetTime(apVal[4]);
  7899. }
  7900. if( rc==SQLITE_OK && bIsDir ){
  7901. /* For a directory, check that the last character in the path is a
  7902. ** '/'. This appears to be required for compatibility with info-zip
  7903. ** (the unzip command on unix). It does not create directories
  7904. ** otherwise. */
  7905. if( nPath<=0 || zPath[nPath-1]!='/' ){
  7906. zFree = sqlite3_mprintf("%s/", zPath);
  7907. zPath = (const char*)zFree;
  7908. if( zFree==0 ){
  7909. rc = SQLITE_NOMEM;
  7910. nPath = 0;
  7911. }else{
  7912. nPath = (int)strlen(zPath);
  7913. }
  7914. }
  7915. }
  7916. /* Check that we're not inserting a duplicate entry -OR- updating an
  7917. ** entry with a path, thereby making it into a duplicate. */
  7918. if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
  7919. ZipfileEntry *p;
  7920. for(p=pTab->pFirstEntry; p; p=p->pNext){
  7921. if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
  7922. switch( sqlite3_vtab_on_conflict(pTab->db) ){
  7923. case SQLITE_IGNORE: {
  7924. goto zipfile_update_done;
  7925. }
  7926. case SQLITE_REPLACE: {
  7927. pOld2 = p;
  7928. break;
  7929. }
  7930. default: {
  7931. zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
  7932. rc = SQLITE_CONSTRAINT;
  7933. break;
  7934. }
  7935. }
  7936. break;
  7937. }
  7938. }
  7939. }
  7940. if( rc==SQLITE_OK ){
  7941. /* Create the new CDS record. */
  7942. pNew = zipfileNewEntry(zPath);
  7943. if( pNew==0 ){
  7944. rc = SQLITE_NOMEM;
  7945. }else{
  7946. pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
  7947. pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
  7948. pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
  7949. pNew->cds.iCompression = (u16)iMethod;
  7950. zipfileMtimeToDos(&pNew->cds, mTime);
  7951. pNew->cds.crc32 = iCrc32;
  7952. pNew->cds.szCompressed = nData;
  7953. pNew->cds.szUncompressed = (u32)sz;
  7954. pNew->cds.iExternalAttr = (mode<<16);
  7955. pNew->cds.iOffset = (u32)pTab->szCurrent;
  7956. pNew->cds.nFile = (u16)nPath;
  7957. pNew->mUnixTime = (u32)mTime;
  7958. rc = zipfileAppendEntry(pTab, pNew, pData, nData);
  7959. zipfileAddEntry(pTab, pOld, pNew);
  7960. }
  7961. }
  7962. }
  7963. if( rc==SQLITE_OK && (pOld || pOld2) ){
  7964. ZipfileCsr *pCsr;
  7965. for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
  7966. if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
  7967. pCsr->pCurrent = pCsr->pCurrent->pNext;
  7968. pCsr->bNoop = 1;
  7969. }
  7970. }
  7971. zipfileRemoveEntryFromList(pTab, pOld);
  7972. zipfileRemoveEntryFromList(pTab, pOld2);
  7973. }
  7974. zipfile_update_done:
  7975. sqlite3_free(pFree);
  7976. sqlite3_free(zFree);
  7977. return rc;
  7978. }
  7979. static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
  7980. u8 *a = aBuf;
  7981. zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
  7982. zipfileWrite16(a, p->iDisk);
  7983. zipfileWrite16(a, p->iFirstDisk);
  7984. zipfileWrite16(a, p->nEntry);
  7985. zipfileWrite16(a, p->nEntryTotal);
  7986. zipfileWrite32(a, p->nSize);
  7987. zipfileWrite32(a, p->iOffset);
  7988. zipfileWrite16(a, 0); /* Size of trailing comment in bytes*/
  7989. return a-aBuf;
  7990. }
  7991. static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
  7992. int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
  7993. assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
  7994. return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
  7995. }
  7996. /*
  7997. ** Serialize the CDS structure into buffer aBuf[]. Return the number
  7998. ** of bytes written.
  7999. */
  8000. static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
  8001. u8 *a = aBuf;
  8002. ZipfileCDS *pCDS = &pEntry->cds;
  8003. if( pEntry->aExtra==0 ){
  8004. pCDS->nExtra = 9;
  8005. }
  8006. zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
  8007. zipfileWrite16(a, pCDS->iVersionMadeBy);
  8008. zipfileWrite16(a, pCDS->iVersionExtract);
  8009. zipfileWrite16(a, pCDS->flags);
  8010. zipfileWrite16(a, pCDS->iCompression);
  8011. zipfileWrite16(a, pCDS->mTime);
  8012. zipfileWrite16(a, pCDS->mDate);
  8013. zipfileWrite32(a, pCDS->crc32);
  8014. zipfileWrite32(a, pCDS->szCompressed);
  8015. zipfileWrite32(a, pCDS->szUncompressed);
  8016. assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
  8017. zipfileWrite16(a, pCDS->nFile);
  8018. zipfileWrite16(a, pCDS->nExtra);
  8019. zipfileWrite16(a, pCDS->nComment);
  8020. zipfileWrite16(a, pCDS->iDiskStart);
  8021. zipfileWrite16(a, pCDS->iInternalAttr);
  8022. zipfileWrite32(a, pCDS->iExternalAttr);
  8023. zipfileWrite32(a, pCDS->iOffset);
  8024. memcpy(a, pCDS->zFile, pCDS->nFile);
  8025. a += pCDS->nFile;
  8026. if( pEntry->aExtra ){
  8027. int n = (int)pCDS->nExtra + (int)pCDS->nComment;
  8028. memcpy(a, pEntry->aExtra, n);
  8029. a += n;
  8030. }else{
  8031. assert( pCDS->nExtra==9 );
  8032. zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
  8033. zipfileWrite16(a, 5);
  8034. *a++ = 0x01;
  8035. zipfileWrite32(a, pEntry->mUnixTime);
  8036. }
  8037. return a-aBuf;
  8038. }
  8039. static int zipfileCommit(sqlite3_vtab *pVtab){
  8040. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  8041. int rc = SQLITE_OK;
  8042. if( pTab->pWriteFd ){
  8043. i64 iOffset = pTab->szCurrent;
  8044. ZipfileEntry *p;
  8045. ZipfileEOCD eocd;
  8046. int nEntry = 0;
  8047. /* Write out all entries */
  8048. for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
  8049. int n = zipfileSerializeCDS(p, pTab->aBuffer);
  8050. rc = zipfileAppendData(pTab, pTab->aBuffer, n);
  8051. nEntry++;
  8052. }
  8053. /* Write out the EOCD record */
  8054. eocd.iDisk = 0;
  8055. eocd.iFirstDisk = 0;
  8056. eocd.nEntry = (u16)nEntry;
  8057. eocd.nEntryTotal = (u16)nEntry;
  8058. eocd.nSize = (u32)(pTab->szCurrent - iOffset);
  8059. eocd.iOffset = (u32)iOffset;
  8060. rc = zipfileAppendEOCD(pTab, &eocd);
  8061. zipfileCleanupTransaction(pTab);
  8062. }
  8063. return rc;
  8064. }
  8065. static int zipfileRollback(sqlite3_vtab *pVtab){
  8066. return zipfileCommit(pVtab);
  8067. }
  8068. static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
  8069. ZipfileCsr *pCsr;
  8070. for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
  8071. if( iId==pCsr->iId ) break;
  8072. }
  8073. return pCsr;
  8074. }
  8075. static void zipfileFunctionCds(
  8076. sqlite3_context *context,
  8077. int argc,
  8078. sqlite3_value **argv
  8079. ){
  8080. ZipfileCsr *pCsr;
  8081. ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
  8082. assert( argc>0 );
  8083. pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
  8084. if( pCsr ){
  8085. ZipfileCDS *p = &pCsr->pCurrent->cds;
  8086. char *zRes = sqlite3_mprintf("{"
  8087. "\"version-made-by\" : %u, "
  8088. "\"version-to-extract\" : %u, "
  8089. "\"flags\" : %u, "
  8090. "\"compression\" : %u, "
  8091. "\"time\" : %u, "
  8092. "\"date\" : %u, "
  8093. "\"crc32\" : %u, "
  8094. "\"compressed-size\" : %u, "
  8095. "\"uncompressed-size\" : %u, "
  8096. "\"file-name-length\" : %u, "
  8097. "\"extra-field-length\" : %u, "
  8098. "\"file-comment-length\" : %u, "
  8099. "\"disk-number-start\" : %u, "
  8100. "\"internal-attr\" : %u, "
  8101. "\"external-attr\" : %u, "
  8102. "\"offset\" : %u }",
  8103. (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
  8104. (u32)p->flags, (u32)p->iCompression,
  8105. (u32)p->mTime, (u32)p->mDate,
  8106. (u32)p->crc32, (u32)p->szCompressed,
  8107. (u32)p->szUncompressed, (u32)p->nFile,
  8108. (u32)p->nExtra, (u32)p->nComment,
  8109. (u32)p->iDiskStart, (u32)p->iInternalAttr,
  8110. (u32)p->iExternalAttr, (u32)p->iOffset
  8111. );
  8112. if( zRes==0 ){
  8113. sqlite3_result_error_nomem(context);
  8114. }else{
  8115. sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
  8116. sqlite3_free(zRes);
  8117. }
  8118. }
  8119. }
  8120. /*
  8121. ** xFindFunction method.
  8122. */
  8123. static int zipfileFindFunction(
  8124. sqlite3_vtab *pVtab, /* Virtual table handle */
  8125. int nArg, /* Number of SQL function arguments */
  8126. const char *zName, /* Name of SQL function */
  8127. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  8128. void **ppArg /* OUT: User data for *pxFunc */
  8129. ){
  8130. if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
  8131. *pxFunc = zipfileFunctionCds;
  8132. *ppArg = (void*)pVtab;
  8133. return 1;
  8134. }
  8135. return 0;
  8136. }
  8137. typedef struct ZipfileBuffer ZipfileBuffer;
  8138. struct ZipfileBuffer {
  8139. u8 *a; /* Pointer to buffer */
  8140. int n; /* Size of buffer in bytes */
  8141. int nAlloc; /* Byte allocated at a[] */
  8142. };
  8143. typedef struct ZipfileCtx ZipfileCtx;
  8144. struct ZipfileCtx {
  8145. int nEntry;
  8146. ZipfileBuffer body;
  8147. ZipfileBuffer cds;
  8148. };
  8149. static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
  8150. if( pBuf->n+nByte>pBuf->nAlloc ){
  8151. u8 *aNew;
  8152. sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
  8153. int nReq = pBuf->n + nByte;
  8154. while( nNew<nReq ) nNew = nNew*2;
  8155. aNew = sqlite3_realloc64(pBuf->a, nNew);
  8156. if( aNew==0 ) return SQLITE_NOMEM;
  8157. pBuf->a = aNew;
  8158. pBuf->nAlloc = (int)nNew;
  8159. }
  8160. return SQLITE_OK;
  8161. }
  8162. /*
  8163. ** xStep() callback for the zipfile() aggregate. This can be called in
  8164. ** any of the following ways:
  8165. **
  8166. ** SELECT zipfile(name,data) ...
  8167. ** SELECT zipfile(name,mode,mtime,data) ...
  8168. ** SELECT zipfile(name,mode,mtime,data,method) ...
  8169. */
  8170. static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
  8171. ZipfileCtx *p; /* Aggregate function context */
  8172. ZipfileEntry e; /* New entry to add to zip archive */
  8173. sqlite3_value *pName = 0;
  8174. sqlite3_value *pMode = 0;
  8175. sqlite3_value *pMtime = 0;
  8176. sqlite3_value *pData = 0;
  8177. sqlite3_value *pMethod = 0;
  8178. int bIsDir = 0;
  8179. u32 mode;
  8180. int rc = SQLITE_OK;
  8181. char *zErr = 0;
  8182. int iMethod = -1; /* Compression method to use (0 or 8) */
  8183. const u8 *aData = 0; /* Possibly compressed data for new entry */
  8184. int nData = 0; /* Size of aData[] in bytes */
  8185. int szUncompressed = 0; /* Size of data before compression */
  8186. u8 *aFree = 0; /* Free this before returning */
  8187. u32 iCrc32 = 0; /* crc32 of uncompressed data */
  8188. char *zName = 0; /* Path (name) of new entry */
  8189. int nName = 0; /* Size of zName in bytes */
  8190. char *zFree = 0; /* Free this before returning */
  8191. int nByte;
  8192. memset(&e, 0, sizeof(e));
  8193. p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
  8194. if( p==0 ) return;
  8195. /* Martial the arguments into stack variables */
  8196. if( nVal!=2 && nVal!=4 && nVal!=5 ){
  8197. zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
  8198. rc = SQLITE_ERROR;
  8199. goto zipfile_step_out;
  8200. }
  8201. pName = apVal[0];
  8202. if( nVal==2 ){
  8203. pData = apVal[1];
  8204. }else{
  8205. pMode = apVal[1];
  8206. pMtime = apVal[2];
  8207. pData = apVal[3];
  8208. if( nVal==5 ){
  8209. pMethod = apVal[4];
  8210. }
  8211. }
  8212. /* Check that the 'name' parameter looks ok. */
  8213. zName = (char*)sqlite3_value_text(pName);
  8214. nName = sqlite3_value_bytes(pName);
  8215. if( zName==0 ){
  8216. zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
  8217. rc = SQLITE_ERROR;
  8218. goto zipfile_step_out;
  8219. }
  8220. /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
  8221. ** deflate compression) or NULL (choose automatically). */
  8222. if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
  8223. iMethod = (int)sqlite3_value_int64(pMethod);
  8224. if( iMethod!=0 && iMethod!=8 ){
  8225. zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
  8226. rc = SQLITE_ERROR;
  8227. goto zipfile_step_out;
  8228. }
  8229. }
  8230. /* Now inspect the data. If this is NULL, then the new entry must be a
  8231. ** directory. Otherwise, figure out whether or not the data should
  8232. ** be deflated or simply stored in the zip archive. */
  8233. if( sqlite3_value_type(pData)==SQLITE_NULL ){
  8234. bIsDir = 1;
  8235. iMethod = 0;
  8236. }else{
  8237. aData = sqlite3_value_blob(pData);
  8238. szUncompressed = nData = sqlite3_value_bytes(pData);
  8239. iCrc32 = crc32(0, aData, nData);
  8240. if( iMethod<0 || iMethod==8 ){
  8241. int nOut = 0;
  8242. rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
  8243. if( rc!=SQLITE_OK ){
  8244. goto zipfile_step_out;
  8245. }
  8246. if( iMethod==8 || nOut<nData ){
  8247. aData = aFree;
  8248. nData = nOut;
  8249. iMethod = 8;
  8250. }else{
  8251. iMethod = 0;
  8252. }
  8253. }
  8254. }
  8255. /* Decode the "mode" argument. */
  8256. rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
  8257. if( rc ) goto zipfile_step_out;
  8258. /* Decode the "mtime" argument. */
  8259. e.mUnixTime = zipfileGetTime(pMtime);
  8260. /* If this is a directory entry, ensure that there is exactly one '/'
  8261. ** at the end of the path. Or, if this is not a directory and the path
  8262. ** ends in '/' it is an error. */
  8263. if( bIsDir==0 ){
  8264. if( nName>0 && zName[nName-1]=='/' ){
  8265. zErr = sqlite3_mprintf("non-directory name must not end with /");
  8266. rc = SQLITE_ERROR;
  8267. goto zipfile_step_out;
  8268. }
  8269. }else{
  8270. if( nName==0 || zName[nName-1]!='/' ){
  8271. zName = zFree = sqlite3_mprintf("%s/", zName);
  8272. if( zName==0 ){
  8273. rc = SQLITE_NOMEM;
  8274. goto zipfile_step_out;
  8275. }
  8276. nName = (int)strlen(zName);
  8277. }else{
  8278. while( nName>1 && zName[nName-2]=='/' ) nName--;
  8279. }
  8280. }
  8281. /* Assemble the ZipfileEntry object for the new zip archive entry */
  8282. e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
  8283. e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
  8284. e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
  8285. e.cds.iCompression = (u16)iMethod;
  8286. zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
  8287. e.cds.crc32 = iCrc32;
  8288. e.cds.szCompressed = nData;
  8289. e.cds.szUncompressed = szUncompressed;
  8290. e.cds.iExternalAttr = (mode<<16);
  8291. e.cds.iOffset = p->body.n;
  8292. e.cds.nFile = (u16)nName;
  8293. e.cds.zFile = zName;
  8294. /* Append the LFH to the body of the new archive */
  8295. nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
  8296. if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
  8297. p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
  8298. /* Append the data to the body of the new archive */
  8299. if( nData>0 ){
  8300. if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
  8301. memcpy(&p->body.a[p->body.n], aData, nData);
  8302. p->body.n += nData;
  8303. }
  8304. /* Append the CDS record to the directory of the new archive */
  8305. nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
  8306. if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
  8307. p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
  8308. /* Increment the count of entries in the archive */
  8309. p->nEntry++;
  8310. zipfile_step_out:
  8311. sqlite3_free(aFree);
  8312. sqlite3_free(zFree);
  8313. if( rc ){
  8314. if( zErr ){
  8315. sqlite3_result_error(pCtx, zErr, -1);
  8316. }else{
  8317. sqlite3_result_error_code(pCtx, rc);
  8318. }
  8319. }
  8320. sqlite3_free(zErr);
  8321. }
  8322. /*
  8323. ** xFinalize() callback for zipfile aggregate function.
  8324. */
  8325. static void zipfileFinal(sqlite3_context *pCtx){
  8326. ZipfileCtx *p;
  8327. ZipfileEOCD eocd;
  8328. sqlite3_int64 nZip;
  8329. u8 *aZip;
  8330. p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
  8331. if( p==0 ) return;
  8332. if( p->nEntry>0 ){
  8333. memset(&eocd, 0, sizeof(eocd));
  8334. eocd.nEntry = (u16)p->nEntry;
  8335. eocd.nEntryTotal = (u16)p->nEntry;
  8336. eocd.nSize = p->cds.n;
  8337. eocd.iOffset = p->body.n;
  8338. nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
  8339. aZip = (u8*)sqlite3_malloc64(nZip);
  8340. if( aZip==0 ){
  8341. sqlite3_result_error_nomem(pCtx);
  8342. }else{
  8343. memcpy(aZip, p->body.a, p->body.n);
  8344. memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
  8345. zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
  8346. sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
  8347. }
  8348. }
  8349. sqlite3_free(p->body.a);
  8350. sqlite3_free(p->cds.a);
  8351. }
  8352. /*
  8353. ** Register the "zipfile" virtual table.
  8354. */
  8355. static int zipfileRegister(sqlite3 *db){
  8356. static sqlite3_module zipfileModule = {
  8357. 1, /* iVersion */
  8358. zipfileConnect, /* xCreate */
  8359. zipfileConnect, /* xConnect */
  8360. zipfileBestIndex, /* xBestIndex */
  8361. zipfileDisconnect, /* xDisconnect */
  8362. zipfileDisconnect, /* xDestroy */
  8363. zipfileOpen, /* xOpen - open a cursor */
  8364. zipfileClose, /* xClose - close a cursor */
  8365. zipfileFilter, /* xFilter - configure scan constraints */
  8366. zipfileNext, /* xNext - advance a cursor */
  8367. zipfileEof, /* xEof - check for end of scan */
  8368. zipfileColumn, /* xColumn - read data */
  8369. 0, /* xRowid - read data */
  8370. zipfileUpdate, /* xUpdate */
  8371. zipfileBegin, /* xBegin */
  8372. 0, /* xSync */
  8373. zipfileCommit, /* xCommit */
  8374. zipfileRollback, /* xRollback */
  8375. zipfileFindFunction, /* xFindMethod */
  8376. 0, /* xRename */
  8377. 0, /* xSavepoint */
  8378. 0, /* xRelease */
  8379. 0, /* xRollback */
  8380. 0 /* xShadowName */
  8381. };
  8382. int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0);
  8383. if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
  8384. if( rc==SQLITE_OK ){
  8385. rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
  8386. zipfileStep, zipfileFinal
  8387. );
  8388. }
  8389. assert( sizeof(i64)==8 );
  8390. assert( sizeof(u32)==4 );
  8391. assert( sizeof(u16)==2 );
  8392. assert( sizeof(u8)==1 );
  8393. return rc;
  8394. }
  8395. #else /* SQLITE_OMIT_VIRTUALTABLE */
  8396. # define zipfileRegister(x) SQLITE_OK
  8397. #endif
  8398. #ifdef _WIN32
  8399. #endif
  8400. int sqlite3_zipfile_init(
  8401. sqlite3 *db,
  8402. char **pzErrMsg,
  8403. const sqlite3_api_routines *pApi
  8404. ){
  8405. SQLITE_EXTENSION_INIT2(pApi);
  8406. (void)pzErrMsg; /* Unused parameter */
  8407. return zipfileRegister(db);
  8408. }
  8409. /************************* End ../ext/misc/zipfile.c ********************/
  8410. /************************* Begin ../ext/misc/sqlar.c ******************/
  8411. /*
  8412. ** 2017-12-17
  8413. **
  8414. ** The author disclaims copyright to this source code. In place of
  8415. ** a legal notice, here is a blessing:
  8416. **
  8417. ** May you do good and not evil.
  8418. ** May you find forgiveness for yourself and forgive others.
  8419. ** May you share freely, never taking more than you give.
  8420. **
  8421. ******************************************************************************
  8422. **
  8423. ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
  8424. ** for working with sqlar archives and used by the shell tool's built-in
  8425. ** sqlar support.
  8426. */
  8427. /* #include "sqlite3ext.h" */
  8428. SQLITE_EXTENSION_INIT1
  8429. #include <zlib.h>
  8430. #include <assert.h>
  8431. /*
  8432. ** Implementation of the "sqlar_compress(X)" SQL function.
  8433. **
  8434. ** If the type of X is SQLITE_BLOB, and compressing that blob using
  8435. ** zlib utility function compress() yields a smaller blob, return the
  8436. ** compressed blob. Otherwise, return a copy of X.
  8437. **
  8438. ** SQLar uses the "zlib format" for compressed content. The zlib format
  8439. ** contains a two-byte identification header and a four-byte checksum at
  8440. ** the end. This is different from ZIP which uses the raw deflate format.
  8441. **
  8442. ** Future enhancements to SQLar might add support for new compression formats.
  8443. ** If so, those new formats will be identified by alternative headers in the
  8444. ** compressed data.
  8445. */
  8446. static void sqlarCompressFunc(
  8447. sqlite3_context *context,
  8448. int argc,
  8449. sqlite3_value **argv
  8450. ){
  8451. assert( argc==1 );
  8452. if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
  8453. const Bytef *pData = sqlite3_value_blob(argv[0]);
  8454. uLong nData = sqlite3_value_bytes(argv[0]);
  8455. uLongf nOut = compressBound(nData);
  8456. Bytef *pOut;
  8457. pOut = (Bytef*)sqlite3_malloc(nOut);
  8458. if( pOut==0 ){
  8459. sqlite3_result_error_nomem(context);
  8460. return;
  8461. }else{
  8462. if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
  8463. sqlite3_result_error(context, "error in compress()", -1);
  8464. }else if( nOut<nData ){
  8465. sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
  8466. }else{
  8467. sqlite3_result_value(context, argv[0]);
  8468. }
  8469. sqlite3_free(pOut);
  8470. }
  8471. }else{
  8472. sqlite3_result_value(context, argv[0]);
  8473. }
  8474. }
  8475. /*
  8476. ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
  8477. **
  8478. ** Parameter SZ is interpreted as an integer. If it is less than or
  8479. ** equal to zero, then this function returns a copy of X. Or, if
  8480. ** SZ is equal to the size of X when interpreted as a blob, also
  8481. ** return a copy of X. Otherwise, decompress blob X using zlib
  8482. ** utility function uncompress() and return the results (another
  8483. ** blob).
  8484. */
  8485. static void sqlarUncompressFunc(
  8486. sqlite3_context *context,
  8487. int argc,
  8488. sqlite3_value **argv
  8489. ){
  8490. uLong nData;
  8491. uLongf sz;
  8492. assert( argc==2 );
  8493. sz = sqlite3_value_int(argv[1]);
  8494. if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
  8495. sqlite3_result_value(context, argv[0]);
  8496. }else{
  8497. const Bytef *pData= sqlite3_value_blob(argv[0]);
  8498. Bytef *pOut = sqlite3_malloc(sz);
  8499. if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
  8500. sqlite3_result_error(context, "error in uncompress()", -1);
  8501. }else{
  8502. sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
  8503. }
  8504. sqlite3_free(pOut);
  8505. }
  8506. }
  8507. #ifdef _WIN32
  8508. #endif
  8509. int sqlite3_sqlar_init(
  8510. sqlite3 *db,
  8511. char **pzErrMsg,
  8512. const sqlite3_api_routines *pApi
  8513. ){
  8514. int rc = SQLITE_OK;
  8515. SQLITE_EXTENSION_INIT2(pApi);
  8516. (void)pzErrMsg; /* Unused parameter */
  8517. rc = sqlite3_create_function(db, "sqlar_compress", 1,
  8518. SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
  8519. sqlarCompressFunc, 0, 0);
  8520. if( rc==SQLITE_OK ){
  8521. rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
  8522. SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
  8523. sqlarUncompressFunc, 0, 0);
  8524. }
  8525. return rc;
  8526. }
  8527. /************************* End ../ext/misc/sqlar.c ********************/
  8528. #endif
  8529. /************************* Begin ../ext/expert/sqlite3expert.h ******************/
  8530. /*
  8531. ** 2017 April 07
  8532. **
  8533. ** The author disclaims copyright to this source code. In place of
  8534. ** a legal notice, here is a blessing:
  8535. **
  8536. ** May you do good and not evil.
  8537. ** May you find forgiveness for yourself and forgive others.
  8538. ** May you share freely, never taking more than you give.
  8539. **
  8540. *************************************************************************
  8541. */
  8542. #if !defined(SQLITEEXPERT_H)
  8543. #define SQLITEEXPERT_H 1
  8544. /* #include "sqlite3.h" */
  8545. typedef struct sqlite3expert sqlite3expert;
  8546. /*
  8547. ** Create a new sqlite3expert object.
  8548. **
  8549. ** If successful, a pointer to the new object is returned and (*pzErr) set
  8550. ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
  8551. ** an English-language error message. In this case it is the responsibility
  8552. ** of the caller to eventually free the error message buffer using
  8553. ** sqlite3_free().
  8554. */
  8555. sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
  8556. /*
  8557. ** Configure an sqlite3expert object.
  8558. **
  8559. ** EXPERT_CONFIG_SAMPLE:
  8560. ** By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
  8561. ** each candidate index. This involves scanning and sorting the entire
  8562. ** contents of each user database table once for each candidate index
  8563. ** associated with the table. For large databases, this can be
  8564. ** prohibitively slow. This option allows the sqlite3expert object to
  8565. ** be configured so that sqlite_stat1 data is instead generated based on a
  8566. ** subset of each table, or so that no sqlite_stat1 data is used at all.
  8567. **
  8568. ** A single integer argument is passed to this option. If the value is less
  8569. ** than or equal to zero, then no sqlite_stat1 data is generated or used by
  8570. ** the analysis - indexes are recommended based on the database schema only.
  8571. ** Or, if the value is 100 or greater, complete sqlite_stat1 data is
  8572. ** generated for each candidate index (this is the default). Finally, if the
  8573. ** value falls between 0 and 100, then it represents the percentage of user
  8574. ** table rows that should be considered when generating sqlite_stat1 data.
  8575. **
  8576. ** Examples:
  8577. **
  8578. ** // Do not generate any sqlite_stat1 data
  8579. ** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
  8580. **
  8581. ** // Generate sqlite_stat1 data based on 10% of the rows in each table.
  8582. ** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
  8583. */
  8584. int sqlite3_expert_config(sqlite3expert *p, int op, ...);
  8585. #define EXPERT_CONFIG_SAMPLE 1 /* int */
  8586. /*
  8587. ** Specify zero or more SQL statements to be included in the analysis.
  8588. **
  8589. ** Buffer zSql must contain zero or more complete SQL statements. This
  8590. ** function parses all statements contained in the buffer and adds them
  8591. ** to the internal list of statements to analyze. If successful, SQLITE_OK
  8592. ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
  8593. ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
  8594. ** may be set to point to an English language error message. In this case
  8595. ** the caller is responsible for eventually freeing the error message buffer
  8596. ** using sqlite3_free().
  8597. **
  8598. ** If an error does occur while processing one of the statements in the
  8599. ** buffer passed as the second argument, none of the statements in the
  8600. ** buffer are added to the analysis.
  8601. **
  8602. ** This function must be called before sqlite3_expert_analyze(). If a call
  8603. ** to this function is made on an sqlite3expert object that has already
  8604. ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
  8605. ** immediately and no statements are added to the analysis.
  8606. */
  8607. int sqlite3_expert_sql(
  8608. sqlite3expert *p, /* From a successful sqlite3_expert_new() */
  8609. const char *zSql, /* SQL statement(s) to add */
  8610. char **pzErr /* OUT: Error message (if any) */
  8611. );
  8612. /*
  8613. ** This function is called after the sqlite3expert object has been configured
  8614. ** with all SQL statements using sqlite3_expert_sql() to actually perform
  8615. ** the analysis. Once this function has been called, it is not possible to
  8616. ** add further SQL statements to the analysis.
  8617. **
  8618. ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
  8619. ** an error occurs, an SQLite error code is returned and (*pzErr) set to
  8620. ** point to a buffer containing an English language error message. In this
  8621. ** case it is the responsibility of the caller to eventually free the buffer
  8622. ** using sqlite3_free().
  8623. **
  8624. ** If an error does occur within this function, the sqlite3expert object
  8625. ** is no longer useful for any purpose. At that point it is no longer
  8626. ** possible to add further SQL statements to the object or to re-attempt
  8627. ** the analysis. The sqlite3expert object must still be freed using a call
  8628. ** sqlite3_expert_destroy().
  8629. */
  8630. int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
  8631. /*
  8632. ** Return the total number of statements loaded using sqlite3_expert_sql().
  8633. ** The total number of SQL statements may be different from the total number
  8634. ** to calls to sqlite3_expert_sql().
  8635. */
  8636. int sqlite3_expert_count(sqlite3expert*);
  8637. /*
  8638. ** Return a component of the report.
  8639. **
  8640. ** This function is called after sqlite3_expert_analyze() to extract the
  8641. ** results of the analysis. Each call to this function returns either a
  8642. ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
  8643. ** The value passed as the third argument must be one of the EXPERT_REPORT_*
  8644. ** #define constants defined below.
  8645. **
  8646. ** For some EXPERT_REPORT_* parameters, the buffer returned contains
  8647. ** information relating to a specific SQL statement. In these cases that
  8648. ** SQL statement is identified by the value passed as the second argument.
  8649. ** SQL statements are numbered from 0 in the order in which they are parsed.
  8650. ** If an out-of-range value (less than zero or equal to or greater than the
  8651. ** value returned by sqlite3_expert_count()) is passed as the second argument
  8652. ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
  8653. **
  8654. ** EXPERT_REPORT_SQL:
  8655. ** Return the text of SQL statement iStmt.
  8656. **
  8657. ** EXPERT_REPORT_INDEXES:
  8658. ** Return a buffer containing the CREATE INDEX statements for all recommended
  8659. ** indexes for statement iStmt. If there are no new recommeded indexes, NULL
  8660. ** is returned.
  8661. **
  8662. ** EXPERT_REPORT_PLAN:
  8663. ** Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
  8664. ** iStmt after the proposed indexes have been added to the database schema.
  8665. **
  8666. ** EXPERT_REPORT_CANDIDATES:
  8667. ** Return a pointer to a buffer containing the CREATE INDEX statements
  8668. ** for all indexes that were tested (for all SQL statements). The iStmt
  8669. ** parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
  8670. */
  8671. const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
  8672. /*
  8673. ** Values for the third argument passed to sqlite3_expert_report().
  8674. */
  8675. #define EXPERT_REPORT_SQL 1
  8676. #define EXPERT_REPORT_INDEXES 2
  8677. #define EXPERT_REPORT_PLAN 3
  8678. #define EXPERT_REPORT_CANDIDATES 4
  8679. /*
  8680. ** Free an (sqlite3expert*) handle and all associated resources. There
  8681. ** should be one call to this function for each successful call to
  8682. ** sqlite3-expert_new().
  8683. */
  8684. void sqlite3_expert_destroy(sqlite3expert*);
  8685. #endif /* !defined(SQLITEEXPERT_H) */
  8686. /************************* End ../ext/expert/sqlite3expert.h ********************/
  8687. /************************* Begin ../ext/expert/sqlite3expert.c ******************/
  8688. /*
  8689. ** 2017 April 09
  8690. **
  8691. ** The author disclaims copyright to this source code. In place of
  8692. ** a legal notice, here is a blessing:
  8693. **
  8694. ** May you do good and not evil.
  8695. ** May you find forgiveness for yourself and forgive others.
  8696. ** May you share freely, never taking more than you give.
  8697. **
  8698. *************************************************************************
  8699. */
  8700. /* #include "sqlite3expert.h" */
  8701. #include <assert.h>
  8702. #include <string.h>
  8703. #include <stdio.h>
  8704. #if !defined(SQLITE_AMALGAMATION)
  8705. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  8706. # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
  8707. #endif
  8708. #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
  8709. # define ALWAYS(X) (1)
  8710. # define NEVER(X) (0)
  8711. #elif !defined(NDEBUG)
  8712. # define ALWAYS(X) ((X)?1:(assert(0),0))
  8713. # define NEVER(X) ((X)?(assert(0),1):0)
  8714. #else
  8715. # define ALWAYS(X) (X)
  8716. # define NEVER(X) (X)
  8717. #endif
  8718. #endif /* !defined(SQLITE_AMALGAMATION) */
  8719. #ifndef SQLITE_OMIT_VIRTUALTABLE
  8720. /* typedef sqlite3_int64 i64; */
  8721. /* typedef sqlite3_uint64 u64; */
  8722. typedef struct IdxColumn IdxColumn;
  8723. typedef struct IdxConstraint IdxConstraint;
  8724. typedef struct IdxScan IdxScan;
  8725. typedef struct IdxStatement IdxStatement;
  8726. typedef struct IdxTable IdxTable;
  8727. typedef struct IdxWrite IdxWrite;
  8728. #define STRLEN (int)strlen
  8729. /*
  8730. ** A temp table name that we assume no user database will actually use.
  8731. ** If this assumption proves incorrect triggers on the table with the
  8732. ** conflicting name will be ignored.
  8733. */
  8734. #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
  8735. /*
  8736. ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
  8737. ** any other type of single-ended range constraint on a column).
  8738. **
  8739. ** pLink:
  8740. ** Used to temporarily link IdxConstraint objects into lists while
  8741. ** creating candidate indexes.
  8742. */
  8743. struct IdxConstraint {
  8744. char *zColl; /* Collation sequence */
  8745. int bRange; /* True for range, false for eq */
  8746. int iCol; /* Constrained table column */
  8747. int bFlag; /* Used by idxFindCompatible() */
  8748. int bDesc; /* True if ORDER BY <expr> DESC */
  8749. IdxConstraint *pNext; /* Next constraint in pEq or pRange list */
  8750. IdxConstraint *pLink; /* See above */
  8751. };
  8752. /*
  8753. ** A single scan of a single table.
  8754. */
  8755. struct IdxScan {
  8756. IdxTable *pTab; /* Associated table object */
  8757. int iDb; /* Database containing table zTable */
  8758. i64 covering; /* Mask of columns required for cov. index */
  8759. IdxConstraint *pOrder; /* ORDER BY columns */
  8760. IdxConstraint *pEq; /* List of == constraints */
  8761. IdxConstraint *pRange; /* List of < constraints */
  8762. IdxScan *pNextScan; /* Next IdxScan object for same analysis */
  8763. };
  8764. /*
  8765. ** Information regarding a single database table. Extracted from
  8766. ** "PRAGMA table_info" by function idxGetTableInfo().
  8767. */
  8768. struct IdxColumn {
  8769. char *zName;
  8770. char *zColl;
  8771. int iPk;
  8772. };
  8773. struct IdxTable {
  8774. int nCol;
  8775. char *zName; /* Table name */
  8776. IdxColumn *aCol;
  8777. IdxTable *pNext; /* Next table in linked list of all tables */
  8778. };
  8779. /*
  8780. ** An object of the following type is created for each unique table/write-op
  8781. ** seen. The objects are stored in a singly-linked list beginning at
  8782. ** sqlite3expert.pWrite.
  8783. */
  8784. struct IdxWrite {
  8785. IdxTable *pTab;
  8786. int eOp; /* SQLITE_UPDATE, DELETE or INSERT */
  8787. IdxWrite *pNext;
  8788. };
  8789. /*
  8790. ** Each statement being analyzed is represented by an instance of this
  8791. ** structure.
  8792. */
  8793. struct IdxStatement {
  8794. int iId; /* Statement number */
  8795. char *zSql; /* SQL statement */
  8796. char *zIdx; /* Indexes */
  8797. char *zEQP; /* Plan */
  8798. IdxStatement *pNext;
  8799. };
  8800. /*
  8801. ** A hash table for storing strings. With space for a payload string
  8802. ** with each entry. Methods are:
  8803. **
  8804. ** idxHashInit()
  8805. ** idxHashClear()
  8806. ** idxHashAdd()
  8807. ** idxHashSearch()
  8808. */
  8809. #define IDX_HASH_SIZE 1023
  8810. typedef struct IdxHashEntry IdxHashEntry;
  8811. typedef struct IdxHash IdxHash;
  8812. struct IdxHashEntry {
  8813. char *zKey; /* nul-terminated key */
  8814. char *zVal; /* nul-terminated value string */
  8815. char *zVal2; /* nul-terminated value string 2 */
  8816. IdxHashEntry *pHashNext; /* Next entry in same hash bucket */
  8817. IdxHashEntry *pNext; /* Next entry in hash */
  8818. };
  8819. struct IdxHash {
  8820. IdxHashEntry *pFirst;
  8821. IdxHashEntry *aHash[IDX_HASH_SIZE];
  8822. };
  8823. /*
  8824. ** sqlite3expert object.
  8825. */
  8826. struct sqlite3expert {
  8827. int iSample; /* Percentage of tables to sample for stat1 */
  8828. sqlite3 *db; /* User database */
  8829. sqlite3 *dbm; /* In-memory db for this analysis */
  8830. sqlite3 *dbv; /* Vtab schema for this analysis */
  8831. IdxTable *pTable; /* List of all IdxTable objects */
  8832. IdxScan *pScan; /* List of scan objects */
  8833. IdxWrite *pWrite; /* List of write objects */
  8834. IdxStatement *pStatement; /* List of IdxStatement objects */
  8835. int bRun; /* True once analysis has run */
  8836. char **pzErrmsg;
  8837. int rc; /* Error code from whereinfo hook */
  8838. IdxHash hIdx; /* Hash containing all candidate indexes */
  8839. char *zCandidates; /* For EXPERT_REPORT_CANDIDATES */
  8840. };
  8841. /*
  8842. ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
  8843. ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
  8844. */
  8845. static void *idxMalloc(int *pRc, int nByte){
  8846. void *pRet;
  8847. assert( *pRc==SQLITE_OK );
  8848. assert( nByte>0 );
  8849. pRet = sqlite3_malloc(nByte);
  8850. if( pRet ){
  8851. memset(pRet, 0, nByte);
  8852. }else{
  8853. *pRc = SQLITE_NOMEM;
  8854. }
  8855. return pRet;
  8856. }
  8857. /*
  8858. ** Initialize an IdxHash hash table.
  8859. */
  8860. static void idxHashInit(IdxHash *pHash){
  8861. memset(pHash, 0, sizeof(IdxHash));
  8862. }
  8863. /*
  8864. ** Reset an IdxHash hash table.
  8865. */
  8866. static void idxHashClear(IdxHash *pHash){
  8867. int i;
  8868. for(i=0; i<IDX_HASH_SIZE; i++){
  8869. IdxHashEntry *pEntry;
  8870. IdxHashEntry *pNext;
  8871. for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
  8872. pNext = pEntry->pHashNext;
  8873. sqlite3_free(pEntry->zVal2);
  8874. sqlite3_free(pEntry);
  8875. }
  8876. }
  8877. memset(pHash, 0, sizeof(IdxHash));
  8878. }
  8879. /*
  8880. ** Return the index of the hash bucket that the string specified by the
  8881. ** arguments to this function belongs.
  8882. */
  8883. static int idxHashString(const char *z, int n){
  8884. unsigned int ret = 0;
  8885. int i;
  8886. for(i=0; i<n; i++){
  8887. ret += (ret<<3) + (unsigned char)(z[i]);
  8888. }
  8889. return (int)(ret % IDX_HASH_SIZE);
  8890. }
  8891. /*
  8892. ** If zKey is already present in the hash table, return non-zero and do
  8893. ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
  8894. ** the hash table passed as the second argument.
  8895. */
  8896. static int idxHashAdd(
  8897. int *pRc,
  8898. IdxHash *pHash,
  8899. const char *zKey,
  8900. const char *zVal
  8901. ){
  8902. int nKey = STRLEN(zKey);
  8903. int iHash = idxHashString(zKey, nKey);
  8904. int nVal = (zVal ? STRLEN(zVal) : 0);
  8905. IdxHashEntry *pEntry;
  8906. assert( iHash>=0 );
  8907. for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
  8908. if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
  8909. return 1;
  8910. }
  8911. }
  8912. pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
  8913. if( pEntry ){
  8914. pEntry->zKey = (char*)&pEntry[1];
  8915. memcpy(pEntry->zKey, zKey, nKey);
  8916. if( zVal ){
  8917. pEntry->zVal = &pEntry->zKey[nKey+1];
  8918. memcpy(pEntry->zVal, zVal, nVal);
  8919. }
  8920. pEntry->pHashNext = pHash->aHash[iHash];
  8921. pHash->aHash[iHash] = pEntry;
  8922. pEntry->pNext = pHash->pFirst;
  8923. pHash->pFirst = pEntry;
  8924. }
  8925. return 0;
  8926. }
  8927. /*
  8928. ** If zKey/nKey is present in the hash table, return a pointer to the
  8929. ** hash-entry object.
  8930. */
  8931. static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
  8932. int iHash;
  8933. IdxHashEntry *pEntry;
  8934. if( nKey<0 ) nKey = STRLEN(zKey);
  8935. iHash = idxHashString(zKey, nKey);
  8936. assert( iHash>=0 );
  8937. for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
  8938. if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
  8939. return pEntry;
  8940. }
  8941. }
  8942. return 0;
  8943. }
  8944. /*
  8945. ** If the hash table contains an entry with a key equal to the string
  8946. ** passed as the final two arguments to this function, return a pointer
  8947. ** to the payload string. Otherwise, if zKey/nKey is not present in the
  8948. ** hash table, return NULL.
  8949. */
  8950. static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
  8951. IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
  8952. if( pEntry ) return pEntry->zVal;
  8953. return 0;
  8954. }
  8955. /*
  8956. ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
  8957. ** variable to point to a copy of nul-terminated string zColl.
  8958. */
  8959. static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
  8960. IdxConstraint *pNew;
  8961. int nColl = STRLEN(zColl);
  8962. assert( *pRc==SQLITE_OK );
  8963. pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
  8964. if( pNew ){
  8965. pNew->zColl = (char*)&pNew[1];
  8966. memcpy(pNew->zColl, zColl, nColl+1);
  8967. }
  8968. return pNew;
  8969. }
  8970. /*
  8971. ** An error associated with database handle db has just occurred. Pass
  8972. ** the error message to callback function xOut.
  8973. */
  8974. static void idxDatabaseError(
  8975. sqlite3 *db, /* Database handle */
  8976. char **pzErrmsg /* Write error here */
  8977. ){
  8978. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  8979. }
  8980. /*
  8981. ** Prepare an SQL statement.
  8982. */
  8983. static int idxPrepareStmt(
  8984. sqlite3 *db, /* Database handle to compile against */
  8985. sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
  8986. char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
  8987. const char *zSql /* SQL statement to compile */
  8988. ){
  8989. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  8990. if( rc!=SQLITE_OK ){
  8991. *ppStmt = 0;
  8992. idxDatabaseError(db, pzErrmsg);
  8993. }
  8994. return rc;
  8995. }
  8996. /*
  8997. ** Prepare an SQL statement using the results of a printf() formatting.
  8998. */
  8999. static int idxPrintfPrepareStmt(
  9000. sqlite3 *db, /* Database handle to compile against */
  9001. sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
  9002. char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
  9003. const char *zFmt, /* printf() format of SQL statement */
  9004. ... /* Trailing printf() arguments */
  9005. ){
  9006. va_list ap;
  9007. int rc;
  9008. char *zSql;
  9009. va_start(ap, zFmt);
  9010. zSql = sqlite3_vmprintf(zFmt, ap);
  9011. if( zSql==0 ){
  9012. rc = SQLITE_NOMEM;
  9013. }else{
  9014. rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
  9015. sqlite3_free(zSql);
  9016. }
  9017. va_end(ap);
  9018. return rc;
  9019. }
  9020. /*************************************************************************
  9021. ** Beginning of virtual table implementation.
  9022. */
  9023. typedef struct ExpertVtab ExpertVtab;
  9024. struct ExpertVtab {
  9025. sqlite3_vtab base;
  9026. IdxTable *pTab;
  9027. sqlite3expert *pExpert;
  9028. };
  9029. typedef struct ExpertCsr ExpertCsr;
  9030. struct ExpertCsr {
  9031. sqlite3_vtab_cursor base;
  9032. sqlite3_stmt *pData;
  9033. };
  9034. static char *expertDequote(const char *zIn){
  9035. int n = STRLEN(zIn);
  9036. char *zRet = sqlite3_malloc(n);
  9037. assert( zIn[0]=='\'' );
  9038. assert( zIn[n-1]=='\'' );
  9039. if( zRet ){
  9040. int iOut = 0;
  9041. int iIn = 0;
  9042. for(iIn=1; iIn<(n-1); iIn++){
  9043. if( zIn[iIn]=='\'' ){
  9044. assert( zIn[iIn+1]=='\'' );
  9045. iIn++;
  9046. }
  9047. zRet[iOut++] = zIn[iIn];
  9048. }
  9049. zRet[iOut] = '\0';
  9050. }
  9051. return zRet;
  9052. }
  9053. /*
  9054. ** This function is the implementation of both the xConnect and xCreate
  9055. ** methods of the r-tree virtual table.
  9056. **
  9057. ** argv[0] -> module name
  9058. ** argv[1] -> database name
  9059. ** argv[2] -> table name
  9060. ** argv[...] -> column names...
  9061. */
  9062. static int expertConnect(
  9063. sqlite3 *db,
  9064. void *pAux,
  9065. int argc, const char *const*argv,
  9066. sqlite3_vtab **ppVtab,
  9067. char **pzErr
  9068. ){
  9069. sqlite3expert *pExpert = (sqlite3expert*)pAux;
  9070. ExpertVtab *p = 0;
  9071. int rc;
  9072. if( argc!=4 ){
  9073. *pzErr = sqlite3_mprintf("internal error!");
  9074. rc = SQLITE_ERROR;
  9075. }else{
  9076. char *zCreateTable = expertDequote(argv[3]);
  9077. if( zCreateTable ){
  9078. rc = sqlite3_declare_vtab(db, zCreateTable);
  9079. if( rc==SQLITE_OK ){
  9080. p = idxMalloc(&rc, sizeof(ExpertVtab));
  9081. }
  9082. if( rc==SQLITE_OK ){
  9083. p->pExpert = pExpert;
  9084. p->pTab = pExpert->pTable;
  9085. assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
  9086. }
  9087. sqlite3_free(zCreateTable);
  9088. }else{
  9089. rc = SQLITE_NOMEM;
  9090. }
  9091. }
  9092. *ppVtab = (sqlite3_vtab*)p;
  9093. return rc;
  9094. }
  9095. static int expertDisconnect(sqlite3_vtab *pVtab){
  9096. ExpertVtab *p = (ExpertVtab*)pVtab;
  9097. sqlite3_free(p);
  9098. return SQLITE_OK;
  9099. }
  9100. static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
  9101. ExpertVtab *p = (ExpertVtab*)pVtab;
  9102. int rc = SQLITE_OK;
  9103. int n = 0;
  9104. IdxScan *pScan;
  9105. const int opmask =
  9106. SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
  9107. SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
  9108. SQLITE_INDEX_CONSTRAINT_LE;
  9109. pScan = idxMalloc(&rc, sizeof(IdxScan));
  9110. if( pScan ){
  9111. int i;
  9112. /* Link the new scan object into the list */
  9113. pScan->pTab = p->pTab;
  9114. pScan->pNextScan = p->pExpert->pScan;
  9115. p->pExpert->pScan = pScan;
  9116. /* Add the constraints to the IdxScan object */
  9117. for(i=0; i<pIdxInfo->nConstraint; i++){
  9118. struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
  9119. if( pCons->usable
  9120. && pCons->iColumn>=0
  9121. && p->pTab->aCol[pCons->iColumn].iPk==0
  9122. && (pCons->op & opmask)
  9123. ){
  9124. IdxConstraint *pNew;
  9125. const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
  9126. pNew = idxNewConstraint(&rc, zColl);
  9127. if( pNew ){
  9128. pNew->iCol = pCons->iColumn;
  9129. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  9130. pNew->pNext = pScan->pEq;
  9131. pScan->pEq = pNew;
  9132. }else{
  9133. pNew->bRange = 1;
  9134. pNew->pNext = pScan->pRange;
  9135. pScan->pRange = pNew;
  9136. }
  9137. }
  9138. n++;
  9139. pIdxInfo->aConstraintUsage[i].argvIndex = n;
  9140. }
  9141. }
  9142. /* Add the ORDER BY to the IdxScan object */
  9143. for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
  9144. int iCol = pIdxInfo->aOrderBy[i].iColumn;
  9145. if( iCol>=0 ){
  9146. IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
  9147. if( pNew ){
  9148. pNew->iCol = iCol;
  9149. pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
  9150. pNew->pNext = pScan->pOrder;
  9151. pNew->pLink = pScan->pOrder;
  9152. pScan->pOrder = pNew;
  9153. n++;
  9154. }
  9155. }
  9156. }
  9157. }
  9158. pIdxInfo->estimatedCost = 1000000.0 / (n+1);
  9159. return rc;
  9160. }
  9161. static int expertUpdate(
  9162. sqlite3_vtab *pVtab,
  9163. int nData,
  9164. sqlite3_value **azData,
  9165. sqlite_int64 *pRowid
  9166. ){
  9167. (void)pVtab;
  9168. (void)nData;
  9169. (void)azData;
  9170. (void)pRowid;
  9171. return SQLITE_OK;
  9172. }
  9173. /*
  9174. ** Virtual table module xOpen method.
  9175. */
  9176. static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  9177. int rc = SQLITE_OK;
  9178. ExpertCsr *pCsr;
  9179. (void)pVTab;
  9180. pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
  9181. *ppCursor = (sqlite3_vtab_cursor*)pCsr;
  9182. return rc;
  9183. }
  9184. /*
  9185. ** Virtual table module xClose method.
  9186. */
  9187. static int expertClose(sqlite3_vtab_cursor *cur){
  9188. ExpertCsr *pCsr = (ExpertCsr*)cur;
  9189. sqlite3_finalize(pCsr->pData);
  9190. sqlite3_free(pCsr);
  9191. return SQLITE_OK;
  9192. }
  9193. /*
  9194. ** Virtual table module xEof method.
  9195. **
  9196. ** Return non-zero if the cursor does not currently point to a valid
  9197. ** record (i.e if the scan has finished), or zero otherwise.
  9198. */
  9199. static int expertEof(sqlite3_vtab_cursor *cur){
  9200. ExpertCsr *pCsr = (ExpertCsr*)cur;
  9201. return pCsr->pData==0;
  9202. }
  9203. /*
  9204. ** Virtual table module xNext method.
  9205. */
  9206. static int expertNext(sqlite3_vtab_cursor *cur){
  9207. ExpertCsr *pCsr = (ExpertCsr*)cur;
  9208. int rc = SQLITE_OK;
  9209. assert( pCsr->pData );
  9210. rc = sqlite3_step(pCsr->pData);
  9211. if( rc!=SQLITE_ROW ){
  9212. rc = sqlite3_finalize(pCsr->pData);
  9213. pCsr->pData = 0;
  9214. }else{
  9215. rc = SQLITE_OK;
  9216. }
  9217. return rc;
  9218. }
  9219. /*
  9220. ** Virtual table module xRowid method.
  9221. */
  9222. static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  9223. (void)cur;
  9224. *pRowid = 0;
  9225. return SQLITE_OK;
  9226. }
  9227. /*
  9228. ** Virtual table module xColumn method.
  9229. */
  9230. static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  9231. ExpertCsr *pCsr = (ExpertCsr*)cur;
  9232. sqlite3_value *pVal;
  9233. pVal = sqlite3_column_value(pCsr->pData, i);
  9234. if( pVal ){
  9235. sqlite3_result_value(ctx, pVal);
  9236. }
  9237. return SQLITE_OK;
  9238. }
  9239. /*
  9240. ** Virtual table module xFilter method.
  9241. */
  9242. static int expertFilter(
  9243. sqlite3_vtab_cursor *cur,
  9244. int idxNum, const char *idxStr,
  9245. int argc, sqlite3_value **argv
  9246. ){
  9247. ExpertCsr *pCsr = (ExpertCsr*)cur;
  9248. ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
  9249. sqlite3expert *pExpert = pVtab->pExpert;
  9250. int rc;
  9251. (void)idxNum;
  9252. (void)idxStr;
  9253. (void)argc;
  9254. (void)argv;
  9255. rc = sqlite3_finalize(pCsr->pData);
  9256. pCsr->pData = 0;
  9257. if( rc==SQLITE_OK ){
  9258. rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
  9259. "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
  9260. );
  9261. }
  9262. if( rc==SQLITE_OK ){
  9263. rc = expertNext(cur);
  9264. }
  9265. return rc;
  9266. }
  9267. static int idxRegisterVtab(sqlite3expert *p){
  9268. static sqlite3_module expertModule = {
  9269. 2, /* iVersion */
  9270. expertConnect, /* xCreate - create a table */
  9271. expertConnect, /* xConnect - connect to an existing table */
  9272. expertBestIndex, /* xBestIndex - Determine search strategy */
  9273. expertDisconnect, /* xDisconnect - Disconnect from a table */
  9274. expertDisconnect, /* xDestroy - Drop a table */
  9275. expertOpen, /* xOpen - open a cursor */
  9276. expertClose, /* xClose - close a cursor */
  9277. expertFilter, /* xFilter - configure scan constraints */
  9278. expertNext, /* xNext - advance a cursor */
  9279. expertEof, /* xEof */
  9280. expertColumn, /* xColumn - read data */
  9281. expertRowid, /* xRowid - read data */
  9282. expertUpdate, /* xUpdate - write data */
  9283. 0, /* xBegin - begin transaction */
  9284. 0, /* xSync - sync transaction */
  9285. 0, /* xCommit - commit transaction */
  9286. 0, /* xRollback - rollback transaction */
  9287. 0, /* xFindFunction - function overloading */
  9288. 0, /* xRename - rename the table */
  9289. 0, /* xSavepoint */
  9290. 0, /* xRelease */
  9291. 0, /* xRollbackTo */
  9292. 0, /* xShadowName */
  9293. };
  9294. return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
  9295. }
  9296. /*
  9297. ** End of virtual table implementation.
  9298. *************************************************************************/
  9299. /*
  9300. ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
  9301. ** is called, set it to the return value of sqlite3_finalize() before
  9302. ** returning. Otherwise, discard the sqlite3_finalize() return value.
  9303. */
  9304. static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
  9305. int rc = sqlite3_finalize(pStmt);
  9306. if( *pRc==SQLITE_OK ) *pRc = rc;
  9307. }
  9308. /*
  9309. ** Attempt to allocate an IdxTable structure corresponding to table zTab
  9310. ** in the main database of connection db. If successful, set (*ppOut) to
  9311. ** point to the new object and return SQLITE_OK. Otherwise, return an
  9312. ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
  9313. ** set to point to an error string.
  9314. **
  9315. ** It is the responsibility of the caller to eventually free either the
  9316. ** IdxTable object or error message using sqlite3_free().
  9317. */
  9318. static int idxGetTableInfo(
  9319. sqlite3 *db, /* Database connection to read details from */
  9320. const char *zTab, /* Table name */
  9321. IdxTable **ppOut, /* OUT: New object (if successful) */
  9322. char **pzErrmsg /* OUT: Error message (if not) */
  9323. ){
  9324. sqlite3_stmt *p1 = 0;
  9325. int nCol = 0;
  9326. int nTab;
  9327. int nByte;
  9328. IdxTable *pNew = 0;
  9329. int rc, rc2;
  9330. char *pCsr = 0;
  9331. int nPk = 0;
  9332. *ppOut = 0;
  9333. if( zTab==0 ) return SQLITE_ERROR;
  9334. nTab = STRLEN(zTab);
  9335. nByte = sizeof(IdxTable) + nTab + 1;
  9336. rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
  9337. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
  9338. const char *zCol = (const char*)sqlite3_column_text(p1, 1);
  9339. const char *zColSeq = 0;
  9340. if( zCol==0 ){
  9341. rc = SQLITE_ERROR;
  9342. break;
  9343. }
  9344. nByte += 1 + STRLEN(zCol);
  9345. rc = sqlite3_table_column_metadata(
  9346. db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
  9347. );
  9348. if( zColSeq==0 ) zColSeq = "binary";
  9349. nByte += 1 + STRLEN(zColSeq);
  9350. nCol++;
  9351. nPk += (sqlite3_column_int(p1, 5)>0);
  9352. }
  9353. rc2 = sqlite3_reset(p1);
  9354. if( rc==SQLITE_OK ) rc = rc2;
  9355. nByte += sizeof(IdxColumn) * nCol;
  9356. if( rc==SQLITE_OK ){
  9357. pNew = idxMalloc(&rc, nByte);
  9358. }
  9359. if( rc==SQLITE_OK ){
  9360. pNew->aCol = (IdxColumn*)&pNew[1];
  9361. pNew->nCol = nCol;
  9362. pCsr = (char*)&pNew->aCol[nCol];
  9363. }
  9364. nCol = 0;
  9365. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
  9366. const char *zCol = (const char*)sqlite3_column_text(p1, 1);
  9367. const char *zColSeq = 0;
  9368. int nCopy;
  9369. if( zCol==0 ) continue;
  9370. nCopy = STRLEN(zCol) + 1;
  9371. pNew->aCol[nCol].zName = pCsr;
  9372. pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
  9373. memcpy(pCsr, zCol, nCopy);
  9374. pCsr += nCopy;
  9375. rc = sqlite3_table_column_metadata(
  9376. db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
  9377. );
  9378. if( rc==SQLITE_OK ){
  9379. if( zColSeq==0 ) zColSeq = "binary";
  9380. nCopy = STRLEN(zColSeq) + 1;
  9381. pNew->aCol[nCol].zColl = pCsr;
  9382. memcpy(pCsr, zColSeq, nCopy);
  9383. pCsr += nCopy;
  9384. }
  9385. nCol++;
  9386. }
  9387. idxFinalize(&rc, p1);
  9388. if( rc!=SQLITE_OK ){
  9389. sqlite3_free(pNew);
  9390. pNew = 0;
  9391. }else if( ALWAYS(pNew!=0) ){
  9392. pNew->zName = pCsr;
  9393. if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
  9394. }
  9395. *ppOut = pNew;
  9396. return rc;
  9397. }
  9398. /*
  9399. ** This function is a no-op if *pRc is set to anything other than
  9400. ** SQLITE_OK when it is called.
  9401. **
  9402. ** If *pRc is initially set to SQLITE_OK, then the text specified by
  9403. ** the printf() style arguments is appended to zIn and the result returned
  9404. ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
  9405. ** zIn before returning.
  9406. */
  9407. static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
  9408. va_list ap;
  9409. char *zAppend = 0;
  9410. char *zRet = 0;
  9411. int nIn = zIn ? STRLEN(zIn) : 0;
  9412. int nAppend = 0;
  9413. va_start(ap, zFmt);
  9414. if( *pRc==SQLITE_OK ){
  9415. zAppend = sqlite3_vmprintf(zFmt, ap);
  9416. if( zAppend ){
  9417. nAppend = STRLEN(zAppend);
  9418. zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
  9419. }
  9420. if( zAppend && zRet ){
  9421. if( nIn ) memcpy(zRet, zIn, nIn);
  9422. memcpy(&zRet[nIn], zAppend, nAppend+1);
  9423. }else{
  9424. sqlite3_free(zRet);
  9425. zRet = 0;
  9426. *pRc = SQLITE_NOMEM;
  9427. }
  9428. sqlite3_free(zAppend);
  9429. sqlite3_free(zIn);
  9430. }
  9431. va_end(ap);
  9432. return zRet;
  9433. }
  9434. /*
  9435. ** Return true if zId must be quoted in order to use it as an SQL
  9436. ** identifier, or false otherwise.
  9437. */
  9438. static int idxIdentifierRequiresQuotes(const char *zId){
  9439. int i;
  9440. int nId = STRLEN(zId);
  9441. if( sqlite3_keyword_check(zId, nId) ) return 1;
  9442. for(i=0; zId[i]; i++){
  9443. if( !(zId[i]=='_')
  9444. && !(zId[i]>='0' && zId[i]<='9')
  9445. && !(zId[i]>='a' && zId[i]<='z')
  9446. && !(zId[i]>='A' && zId[i]<='Z')
  9447. ){
  9448. return 1;
  9449. }
  9450. }
  9451. return 0;
  9452. }
  9453. /*
  9454. ** This function appends an index column definition suitable for constraint
  9455. ** pCons to the string passed as zIn and returns the result.
  9456. */
  9457. static char *idxAppendColDefn(
  9458. int *pRc, /* IN/OUT: Error code */
  9459. char *zIn, /* Column defn accumulated so far */
  9460. IdxTable *pTab, /* Table index will be created on */
  9461. IdxConstraint *pCons
  9462. ){
  9463. char *zRet = zIn;
  9464. IdxColumn *p = &pTab->aCol[pCons->iCol];
  9465. if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
  9466. if( idxIdentifierRequiresQuotes(p->zName) ){
  9467. zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
  9468. }else{
  9469. zRet = idxAppendText(pRc, zRet, "%s", p->zName);
  9470. }
  9471. if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
  9472. if( idxIdentifierRequiresQuotes(pCons->zColl) ){
  9473. zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
  9474. }else{
  9475. zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
  9476. }
  9477. }
  9478. if( pCons->bDesc ){
  9479. zRet = idxAppendText(pRc, zRet, " DESC");
  9480. }
  9481. return zRet;
  9482. }
  9483. /*
  9484. ** Search database dbm for an index compatible with the one idxCreateFromCons()
  9485. ** would create from arguments pScan, pEq and pTail. If no error occurs and
  9486. ** such an index is found, return non-zero. Or, if no such index is found,
  9487. ** return zero.
  9488. **
  9489. ** If an error occurs, set *pRc to an SQLite error code and return zero.
  9490. */
  9491. static int idxFindCompatible(
  9492. int *pRc, /* OUT: Error code */
  9493. sqlite3* dbm, /* Database to search */
  9494. IdxScan *pScan, /* Scan for table to search for index on */
  9495. IdxConstraint *pEq, /* List of == constraints */
  9496. IdxConstraint *pTail /* List of range constraints */
  9497. ){
  9498. const char *zTbl = pScan->pTab->zName;
  9499. sqlite3_stmt *pIdxList = 0;
  9500. IdxConstraint *pIter;
  9501. int nEq = 0; /* Number of elements in pEq */
  9502. int rc;
  9503. /* Count the elements in list pEq */
  9504. for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
  9505. rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
  9506. while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
  9507. int bMatch = 1;
  9508. IdxConstraint *pT = pTail;
  9509. sqlite3_stmt *pInfo = 0;
  9510. const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
  9511. if( zIdx==0 ) continue;
  9512. /* Zero the IdxConstraint.bFlag values in the pEq list */
  9513. for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
  9514. rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
  9515. while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
  9516. int iIdx = sqlite3_column_int(pInfo, 0);
  9517. int iCol = sqlite3_column_int(pInfo, 1);
  9518. const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
  9519. if( iIdx<nEq ){
  9520. for(pIter=pEq; pIter; pIter=pIter->pLink){
  9521. if( pIter->bFlag ) continue;
  9522. if( pIter->iCol!=iCol ) continue;
  9523. if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
  9524. pIter->bFlag = 1;
  9525. break;
  9526. }
  9527. if( pIter==0 ){
  9528. bMatch = 0;
  9529. break;
  9530. }
  9531. }else{
  9532. if( pT ){
  9533. if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
  9534. bMatch = 0;
  9535. break;
  9536. }
  9537. pT = pT->pLink;
  9538. }
  9539. }
  9540. }
  9541. idxFinalize(&rc, pInfo);
  9542. if( rc==SQLITE_OK && bMatch ){
  9543. sqlite3_finalize(pIdxList);
  9544. return 1;
  9545. }
  9546. }
  9547. idxFinalize(&rc, pIdxList);
  9548. *pRc = rc;
  9549. return 0;
  9550. }
  9551. /* Callback for sqlite3_exec() with query with leading count(*) column.
  9552. * The first argument is expected to be an int*, referent to be incremented
  9553. * if that leading column is not exactly '0'.
  9554. */
  9555. static int countNonzeros(void* pCount, int nc,
  9556. char* azResults[], char* azColumns[]){
  9557. (void)azColumns; /* Suppress unused parameter warning */
  9558. if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
  9559. *((int *)pCount) += 1;
  9560. }
  9561. return 0;
  9562. }
  9563. static int idxCreateFromCons(
  9564. sqlite3expert *p,
  9565. IdxScan *pScan,
  9566. IdxConstraint *pEq,
  9567. IdxConstraint *pTail
  9568. ){
  9569. sqlite3 *dbm = p->dbm;
  9570. int rc = SQLITE_OK;
  9571. if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
  9572. IdxTable *pTab = pScan->pTab;
  9573. char *zCols = 0;
  9574. char *zIdx = 0;
  9575. IdxConstraint *pCons;
  9576. unsigned int h = 0;
  9577. const char *zFmt;
  9578. for(pCons=pEq; pCons; pCons=pCons->pLink){
  9579. zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
  9580. }
  9581. for(pCons=pTail; pCons; pCons=pCons->pLink){
  9582. zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
  9583. }
  9584. if( rc==SQLITE_OK ){
  9585. /* Hash the list of columns to come up with a name for the index */
  9586. const char *zTable = pScan->pTab->zName;
  9587. int quoteTable = idxIdentifierRequiresQuotes(zTable);
  9588. char *zName = 0; /* Index name */
  9589. int collisions = 0;
  9590. do{
  9591. int i;
  9592. char *zFind;
  9593. for(i=0; zCols[i]; i++){
  9594. h += ((h<<3) + zCols[i]);
  9595. }
  9596. sqlite3_free(zName);
  9597. zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
  9598. if( zName==0 ) break;
  9599. /* Is is unique among table, view and index names? */
  9600. zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
  9601. " AND type in ('index','table','view')";
  9602. zFind = sqlite3_mprintf(zFmt, zName);
  9603. i = 0;
  9604. rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
  9605. assert(rc==SQLITE_OK);
  9606. sqlite3_free(zFind);
  9607. if( i==0 ){
  9608. collisions = 0;
  9609. break;
  9610. }
  9611. ++collisions;
  9612. }while( collisions<50 && zName!=0 );
  9613. if( collisions ){
  9614. /* This return means "Gave up trying to find a unique index name." */
  9615. rc = SQLITE_BUSY_TIMEOUT;
  9616. }else if( zName==0 ){
  9617. rc = SQLITE_NOMEM;
  9618. }else{
  9619. if( quoteTable ){
  9620. zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
  9621. }else{
  9622. zFmt = "CREATE INDEX %s ON %s(%s)";
  9623. }
  9624. zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
  9625. if( !zIdx ){
  9626. rc = SQLITE_NOMEM;
  9627. }else{
  9628. rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
  9629. if( rc!=SQLITE_OK ){
  9630. rc = SQLITE_BUSY_TIMEOUT;
  9631. }else{
  9632. idxHashAdd(&rc, &p->hIdx, zName, zIdx);
  9633. }
  9634. }
  9635. sqlite3_free(zName);
  9636. sqlite3_free(zIdx);
  9637. }
  9638. }
  9639. sqlite3_free(zCols);
  9640. }
  9641. return rc;
  9642. }
  9643. /*
  9644. ** Return true if list pList (linked by IdxConstraint.pLink) contains
  9645. ** a constraint compatible with *p. Otherwise return false.
  9646. */
  9647. static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
  9648. IdxConstraint *pCmp;
  9649. for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
  9650. if( p->iCol==pCmp->iCol ) return 1;
  9651. }
  9652. return 0;
  9653. }
  9654. static int idxCreateFromWhere(
  9655. sqlite3expert *p,
  9656. IdxScan *pScan, /* Create indexes for this scan */
  9657. IdxConstraint *pTail /* range/ORDER BY constraints for inclusion */
  9658. ){
  9659. IdxConstraint *p1 = 0;
  9660. IdxConstraint *pCon;
  9661. int rc;
  9662. /* Gather up all the == constraints. */
  9663. for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
  9664. if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
  9665. pCon->pLink = p1;
  9666. p1 = pCon;
  9667. }
  9668. }
  9669. /* Create an index using the == constraints collected above. And the
  9670. ** range constraint/ORDER BY terms passed in by the caller, if any. */
  9671. rc = idxCreateFromCons(p, pScan, p1, pTail);
  9672. /* If no range/ORDER BY passed by the caller, create a version of the
  9673. ** index for each range constraint. */
  9674. if( pTail==0 ){
  9675. for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
  9676. assert( pCon->pLink==0 );
  9677. if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
  9678. rc = idxCreateFromCons(p, pScan, p1, pCon);
  9679. }
  9680. }
  9681. }
  9682. return rc;
  9683. }
  9684. /*
  9685. ** Create candidate indexes in database [dbm] based on the data in
  9686. ** linked-list pScan.
  9687. */
  9688. static int idxCreateCandidates(sqlite3expert *p){
  9689. int rc = SQLITE_OK;
  9690. IdxScan *pIter;
  9691. for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
  9692. rc = idxCreateFromWhere(p, pIter, 0);
  9693. if( rc==SQLITE_OK && pIter->pOrder ){
  9694. rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
  9695. }
  9696. }
  9697. return rc;
  9698. }
  9699. /*
  9700. ** Free all elements of the linked list starting at pConstraint.
  9701. */
  9702. static void idxConstraintFree(IdxConstraint *pConstraint){
  9703. IdxConstraint *pNext;
  9704. IdxConstraint *p;
  9705. for(p=pConstraint; p; p=pNext){
  9706. pNext = p->pNext;
  9707. sqlite3_free(p);
  9708. }
  9709. }
  9710. /*
  9711. ** Free all elements of the linked list starting from pScan up until pLast
  9712. ** (pLast is not freed).
  9713. */
  9714. static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
  9715. IdxScan *p;
  9716. IdxScan *pNext;
  9717. for(p=pScan; p!=pLast; p=pNext){
  9718. pNext = p->pNextScan;
  9719. idxConstraintFree(p->pOrder);
  9720. idxConstraintFree(p->pEq);
  9721. idxConstraintFree(p->pRange);
  9722. sqlite3_free(p);
  9723. }
  9724. }
  9725. /*
  9726. ** Free all elements of the linked list starting from pStatement up
  9727. ** until pLast (pLast is not freed).
  9728. */
  9729. static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
  9730. IdxStatement *p;
  9731. IdxStatement *pNext;
  9732. for(p=pStatement; p!=pLast; p=pNext){
  9733. pNext = p->pNext;
  9734. sqlite3_free(p->zEQP);
  9735. sqlite3_free(p->zIdx);
  9736. sqlite3_free(p);
  9737. }
  9738. }
  9739. /*
  9740. ** Free the linked list of IdxTable objects starting at pTab.
  9741. */
  9742. static void idxTableFree(IdxTable *pTab){
  9743. IdxTable *pIter;
  9744. IdxTable *pNext;
  9745. for(pIter=pTab; pIter; pIter=pNext){
  9746. pNext = pIter->pNext;
  9747. sqlite3_free(pIter);
  9748. }
  9749. }
  9750. /*
  9751. ** Free the linked list of IdxWrite objects starting at pTab.
  9752. */
  9753. static void idxWriteFree(IdxWrite *pTab){
  9754. IdxWrite *pIter;
  9755. IdxWrite *pNext;
  9756. for(pIter=pTab; pIter; pIter=pNext){
  9757. pNext = pIter->pNext;
  9758. sqlite3_free(pIter);
  9759. }
  9760. }
  9761. /*
  9762. ** This function is called after candidate indexes have been created. It
  9763. ** runs all the queries to see which indexes they prefer, and populates
  9764. ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
  9765. */
  9766. static int idxFindIndexes(
  9767. sqlite3expert *p,
  9768. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  9769. ){
  9770. IdxStatement *pStmt;
  9771. sqlite3 *dbm = p->dbm;
  9772. int rc = SQLITE_OK;
  9773. IdxHash hIdx;
  9774. idxHashInit(&hIdx);
  9775. for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
  9776. IdxHashEntry *pEntry;
  9777. sqlite3_stmt *pExplain = 0;
  9778. idxHashClear(&hIdx);
  9779. rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
  9780. "EXPLAIN QUERY PLAN %s", pStmt->zSql
  9781. );
  9782. while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
  9783. /* int iId = sqlite3_column_int(pExplain, 0); */
  9784. /* int iParent = sqlite3_column_int(pExplain, 1); */
  9785. /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
  9786. const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
  9787. int nDetail;
  9788. int i;
  9789. if( !zDetail ) continue;
  9790. nDetail = STRLEN(zDetail);
  9791. for(i=0; i<nDetail; i++){
  9792. const char *zIdx = 0;
  9793. if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
  9794. zIdx = &zDetail[i+13];
  9795. }else if( i+22<nDetail
  9796. && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
  9797. ){
  9798. zIdx = &zDetail[i+22];
  9799. }
  9800. if( zIdx ){
  9801. const char *zSql;
  9802. int nIdx = 0;
  9803. while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
  9804. nIdx++;
  9805. }
  9806. zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
  9807. if( zSql ){
  9808. idxHashAdd(&rc, &hIdx, zSql, 0);
  9809. if( rc ) goto find_indexes_out;
  9810. }
  9811. break;
  9812. }
  9813. }
  9814. if( zDetail[0]!='-' ){
  9815. pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
  9816. }
  9817. }
  9818. for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
  9819. pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
  9820. }
  9821. idxFinalize(&rc, pExplain);
  9822. }
  9823. find_indexes_out:
  9824. idxHashClear(&hIdx);
  9825. return rc;
  9826. }
  9827. static int idxAuthCallback(
  9828. void *pCtx,
  9829. int eOp,
  9830. const char *z3,
  9831. const char *z4,
  9832. const char *zDb,
  9833. const char *zTrigger
  9834. ){
  9835. int rc = SQLITE_OK;
  9836. (void)z4;
  9837. (void)zTrigger;
  9838. if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
  9839. if( sqlite3_stricmp(zDb, "main")==0 ){
  9840. sqlite3expert *p = (sqlite3expert*)pCtx;
  9841. IdxTable *pTab;
  9842. for(pTab=p->pTable; pTab; pTab=pTab->pNext){
  9843. if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
  9844. }
  9845. if( pTab ){
  9846. IdxWrite *pWrite;
  9847. for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
  9848. if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
  9849. }
  9850. if( pWrite==0 ){
  9851. pWrite = idxMalloc(&rc, sizeof(IdxWrite));
  9852. if( rc==SQLITE_OK ){
  9853. pWrite->pTab = pTab;
  9854. pWrite->eOp = eOp;
  9855. pWrite->pNext = p->pWrite;
  9856. p->pWrite = pWrite;
  9857. }
  9858. }
  9859. }
  9860. }
  9861. }
  9862. return rc;
  9863. }
  9864. static int idxProcessOneTrigger(
  9865. sqlite3expert *p,
  9866. IdxWrite *pWrite,
  9867. char **pzErr
  9868. ){
  9869. static const char *zInt = UNIQUE_TABLE_NAME;
  9870. static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
  9871. IdxTable *pTab = pWrite->pTab;
  9872. const char *zTab = pTab->zName;
  9873. const char *zSql =
  9874. "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
  9875. "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
  9876. "ORDER BY type;";
  9877. sqlite3_stmt *pSelect = 0;
  9878. int rc = SQLITE_OK;
  9879. char *zWrite = 0;
  9880. /* Create the table and its triggers in the temp schema */
  9881. rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
  9882. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
  9883. const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
  9884. if( zCreate==0 ) continue;
  9885. rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
  9886. }
  9887. idxFinalize(&rc, pSelect);
  9888. /* Rename the table in the temp schema to zInt */
  9889. if( rc==SQLITE_OK ){
  9890. char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
  9891. if( z==0 ){
  9892. rc = SQLITE_NOMEM;
  9893. }else{
  9894. rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
  9895. sqlite3_free(z);
  9896. }
  9897. }
  9898. switch( pWrite->eOp ){
  9899. case SQLITE_INSERT: {
  9900. int i;
  9901. zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
  9902. for(i=0; i<pTab->nCol; i++){
  9903. zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
  9904. }
  9905. zWrite = idxAppendText(&rc, zWrite, ")");
  9906. break;
  9907. }
  9908. case SQLITE_UPDATE: {
  9909. int i;
  9910. zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
  9911. for(i=0; i<pTab->nCol; i++){
  9912. zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
  9913. pTab->aCol[i].zName
  9914. );
  9915. }
  9916. break;
  9917. }
  9918. default: {
  9919. assert( pWrite->eOp==SQLITE_DELETE );
  9920. if( rc==SQLITE_OK ){
  9921. zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
  9922. if( zWrite==0 ) rc = SQLITE_NOMEM;
  9923. }
  9924. }
  9925. }
  9926. if( rc==SQLITE_OK ){
  9927. sqlite3_stmt *pX = 0;
  9928. rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
  9929. idxFinalize(&rc, pX);
  9930. if( rc!=SQLITE_OK ){
  9931. idxDatabaseError(p->dbv, pzErr);
  9932. }
  9933. }
  9934. sqlite3_free(zWrite);
  9935. if( rc==SQLITE_OK ){
  9936. rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
  9937. }
  9938. return rc;
  9939. }
  9940. static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
  9941. int rc = SQLITE_OK;
  9942. IdxWrite *pEnd = 0;
  9943. IdxWrite *pFirst = p->pWrite;
  9944. while( rc==SQLITE_OK && pFirst!=pEnd ){
  9945. IdxWrite *pIter;
  9946. for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
  9947. rc = idxProcessOneTrigger(p, pIter, pzErr);
  9948. }
  9949. pEnd = pFirst;
  9950. pFirst = p->pWrite;
  9951. }
  9952. return rc;
  9953. }
  9954. static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
  9955. int rc = idxRegisterVtab(p);
  9956. sqlite3_stmt *pSchema = 0;
  9957. /* For each table in the main db schema:
  9958. **
  9959. ** 1) Add an entry to the p->pTable list, and
  9960. ** 2) Create the equivalent virtual table in dbv.
  9961. */
  9962. rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
  9963. "SELECT type, name, sql, 1 FROM sqlite_schema "
  9964. "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
  9965. " UNION ALL "
  9966. "SELECT type, name, sql, 2 FROM sqlite_schema "
  9967. "WHERE type = 'trigger'"
  9968. " AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
  9969. "ORDER BY 4, 1"
  9970. );
  9971. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
  9972. const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
  9973. const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
  9974. const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
  9975. if( zType==0 || zName==0 ) continue;
  9976. if( zType[0]=='v' || zType[1]=='r' ){
  9977. if( zSql ) rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
  9978. }else{
  9979. IdxTable *pTab;
  9980. rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
  9981. if( rc==SQLITE_OK ){
  9982. int i;
  9983. char *zInner = 0;
  9984. char *zOuter = 0;
  9985. pTab->pNext = p->pTable;
  9986. p->pTable = pTab;
  9987. /* The statement the vtab will pass to sqlite3_declare_vtab() */
  9988. zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
  9989. for(i=0; i<pTab->nCol; i++){
  9990. zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
  9991. (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
  9992. );
  9993. }
  9994. zInner = idxAppendText(&rc, zInner, ")");
  9995. /* The CVT statement to create the vtab */
  9996. zOuter = idxAppendText(&rc, 0,
  9997. "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
  9998. );
  9999. if( rc==SQLITE_OK ){
  10000. rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
  10001. }
  10002. sqlite3_free(zInner);
  10003. sqlite3_free(zOuter);
  10004. }
  10005. }
  10006. }
  10007. idxFinalize(&rc, pSchema);
  10008. return rc;
  10009. }
  10010. struct IdxSampleCtx {
  10011. int iTarget;
  10012. double target; /* Target nRet/nRow value */
  10013. double nRow; /* Number of rows seen */
  10014. double nRet; /* Number of rows returned */
  10015. };
  10016. static void idxSampleFunc(
  10017. sqlite3_context *pCtx,
  10018. int argc,
  10019. sqlite3_value **argv
  10020. ){
  10021. struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
  10022. int bRet;
  10023. (void)argv;
  10024. assert( argc==0 );
  10025. if( p->nRow==0.0 ){
  10026. bRet = 1;
  10027. }else{
  10028. bRet = (p->nRet / p->nRow) <= p->target;
  10029. if( bRet==0 ){
  10030. unsigned short rnd;
  10031. sqlite3_randomness(2, (void*)&rnd);
  10032. bRet = ((int)rnd % 100) <= p->iTarget;
  10033. }
  10034. }
  10035. sqlite3_result_int(pCtx, bRet);
  10036. p->nRow += 1.0;
  10037. p->nRet += (double)bRet;
  10038. }
  10039. struct IdxRemCtx {
  10040. int nSlot;
  10041. struct IdxRemSlot {
  10042. int eType; /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
  10043. i64 iVal; /* SQLITE_INTEGER value */
  10044. double rVal; /* SQLITE_FLOAT value */
  10045. int nByte; /* Bytes of space allocated at z */
  10046. int n; /* Size of buffer z */
  10047. char *z; /* SQLITE_TEXT/BLOB value */
  10048. } aSlot[1];
  10049. };
  10050. /*
  10051. ** Implementation of scalar function rem().
  10052. */
  10053. static void idxRemFunc(
  10054. sqlite3_context *pCtx,
  10055. int argc,
  10056. sqlite3_value **argv
  10057. ){
  10058. struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
  10059. struct IdxRemSlot *pSlot;
  10060. int iSlot;
  10061. assert( argc==2 );
  10062. iSlot = sqlite3_value_int(argv[0]);
  10063. assert( iSlot<=p->nSlot );
  10064. pSlot = &p->aSlot[iSlot];
  10065. switch( pSlot->eType ){
  10066. case SQLITE_NULL:
  10067. /* no-op */
  10068. break;
  10069. case SQLITE_INTEGER:
  10070. sqlite3_result_int64(pCtx, pSlot->iVal);
  10071. break;
  10072. case SQLITE_FLOAT:
  10073. sqlite3_result_double(pCtx, pSlot->rVal);
  10074. break;
  10075. case SQLITE_BLOB:
  10076. sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
  10077. break;
  10078. case SQLITE_TEXT:
  10079. sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
  10080. break;
  10081. }
  10082. pSlot->eType = sqlite3_value_type(argv[1]);
  10083. switch( pSlot->eType ){
  10084. case SQLITE_NULL:
  10085. /* no-op */
  10086. break;
  10087. case SQLITE_INTEGER:
  10088. pSlot->iVal = sqlite3_value_int64(argv[1]);
  10089. break;
  10090. case SQLITE_FLOAT:
  10091. pSlot->rVal = sqlite3_value_double(argv[1]);
  10092. break;
  10093. case SQLITE_BLOB:
  10094. case SQLITE_TEXT: {
  10095. int nByte = sqlite3_value_bytes(argv[1]);
  10096. const void *pData = 0;
  10097. if( nByte>pSlot->nByte ){
  10098. char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
  10099. if( zNew==0 ){
  10100. sqlite3_result_error_nomem(pCtx);
  10101. return;
  10102. }
  10103. pSlot->nByte = nByte*2;
  10104. pSlot->z = zNew;
  10105. }
  10106. pSlot->n = nByte;
  10107. if( pSlot->eType==SQLITE_BLOB ){
  10108. pData = sqlite3_value_blob(argv[1]);
  10109. if( pData ) memcpy(pSlot->z, pData, nByte);
  10110. }else{
  10111. pData = sqlite3_value_text(argv[1]);
  10112. memcpy(pSlot->z, pData, nByte);
  10113. }
  10114. break;
  10115. }
  10116. }
  10117. }
  10118. static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
  10119. int rc = SQLITE_OK;
  10120. const char *zMax =
  10121. "SELECT max(i.seqno) FROM "
  10122. " sqlite_schema AS s, "
  10123. " pragma_index_list(s.name) AS l, "
  10124. " pragma_index_info(l.name) AS i "
  10125. "WHERE s.type = 'table'";
  10126. sqlite3_stmt *pMax = 0;
  10127. *pnMax = 0;
  10128. rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
  10129. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
  10130. *pnMax = sqlite3_column_int(pMax, 0) + 1;
  10131. }
  10132. idxFinalize(&rc, pMax);
  10133. return rc;
  10134. }
  10135. static int idxPopulateOneStat1(
  10136. sqlite3expert *p,
  10137. sqlite3_stmt *pIndexXInfo,
  10138. sqlite3_stmt *pWriteStat,
  10139. const char *zTab,
  10140. const char *zIdx,
  10141. char **pzErr
  10142. ){
  10143. char *zCols = 0;
  10144. char *zOrder = 0;
  10145. char *zQuery = 0;
  10146. int nCol = 0;
  10147. int i;
  10148. sqlite3_stmt *pQuery = 0;
  10149. int *aStat = 0;
  10150. int rc = SQLITE_OK;
  10151. assert( p->iSample>0 );
  10152. /* Formulate the query text */
  10153. sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
  10154. while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
  10155. const char *zComma = zCols==0 ? "" : ", ";
  10156. const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
  10157. const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
  10158. zCols = idxAppendText(&rc, zCols,
  10159. "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
  10160. );
  10161. zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
  10162. }
  10163. sqlite3_reset(pIndexXInfo);
  10164. if( rc==SQLITE_OK ){
  10165. if( p->iSample==100 ){
  10166. zQuery = sqlite3_mprintf(
  10167. "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
  10168. );
  10169. }else{
  10170. zQuery = sqlite3_mprintf(
  10171. "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
  10172. );
  10173. }
  10174. }
  10175. sqlite3_free(zCols);
  10176. sqlite3_free(zOrder);
  10177. /* Formulate the query text */
  10178. if( rc==SQLITE_OK ){
  10179. sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
  10180. rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
  10181. }
  10182. sqlite3_free(zQuery);
  10183. if( rc==SQLITE_OK ){
  10184. aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
  10185. }
  10186. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
  10187. IdxHashEntry *pEntry;
  10188. char *zStat = 0;
  10189. for(i=0; i<=nCol; i++) aStat[i] = 1;
  10190. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
  10191. aStat[0]++;
  10192. for(i=0; i<nCol; i++){
  10193. if( sqlite3_column_int(pQuery, i)==0 ) break;
  10194. }
  10195. for(/*no-op*/; i<nCol; i++){
  10196. aStat[i+1]++;
  10197. }
  10198. }
  10199. if( rc==SQLITE_OK ){
  10200. int s0 = aStat[0];
  10201. zStat = sqlite3_mprintf("%d", s0);
  10202. if( zStat==0 ) rc = SQLITE_NOMEM;
  10203. for(i=1; rc==SQLITE_OK && i<=nCol; i++){
  10204. zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
  10205. }
  10206. }
  10207. if( rc==SQLITE_OK ){
  10208. sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
  10209. sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
  10210. sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
  10211. sqlite3_step(pWriteStat);
  10212. rc = sqlite3_reset(pWriteStat);
  10213. }
  10214. pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
  10215. if( pEntry ){
  10216. assert( pEntry->zVal2==0 );
  10217. pEntry->zVal2 = zStat;
  10218. }else{
  10219. sqlite3_free(zStat);
  10220. }
  10221. }
  10222. sqlite3_free(aStat);
  10223. idxFinalize(&rc, pQuery);
  10224. return rc;
  10225. }
  10226. static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
  10227. int rc;
  10228. char *zSql;
  10229. rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
  10230. if( rc!=SQLITE_OK ) return rc;
  10231. zSql = sqlite3_mprintf(
  10232. "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
  10233. );
  10234. if( zSql==0 ) return SQLITE_NOMEM;
  10235. rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
  10236. sqlite3_free(zSql);
  10237. return rc;
  10238. }
  10239. /*
  10240. ** This function is called as part of sqlite3_expert_analyze(). Candidate
  10241. ** indexes have already been created in database sqlite3expert.dbm, this
  10242. ** function populates sqlite_stat1 table in the same database.
  10243. **
  10244. ** The stat1 data is generated by querying the
  10245. */
  10246. static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
  10247. int rc = SQLITE_OK;
  10248. int nMax =0;
  10249. struct IdxRemCtx *pCtx = 0;
  10250. struct IdxSampleCtx samplectx;
  10251. int i;
  10252. i64 iPrev = -100000;
  10253. sqlite3_stmt *pAllIndex = 0;
  10254. sqlite3_stmt *pIndexXInfo = 0;
  10255. sqlite3_stmt *pWrite = 0;
  10256. const char *zAllIndex =
  10257. "SELECT s.rowid, s.name, l.name FROM "
  10258. " sqlite_schema AS s, "
  10259. " pragma_index_list(s.name) AS l "
  10260. "WHERE s.type = 'table'";
  10261. const char *zIndexXInfo =
  10262. "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
  10263. const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
  10264. /* If iSample==0, no sqlite_stat1 data is required. */
  10265. if( p->iSample==0 ) return SQLITE_OK;
  10266. rc = idxLargestIndex(p->dbm, &nMax, pzErr);
  10267. if( nMax<=0 || rc!=SQLITE_OK ) return rc;
  10268. rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
  10269. if( rc==SQLITE_OK ){
  10270. int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
  10271. pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
  10272. }
  10273. if( rc==SQLITE_OK ){
  10274. sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
  10275. rc = sqlite3_create_function(
  10276. dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
  10277. );
  10278. }
  10279. if( rc==SQLITE_OK ){
  10280. rc = sqlite3_create_function(
  10281. p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
  10282. );
  10283. }
  10284. if( rc==SQLITE_OK ){
  10285. pCtx->nSlot = nMax+1;
  10286. rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
  10287. }
  10288. if( rc==SQLITE_OK ){
  10289. rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
  10290. }
  10291. if( rc==SQLITE_OK ){
  10292. rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
  10293. }
  10294. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
  10295. i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
  10296. const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
  10297. const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
  10298. if( zTab==0 || zIdx==0 ) continue;
  10299. if( p->iSample<100 && iPrev!=iRowid ){
  10300. samplectx.target = (double)p->iSample / 100.0;
  10301. samplectx.iTarget = p->iSample;
  10302. samplectx.nRow = 0.0;
  10303. samplectx.nRet = 0.0;
  10304. rc = idxBuildSampleTable(p, zTab);
  10305. if( rc!=SQLITE_OK ) break;
  10306. }
  10307. rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
  10308. iPrev = iRowid;
  10309. }
  10310. if( rc==SQLITE_OK && p->iSample<100 ){
  10311. rc = sqlite3_exec(p->dbv,
  10312. "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
  10313. );
  10314. }
  10315. idxFinalize(&rc, pAllIndex);
  10316. idxFinalize(&rc, pIndexXInfo);
  10317. idxFinalize(&rc, pWrite);
  10318. if( pCtx ){
  10319. for(i=0; i<pCtx->nSlot; i++){
  10320. sqlite3_free(pCtx->aSlot[i].z);
  10321. }
  10322. sqlite3_free(pCtx);
  10323. }
  10324. if( rc==SQLITE_OK ){
  10325. rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
  10326. }
  10327. sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
  10328. return rc;
  10329. }
  10330. /*
  10331. ** Allocate a new sqlite3expert object.
  10332. */
  10333. sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
  10334. int rc = SQLITE_OK;
  10335. sqlite3expert *pNew;
  10336. pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
  10337. /* Open two in-memory databases to work with. The "vtab database" (dbv)
  10338. ** will contain a virtual table corresponding to each real table in
  10339. ** the user database schema, and a copy of each view. It is used to
  10340. ** collect information regarding the WHERE, ORDER BY and other clauses
  10341. ** of the user's query.
  10342. */
  10343. if( rc==SQLITE_OK ){
  10344. pNew->db = db;
  10345. pNew->iSample = 100;
  10346. rc = sqlite3_open(":memory:", &pNew->dbv);
  10347. }
  10348. if( rc==SQLITE_OK ){
  10349. rc = sqlite3_open(":memory:", &pNew->dbm);
  10350. if( rc==SQLITE_OK ){
  10351. sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
  10352. }
  10353. }
  10354. /* Copy the entire schema of database [db] into [dbm]. */
  10355. if( rc==SQLITE_OK ){
  10356. sqlite3_stmt *pSql = 0;
  10357. rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
  10358. "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
  10359. " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
  10360. );
  10361. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  10362. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  10363. if( zSql ) rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
  10364. }
  10365. idxFinalize(&rc, pSql);
  10366. }
  10367. /* Create the vtab schema */
  10368. if( rc==SQLITE_OK ){
  10369. rc = idxCreateVtabSchema(pNew, pzErrmsg);
  10370. }
  10371. /* Register the auth callback with dbv */
  10372. if( rc==SQLITE_OK ){
  10373. sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
  10374. }
  10375. /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
  10376. ** return the new sqlite3expert handle. */
  10377. if( rc!=SQLITE_OK ){
  10378. sqlite3_expert_destroy(pNew);
  10379. pNew = 0;
  10380. }
  10381. return pNew;
  10382. }
  10383. /*
  10384. ** Configure an sqlite3expert object.
  10385. */
  10386. int sqlite3_expert_config(sqlite3expert *p, int op, ...){
  10387. int rc = SQLITE_OK;
  10388. va_list ap;
  10389. va_start(ap, op);
  10390. switch( op ){
  10391. case EXPERT_CONFIG_SAMPLE: {
  10392. int iVal = va_arg(ap, int);
  10393. if( iVal<0 ) iVal = 0;
  10394. if( iVal>100 ) iVal = 100;
  10395. p->iSample = iVal;
  10396. break;
  10397. }
  10398. default:
  10399. rc = SQLITE_NOTFOUND;
  10400. break;
  10401. }
  10402. va_end(ap);
  10403. return rc;
  10404. }
  10405. /*
  10406. ** Add an SQL statement to the analysis.
  10407. */
  10408. int sqlite3_expert_sql(
  10409. sqlite3expert *p, /* From sqlite3_expert_new() */
  10410. const char *zSql, /* SQL statement to add */
  10411. char **pzErr /* OUT: Error message (if any) */
  10412. ){
  10413. IdxScan *pScanOrig = p->pScan;
  10414. IdxStatement *pStmtOrig = p->pStatement;
  10415. int rc = SQLITE_OK;
  10416. const char *zStmt = zSql;
  10417. if( p->bRun ) return SQLITE_MISUSE;
  10418. while( rc==SQLITE_OK && zStmt && zStmt[0] ){
  10419. sqlite3_stmt *pStmt = 0;
  10420. rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
  10421. if( rc==SQLITE_OK ){
  10422. if( pStmt ){
  10423. IdxStatement *pNew;
  10424. const char *z = sqlite3_sql(pStmt);
  10425. int n = STRLEN(z);
  10426. pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
  10427. if( rc==SQLITE_OK ){
  10428. pNew->zSql = (char*)&pNew[1];
  10429. memcpy(pNew->zSql, z, n+1);
  10430. pNew->pNext = p->pStatement;
  10431. if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
  10432. p->pStatement = pNew;
  10433. }
  10434. sqlite3_finalize(pStmt);
  10435. }
  10436. }else{
  10437. idxDatabaseError(p->dbv, pzErr);
  10438. }
  10439. }
  10440. if( rc!=SQLITE_OK ){
  10441. idxScanFree(p->pScan, pScanOrig);
  10442. idxStatementFree(p->pStatement, pStmtOrig);
  10443. p->pScan = pScanOrig;
  10444. p->pStatement = pStmtOrig;
  10445. }
  10446. return rc;
  10447. }
  10448. int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
  10449. int rc;
  10450. IdxHashEntry *pEntry;
  10451. /* Do trigger processing to collect any extra IdxScan structures */
  10452. rc = idxProcessTriggers(p, pzErr);
  10453. /* Create candidate indexes within the in-memory database file */
  10454. if( rc==SQLITE_OK ){
  10455. rc = idxCreateCandidates(p);
  10456. }else if ( rc==SQLITE_BUSY_TIMEOUT ){
  10457. if( pzErr )
  10458. *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
  10459. return rc;
  10460. }
  10461. /* Generate the stat1 data */
  10462. if( rc==SQLITE_OK ){
  10463. rc = idxPopulateStat1(p, pzErr);
  10464. }
  10465. /* Formulate the EXPERT_REPORT_CANDIDATES text */
  10466. for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
  10467. p->zCandidates = idxAppendText(&rc, p->zCandidates,
  10468. "%s;%s%s\n", pEntry->zVal,
  10469. pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
  10470. );
  10471. }
  10472. /* Figure out which of the candidate indexes are preferred by the query
  10473. ** planner and report the results to the user. */
  10474. if( rc==SQLITE_OK ){
  10475. rc = idxFindIndexes(p, pzErr);
  10476. }
  10477. if( rc==SQLITE_OK ){
  10478. p->bRun = 1;
  10479. }
  10480. return rc;
  10481. }
  10482. /*
  10483. ** Return the total number of statements that have been added to this
  10484. ** sqlite3expert using sqlite3_expert_sql().
  10485. */
  10486. int sqlite3_expert_count(sqlite3expert *p){
  10487. int nRet = 0;
  10488. if( p->pStatement ) nRet = p->pStatement->iId+1;
  10489. return nRet;
  10490. }
  10491. /*
  10492. ** Return a component of the report.
  10493. */
  10494. const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
  10495. const char *zRet = 0;
  10496. IdxStatement *pStmt;
  10497. if( p->bRun==0 ) return 0;
  10498. for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
  10499. switch( eReport ){
  10500. case EXPERT_REPORT_SQL:
  10501. if( pStmt ) zRet = pStmt->zSql;
  10502. break;
  10503. case EXPERT_REPORT_INDEXES:
  10504. if( pStmt ) zRet = pStmt->zIdx;
  10505. break;
  10506. case EXPERT_REPORT_PLAN:
  10507. if( pStmt ) zRet = pStmt->zEQP;
  10508. break;
  10509. case EXPERT_REPORT_CANDIDATES:
  10510. zRet = p->zCandidates;
  10511. break;
  10512. }
  10513. return zRet;
  10514. }
  10515. /*
  10516. ** Free an sqlite3expert object.
  10517. */
  10518. void sqlite3_expert_destroy(sqlite3expert *p){
  10519. if( p ){
  10520. sqlite3_close(p->dbm);
  10521. sqlite3_close(p->dbv);
  10522. idxScanFree(p->pScan, 0);
  10523. idxStatementFree(p->pStatement, 0);
  10524. idxTableFree(p->pTable);
  10525. idxWriteFree(p->pWrite);
  10526. idxHashClear(&p->hIdx);
  10527. sqlite3_free(p->zCandidates);
  10528. sqlite3_free(p);
  10529. }
  10530. }
  10531. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  10532. /************************* End ../ext/expert/sqlite3expert.c ********************/
  10533. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
  10534. #define SQLITE_SHELL_HAVE_RECOVER 1
  10535. #else
  10536. #define SQLITE_SHELL_HAVE_RECOVER 0
  10537. #endif
  10538. #if SQLITE_SHELL_HAVE_RECOVER
  10539. /************************* Begin ../ext/recover/dbdata.c ******************/
  10540. /*
  10541. ** 2019-04-17
  10542. **
  10543. ** The author disclaims copyright to this source code. In place of
  10544. ** a legal notice, here is a blessing:
  10545. **
  10546. ** May you do good and not evil.
  10547. ** May you find forgiveness for yourself and forgive others.
  10548. ** May you share freely, never taking more than you give.
  10549. **
  10550. ******************************************************************************
  10551. **
  10552. ** This file contains an implementation of two eponymous virtual tables,
  10553. ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
  10554. ** "sqlite_dbpage" eponymous virtual table be available.
  10555. **
  10556. ** SQLITE_DBDATA:
  10557. ** sqlite_dbdata is used to extract data directly from a database b-tree
  10558. ** page and its associated overflow pages, bypassing the b-tree layer.
  10559. ** The table schema is equivalent to:
  10560. **
  10561. ** CREATE TABLE sqlite_dbdata(
  10562. ** pgno INTEGER,
  10563. ** cell INTEGER,
  10564. ** field INTEGER,
  10565. ** value ANY,
  10566. ** schema TEXT HIDDEN
  10567. ** );
  10568. **
  10569. ** IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
  10570. ** FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
  10571. ** "schema".
  10572. **
  10573. ** Each page of the database is inspected. If it cannot be interpreted as
  10574. ** a b-tree page, or if it is a b-tree page containing 0 entries, the
  10575. ** sqlite_dbdata table contains no rows for that page. Otherwise, the
  10576. ** table contains one row for each field in the record associated with
  10577. ** each cell on the page. For intkey b-trees, the key value is stored in
  10578. ** field -1.
  10579. **
  10580. ** For example, for the database:
  10581. **
  10582. ** CREATE TABLE t1(a, b); -- root page is page 2
  10583. ** INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
  10584. ** INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
  10585. **
  10586. ** the sqlite_dbdata table contains, as well as from entries related to
  10587. ** page 1, content equivalent to:
  10588. **
  10589. ** INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
  10590. ** (2, 0, -1, 5 ),
  10591. ** (2, 0, 0, 'v' ),
  10592. ** (2, 0, 1, 'five'),
  10593. ** (2, 1, -1, 10 ),
  10594. ** (2, 1, 0, 'x' ),
  10595. ** (2, 1, 1, 'ten' );
  10596. **
  10597. ** If database corruption is encountered, this module does not report an
  10598. ** error. Instead, it attempts to extract as much data as possible and
  10599. ** ignores the corruption.
  10600. **
  10601. ** SQLITE_DBPTR:
  10602. ** The sqlite_dbptr table has the following schema:
  10603. **
  10604. ** CREATE TABLE sqlite_dbptr(
  10605. ** pgno INTEGER,
  10606. ** child INTEGER,
  10607. ** schema TEXT HIDDEN
  10608. ** );
  10609. **
  10610. ** It contains one entry for each b-tree pointer between a parent and
  10611. ** child page in the database.
  10612. */
  10613. #if !defined(SQLITEINT_H)
  10614. /* #include "sqlite3ext.h" */
  10615. /* typedef unsigned char u8; */
  10616. /* typedef unsigned int u32; */
  10617. #endif
  10618. SQLITE_EXTENSION_INIT1
  10619. #include <string.h>
  10620. #include <assert.h>
  10621. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10622. #define DBDATA_PADDING_BYTES 100
  10623. typedef struct DbdataTable DbdataTable;
  10624. typedef struct DbdataCursor DbdataCursor;
  10625. /* Cursor object */
  10626. struct DbdataCursor {
  10627. sqlite3_vtab_cursor base; /* Base class. Must be first */
  10628. sqlite3_stmt *pStmt; /* For fetching database pages */
  10629. int iPgno; /* Current page number */
  10630. u8 *aPage; /* Buffer containing page */
  10631. int nPage; /* Size of aPage[] in bytes */
  10632. int nCell; /* Number of cells on aPage[] */
  10633. int iCell; /* Current cell number */
  10634. int bOnePage; /* True to stop after one page */
  10635. int szDb;
  10636. sqlite3_int64 iRowid;
  10637. /* Only for the sqlite_dbdata table */
  10638. u8 *pRec; /* Buffer containing current record */
  10639. sqlite3_int64 nRec; /* Size of pRec[] in bytes */
  10640. sqlite3_int64 nHdr; /* Size of header in bytes */
  10641. int iField; /* Current field number */
  10642. u8 *pHdrPtr;
  10643. u8 *pPtr;
  10644. u32 enc; /* Text encoding */
  10645. sqlite3_int64 iIntkey; /* Integer key value */
  10646. };
  10647. /* Table object */
  10648. struct DbdataTable {
  10649. sqlite3_vtab base; /* Base class. Must be first */
  10650. sqlite3 *db; /* The database connection */
  10651. sqlite3_stmt *pStmt; /* For fetching database pages */
  10652. int bPtr; /* True for sqlite3_dbptr table */
  10653. };
  10654. /* Column and schema definitions for sqlite_dbdata */
  10655. #define DBDATA_COLUMN_PGNO 0
  10656. #define DBDATA_COLUMN_CELL 1
  10657. #define DBDATA_COLUMN_FIELD 2
  10658. #define DBDATA_COLUMN_VALUE 3
  10659. #define DBDATA_COLUMN_SCHEMA 4
  10660. #define DBDATA_SCHEMA \
  10661. "CREATE TABLE x(" \
  10662. " pgno INTEGER," \
  10663. " cell INTEGER," \
  10664. " field INTEGER," \
  10665. " value ANY," \
  10666. " schema TEXT HIDDEN" \
  10667. ")"
  10668. /* Column and schema definitions for sqlite_dbptr */
  10669. #define DBPTR_COLUMN_PGNO 0
  10670. #define DBPTR_COLUMN_CHILD 1
  10671. #define DBPTR_COLUMN_SCHEMA 2
  10672. #define DBPTR_SCHEMA \
  10673. "CREATE TABLE x(" \
  10674. " pgno INTEGER," \
  10675. " child INTEGER," \
  10676. " schema TEXT HIDDEN" \
  10677. ")"
  10678. /*
  10679. ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
  10680. ** table.
  10681. */
  10682. static int dbdataConnect(
  10683. sqlite3 *db,
  10684. void *pAux,
  10685. int argc, const char *const*argv,
  10686. sqlite3_vtab **ppVtab,
  10687. char **pzErr
  10688. ){
  10689. DbdataTable *pTab = 0;
  10690. int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
  10691. if( rc==SQLITE_OK ){
  10692. pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
  10693. if( pTab==0 ){
  10694. rc = SQLITE_NOMEM;
  10695. }else{
  10696. memset(pTab, 0, sizeof(DbdataTable));
  10697. pTab->db = db;
  10698. pTab->bPtr = (pAux!=0);
  10699. }
  10700. }
  10701. *ppVtab = (sqlite3_vtab*)pTab;
  10702. return rc;
  10703. }
  10704. /*
  10705. ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
  10706. */
  10707. static int dbdataDisconnect(sqlite3_vtab *pVtab){
  10708. DbdataTable *pTab = (DbdataTable*)pVtab;
  10709. if( pTab ){
  10710. sqlite3_finalize(pTab->pStmt);
  10711. sqlite3_free(pVtab);
  10712. }
  10713. return SQLITE_OK;
  10714. }
  10715. /*
  10716. ** This function interprets two types of constraints:
  10717. **
  10718. ** schema=?
  10719. ** pgno=?
  10720. **
  10721. ** If neither are present, idxNum is set to 0. If schema=? is present,
  10722. ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
  10723. ** in idxNum is set.
  10724. **
  10725. ** If both parameters are present, schema is in position 0 and pgno in
  10726. ** position 1.
  10727. */
  10728. static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
  10729. DbdataTable *pTab = (DbdataTable*)tab;
  10730. int i;
  10731. int iSchema = -1;
  10732. int iPgno = -1;
  10733. int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
  10734. for(i=0; i<pIdx->nConstraint; i++){
  10735. struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
  10736. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  10737. if( p->iColumn==colSchema ){
  10738. if( p->usable==0 ) return SQLITE_CONSTRAINT;
  10739. iSchema = i;
  10740. }
  10741. if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
  10742. iPgno = i;
  10743. }
  10744. }
  10745. }
  10746. if( iSchema>=0 ){
  10747. pIdx->aConstraintUsage[iSchema].argvIndex = 1;
  10748. pIdx->aConstraintUsage[iSchema].omit = 1;
  10749. }
  10750. if( iPgno>=0 ){
  10751. pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
  10752. pIdx->aConstraintUsage[iPgno].omit = 1;
  10753. pIdx->estimatedCost = 100;
  10754. pIdx->estimatedRows = 50;
  10755. if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
  10756. int iCol = pIdx->aOrderBy[0].iColumn;
  10757. if( pIdx->nOrderBy==1 ){
  10758. pIdx->orderByConsumed = (iCol==0 || iCol==1);
  10759. }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
  10760. pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
  10761. }
  10762. }
  10763. }else{
  10764. pIdx->estimatedCost = 100000000;
  10765. pIdx->estimatedRows = 1000000000;
  10766. }
  10767. pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
  10768. return SQLITE_OK;
  10769. }
  10770. /*
  10771. ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
  10772. */
  10773. static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  10774. DbdataCursor *pCsr;
  10775. pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
  10776. if( pCsr==0 ){
  10777. return SQLITE_NOMEM;
  10778. }else{
  10779. memset(pCsr, 0, sizeof(DbdataCursor));
  10780. pCsr->base.pVtab = pVTab;
  10781. }
  10782. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  10783. return SQLITE_OK;
  10784. }
  10785. /*
  10786. ** Restore a cursor object to the state it was in when first allocated
  10787. ** by dbdataOpen().
  10788. */
  10789. static void dbdataResetCursor(DbdataCursor *pCsr){
  10790. DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
  10791. if( pTab->pStmt==0 ){
  10792. pTab->pStmt = pCsr->pStmt;
  10793. }else{
  10794. sqlite3_finalize(pCsr->pStmt);
  10795. }
  10796. pCsr->pStmt = 0;
  10797. pCsr->iPgno = 1;
  10798. pCsr->iCell = 0;
  10799. pCsr->iField = 0;
  10800. pCsr->bOnePage = 0;
  10801. sqlite3_free(pCsr->aPage);
  10802. sqlite3_free(pCsr->pRec);
  10803. pCsr->pRec = 0;
  10804. pCsr->aPage = 0;
  10805. }
  10806. /*
  10807. ** Close an sqlite_dbdata or sqlite_dbptr cursor.
  10808. */
  10809. static int dbdataClose(sqlite3_vtab_cursor *pCursor){
  10810. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  10811. dbdataResetCursor(pCsr);
  10812. sqlite3_free(pCsr);
  10813. return SQLITE_OK;
  10814. }
  10815. /*
  10816. ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
  10817. */
  10818. static u32 get_uint16(unsigned char *a){
  10819. return (a[0]<<8)|a[1];
  10820. }
  10821. static u32 get_uint32(unsigned char *a){
  10822. return ((u32)a[0]<<24)
  10823. | ((u32)a[1]<<16)
  10824. | ((u32)a[2]<<8)
  10825. | ((u32)a[3]);
  10826. }
  10827. /*
  10828. ** Load page pgno from the database via the sqlite_dbpage virtual table.
  10829. ** If successful, set (*ppPage) to point to a buffer containing the page
  10830. ** data, (*pnPage) to the size of that buffer in bytes and return
  10831. ** SQLITE_OK. In this case it is the responsibility of the caller to
  10832. ** eventually free the buffer using sqlite3_free().
  10833. **
  10834. ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
  10835. ** return an SQLite error code.
  10836. */
  10837. static int dbdataLoadPage(
  10838. DbdataCursor *pCsr, /* Cursor object */
  10839. u32 pgno, /* Page number of page to load */
  10840. u8 **ppPage, /* OUT: pointer to page buffer */
  10841. int *pnPage /* OUT: Size of (*ppPage) in bytes */
  10842. ){
  10843. int rc2;
  10844. int rc = SQLITE_OK;
  10845. sqlite3_stmt *pStmt = pCsr->pStmt;
  10846. *ppPage = 0;
  10847. *pnPage = 0;
  10848. if( pgno>0 ){
  10849. sqlite3_bind_int64(pStmt, 2, pgno);
  10850. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  10851. int nCopy = sqlite3_column_bytes(pStmt, 0);
  10852. if( nCopy>0 ){
  10853. u8 *pPage;
  10854. pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
  10855. if( pPage==0 ){
  10856. rc = SQLITE_NOMEM;
  10857. }else{
  10858. const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
  10859. memcpy(pPage, pCopy, nCopy);
  10860. memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
  10861. }
  10862. *ppPage = pPage;
  10863. *pnPage = nCopy;
  10864. }
  10865. }
  10866. rc2 = sqlite3_reset(pStmt);
  10867. if( rc==SQLITE_OK ) rc = rc2;
  10868. }
  10869. return rc;
  10870. }
  10871. /*
  10872. ** Read a varint. Put the value in *pVal and return the number of bytes.
  10873. */
  10874. static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
  10875. sqlite3_uint64 u = 0;
  10876. int i;
  10877. for(i=0; i<8; i++){
  10878. u = (u<<7) + (z[i]&0x7f);
  10879. if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
  10880. }
  10881. u = (u<<8) + (z[i]&0xff);
  10882. *pVal = (sqlite3_int64)u;
  10883. return 9;
  10884. }
  10885. /*
  10886. ** Like dbdataGetVarint(), but set the output to 0 if it is less than 0
  10887. ** or greater than 0xFFFFFFFF. This can be used for all varints in an
  10888. ** SQLite database except for key values in intkey tables.
  10889. */
  10890. static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){
  10891. sqlite3_int64 val;
  10892. int nRet = dbdataGetVarint(z, &val);
  10893. if( val<0 || val>0xFFFFFFFF ) val = 0;
  10894. *pVal = val;
  10895. return nRet;
  10896. }
  10897. /*
  10898. ** Return the number of bytes of space used by an SQLite value of type
  10899. ** eType.
  10900. */
  10901. static int dbdataValueBytes(int eType){
  10902. switch( eType ){
  10903. case 0: case 8: case 9:
  10904. case 10: case 11:
  10905. return 0;
  10906. case 1:
  10907. return 1;
  10908. case 2:
  10909. return 2;
  10910. case 3:
  10911. return 3;
  10912. case 4:
  10913. return 4;
  10914. case 5:
  10915. return 6;
  10916. case 6:
  10917. case 7:
  10918. return 8;
  10919. default:
  10920. if( eType>0 ){
  10921. return ((eType-12) / 2);
  10922. }
  10923. return 0;
  10924. }
  10925. }
  10926. /*
  10927. ** Load a value of type eType from buffer pData and use it to set the
  10928. ** result of context object pCtx.
  10929. */
  10930. static void dbdataValue(
  10931. sqlite3_context *pCtx,
  10932. u32 enc,
  10933. int eType,
  10934. u8 *pData,
  10935. sqlite3_int64 nData
  10936. ){
  10937. if( eType>=0 && dbdataValueBytes(eType)<=nData ){
  10938. switch( eType ){
  10939. case 0:
  10940. case 10:
  10941. case 11:
  10942. sqlite3_result_null(pCtx);
  10943. break;
  10944. case 8:
  10945. sqlite3_result_int(pCtx, 0);
  10946. break;
  10947. case 9:
  10948. sqlite3_result_int(pCtx, 1);
  10949. break;
  10950. case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
  10951. sqlite3_uint64 v = (signed char)pData[0];
  10952. pData++;
  10953. switch( eType ){
  10954. case 7:
  10955. case 6: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2;
  10956. case 5: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2;
  10957. case 4: v = (v<<8) + pData[0]; pData++;
  10958. case 3: v = (v<<8) + pData[0]; pData++;
  10959. case 2: v = (v<<8) + pData[0]; pData++;
  10960. }
  10961. if( eType==7 ){
  10962. double r;
  10963. memcpy(&r, &v, sizeof(r));
  10964. sqlite3_result_double(pCtx, r);
  10965. }else{
  10966. sqlite3_result_int64(pCtx, (sqlite3_int64)v);
  10967. }
  10968. break;
  10969. }
  10970. default: {
  10971. int n = ((eType-12) / 2);
  10972. if( eType % 2 ){
  10973. switch( enc ){
  10974. #ifndef SQLITE_OMIT_UTF16
  10975. case SQLITE_UTF16BE:
  10976. sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
  10977. break;
  10978. case SQLITE_UTF16LE:
  10979. sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
  10980. break;
  10981. #endif
  10982. default:
  10983. sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
  10984. break;
  10985. }
  10986. }else{
  10987. sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
  10988. }
  10989. }
  10990. }
  10991. }
  10992. }
  10993. /*
  10994. ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
  10995. */
  10996. static int dbdataNext(sqlite3_vtab_cursor *pCursor){
  10997. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  10998. DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
  10999. pCsr->iRowid++;
  11000. while( 1 ){
  11001. int rc;
  11002. int iOff = (pCsr->iPgno==1 ? 100 : 0);
  11003. int bNextPage = 0;
  11004. if( pCsr->aPage==0 ){
  11005. while( 1 ){
  11006. if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
  11007. rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
  11008. if( rc!=SQLITE_OK ) return rc;
  11009. if( pCsr->aPage ) break;
  11010. if( pCsr->bOnePage ) return SQLITE_OK;
  11011. pCsr->iPgno++;
  11012. }
  11013. pCsr->iCell = pTab->bPtr ? -2 : 0;
  11014. pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
  11015. }
  11016. if( pTab->bPtr ){
  11017. if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
  11018. pCsr->iCell = pCsr->nCell;
  11019. }
  11020. pCsr->iCell++;
  11021. if( pCsr->iCell>=pCsr->nCell ){
  11022. sqlite3_free(pCsr->aPage);
  11023. pCsr->aPage = 0;
  11024. if( pCsr->bOnePage ) return SQLITE_OK;
  11025. pCsr->iPgno++;
  11026. }else{
  11027. return SQLITE_OK;
  11028. }
  11029. }else{
  11030. /* If there is no record loaded, load it now. */
  11031. if( pCsr->pRec==0 ){
  11032. int bHasRowid = 0;
  11033. int nPointer = 0;
  11034. sqlite3_int64 nPayload = 0;
  11035. sqlite3_int64 nHdr = 0;
  11036. int iHdr;
  11037. int U, X;
  11038. int nLocal;
  11039. switch( pCsr->aPage[iOff] ){
  11040. case 0x02:
  11041. nPointer = 4;
  11042. break;
  11043. case 0x0a:
  11044. break;
  11045. case 0x0d:
  11046. bHasRowid = 1;
  11047. break;
  11048. default:
  11049. /* This is not a b-tree page with records on it. Continue. */
  11050. pCsr->iCell = pCsr->nCell;
  11051. break;
  11052. }
  11053. if( pCsr->iCell>=pCsr->nCell ){
  11054. bNextPage = 1;
  11055. }else{
  11056. iOff += 8 + nPointer + pCsr->iCell*2;
  11057. if( iOff>pCsr->nPage ){
  11058. bNextPage = 1;
  11059. }else{
  11060. iOff = get_uint16(&pCsr->aPage[iOff]);
  11061. }
  11062. /* For an interior node cell, skip past the child-page number */
  11063. iOff += nPointer;
  11064. /* Load the "byte of payload including overflow" field */
  11065. if( bNextPage || iOff>pCsr->nPage ){
  11066. bNextPage = 1;
  11067. }else{
  11068. iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
  11069. }
  11070. /* If this is a leaf intkey cell, load the rowid */
  11071. if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
  11072. iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
  11073. }
  11074. /* Figure out how much data to read from the local page */
  11075. U = pCsr->nPage;
  11076. if( bHasRowid ){
  11077. X = U-35;
  11078. }else{
  11079. X = ((U-12)*64/255)-23;
  11080. }
  11081. if( nPayload<=X ){
  11082. nLocal = nPayload;
  11083. }else{
  11084. int M, K;
  11085. M = ((U-12)*32/255)-23;
  11086. K = M+((nPayload-M)%(U-4));
  11087. if( K<=X ){
  11088. nLocal = K;
  11089. }else{
  11090. nLocal = M;
  11091. }
  11092. }
  11093. if( bNextPage || nLocal+iOff>pCsr->nPage ){
  11094. bNextPage = 1;
  11095. }else{
  11096. /* Allocate space for payload. And a bit more to catch small buffer
  11097. ** overruns caused by attempting to read a varint or similar from
  11098. ** near the end of a corrupt record. */
  11099. pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
  11100. if( pCsr->pRec==0 ) return SQLITE_NOMEM;
  11101. memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
  11102. pCsr->nRec = nPayload;
  11103. /* Load the nLocal bytes of payload */
  11104. memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
  11105. iOff += nLocal;
  11106. /* Load content from overflow pages */
  11107. if( nPayload>nLocal ){
  11108. sqlite3_int64 nRem = nPayload - nLocal;
  11109. u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
  11110. while( nRem>0 ){
  11111. u8 *aOvfl = 0;
  11112. int nOvfl = 0;
  11113. int nCopy;
  11114. rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
  11115. assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
  11116. if( rc!=SQLITE_OK ) return rc;
  11117. if( aOvfl==0 ) break;
  11118. nCopy = U-4;
  11119. if( nCopy>nRem ) nCopy = nRem;
  11120. memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
  11121. nRem -= nCopy;
  11122. pgnoOvfl = get_uint32(aOvfl);
  11123. sqlite3_free(aOvfl);
  11124. }
  11125. }
  11126. iHdr = dbdataGetVarintU32(pCsr->pRec, &nHdr);
  11127. if( nHdr>nPayload ) nHdr = 0;
  11128. pCsr->nHdr = nHdr;
  11129. pCsr->pHdrPtr = &pCsr->pRec[iHdr];
  11130. pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
  11131. pCsr->iField = (bHasRowid ? -1 : 0);
  11132. }
  11133. }
  11134. }else{
  11135. pCsr->iField++;
  11136. if( pCsr->iField>0 ){
  11137. sqlite3_int64 iType;
  11138. if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
  11139. bNextPage = 1;
  11140. }else{
  11141. pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
  11142. pCsr->pPtr += dbdataValueBytes(iType);
  11143. }
  11144. }
  11145. }
  11146. if( bNextPage ){
  11147. sqlite3_free(pCsr->aPage);
  11148. sqlite3_free(pCsr->pRec);
  11149. pCsr->aPage = 0;
  11150. pCsr->pRec = 0;
  11151. if( pCsr->bOnePage ) return SQLITE_OK;
  11152. pCsr->iPgno++;
  11153. }else{
  11154. if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
  11155. return SQLITE_OK;
  11156. }
  11157. /* Advance to the next cell. The next iteration of the loop will load
  11158. ** the record and so on. */
  11159. sqlite3_free(pCsr->pRec);
  11160. pCsr->pRec = 0;
  11161. pCsr->iCell++;
  11162. }
  11163. }
  11164. }
  11165. assert( !"can't get here" );
  11166. return SQLITE_OK;
  11167. }
  11168. /*
  11169. ** Return true if the cursor is at EOF.
  11170. */
  11171. static int dbdataEof(sqlite3_vtab_cursor *pCursor){
  11172. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  11173. return pCsr->aPage==0;
  11174. }
  11175. /*
  11176. ** Return true if nul-terminated string zSchema ends in "()". Or false
  11177. ** otherwise.
  11178. */
  11179. static int dbdataIsFunction(const char *zSchema){
  11180. size_t n = strlen(zSchema);
  11181. if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){
  11182. return (int)n-2;
  11183. }
  11184. return 0;
  11185. }
  11186. /*
  11187. ** Determine the size in pages of database zSchema (where zSchema is
  11188. ** "main", "temp" or the name of an attached database) and set
  11189. ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
  11190. ** an SQLite error code.
  11191. */
  11192. static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
  11193. DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
  11194. char *zSql = 0;
  11195. int rc, rc2;
  11196. int nFunc = 0;
  11197. sqlite3_stmt *pStmt = 0;
  11198. if( (nFunc = dbdataIsFunction(zSchema))>0 ){
  11199. zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema);
  11200. }else{
  11201. zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
  11202. }
  11203. if( zSql==0 ) return SQLITE_NOMEM;
  11204. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  11205. sqlite3_free(zSql);
  11206. if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
  11207. pCsr->szDb = sqlite3_column_int(pStmt, 0);
  11208. }
  11209. rc2 = sqlite3_finalize(pStmt);
  11210. if( rc==SQLITE_OK ) rc = rc2;
  11211. return rc;
  11212. }
  11213. /*
  11214. ** Attempt to figure out the encoding of the database by retrieving page 1
  11215. ** and inspecting the header field. If successful, set the pCsr->enc variable
  11216. ** and return SQLITE_OK. Otherwise, return an SQLite error code.
  11217. */
  11218. static int dbdataGetEncoding(DbdataCursor *pCsr){
  11219. int rc = SQLITE_OK;
  11220. int nPg1 = 0;
  11221. u8 *aPg1 = 0;
  11222. rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1);
  11223. assert( rc!=SQLITE_OK || nPg1==0 || nPg1>=512 );
  11224. if( rc==SQLITE_OK && nPg1>0 ){
  11225. pCsr->enc = get_uint32(&aPg1[56]);
  11226. }
  11227. sqlite3_free(aPg1);
  11228. return rc;
  11229. }
  11230. /*
  11231. ** xFilter method for sqlite_dbdata and sqlite_dbptr.
  11232. */
  11233. static int dbdataFilter(
  11234. sqlite3_vtab_cursor *pCursor,
  11235. int idxNum, const char *idxStr,
  11236. int argc, sqlite3_value **argv
  11237. ){
  11238. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  11239. DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
  11240. int rc = SQLITE_OK;
  11241. const char *zSchema = "main";
  11242. dbdataResetCursor(pCsr);
  11243. assert( pCsr->iPgno==1 );
  11244. if( idxNum & 0x01 ){
  11245. zSchema = (const char*)sqlite3_value_text(argv[0]);
  11246. if( zSchema==0 ) zSchema = "";
  11247. }
  11248. if( idxNum & 0x02 ){
  11249. pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
  11250. pCsr->bOnePage = 1;
  11251. }else{
  11252. rc = dbdataDbsize(pCsr, zSchema);
  11253. }
  11254. if( rc==SQLITE_OK ){
  11255. int nFunc = 0;
  11256. if( pTab->pStmt ){
  11257. pCsr->pStmt = pTab->pStmt;
  11258. pTab->pStmt = 0;
  11259. }else if( (nFunc = dbdataIsFunction(zSchema))>0 ){
  11260. char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema);
  11261. if( zSql==0 ){
  11262. rc = SQLITE_NOMEM;
  11263. }else{
  11264. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  11265. sqlite3_free(zSql);
  11266. }
  11267. }else{
  11268. rc = sqlite3_prepare_v2(pTab->db,
  11269. "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
  11270. &pCsr->pStmt, 0
  11271. );
  11272. }
  11273. }
  11274. if( rc==SQLITE_OK ){
  11275. rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
  11276. }else{
  11277. pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
  11278. }
  11279. /* Try to determine the encoding of the db by inspecting the header
  11280. ** field on page 1. */
  11281. if( rc==SQLITE_OK ){
  11282. rc = dbdataGetEncoding(pCsr);
  11283. }
  11284. if( rc==SQLITE_OK ){
  11285. rc = dbdataNext(pCursor);
  11286. }
  11287. return rc;
  11288. }
  11289. /*
  11290. ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
  11291. */
  11292. static int dbdataColumn(
  11293. sqlite3_vtab_cursor *pCursor,
  11294. sqlite3_context *ctx,
  11295. int i
  11296. ){
  11297. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  11298. DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
  11299. if( pTab->bPtr ){
  11300. switch( i ){
  11301. case DBPTR_COLUMN_PGNO:
  11302. sqlite3_result_int64(ctx, pCsr->iPgno);
  11303. break;
  11304. case DBPTR_COLUMN_CHILD: {
  11305. int iOff = pCsr->iPgno==1 ? 100 : 0;
  11306. if( pCsr->iCell<0 ){
  11307. iOff += 8;
  11308. }else{
  11309. iOff += 12 + pCsr->iCell*2;
  11310. if( iOff>pCsr->nPage ) return SQLITE_OK;
  11311. iOff = get_uint16(&pCsr->aPage[iOff]);
  11312. }
  11313. if( iOff<=pCsr->nPage ){
  11314. sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
  11315. }
  11316. break;
  11317. }
  11318. }
  11319. }else{
  11320. switch( i ){
  11321. case DBDATA_COLUMN_PGNO:
  11322. sqlite3_result_int64(ctx, pCsr->iPgno);
  11323. break;
  11324. case DBDATA_COLUMN_CELL:
  11325. sqlite3_result_int(ctx, pCsr->iCell);
  11326. break;
  11327. case DBDATA_COLUMN_FIELD:
  11328. sqlite3_result_int(ctx, pCsr->iField);
  11329. break;
  11330. case DBDATA_COLUMN_VALUE: {
  11331. if( pCsr->iField<0 ){
  11332. sqlite3_result_int64(ctx, pCsr->iIntkey);
  11333. }else if( &pCsr->pRec[pCsr->nRec] >= pCsr->pPtr ){
  11334. sqlite3_int64 iType;
  11335. dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
  11336. dbdataValue(
  11337. ctx, pCsr->enc, iType, pCsr->pPtr,
  11338. &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
  11339. );
  11340. }
  11341. break;
  11342. }
  11343. }
  11344. }
  11345. return SQLITE_OK;
  11346. }
  11347. /*
  11348. ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
  11349. */
  11350. static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  11351. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  11352. *pRowid = pCsr->iRowid;
  11353. return SQLITE_OK;
  11354. }
  11355. /*
  11356. ** Invoke this routine to register the "sqlite_dbdata" virtual table module
  11357. */
  11358. static int sqlite3DbdataRegister(sqlite3 *db){
  11359. static sqlite3_module dbdata_module = {
  11360. 0, /* iVersion */
  11361. 0, /* xCreate */
  11362. dbdataConnect, /* xConnect */
  11363. dbdataBestIndex, /* xBestIndex */
  11364. dbdataDisconnect, /* xDisconnect */
  11365. 0, /* xDestroy */
  11366. dbdataOpen, /* xOpen - open a cursor */
  11367. dbdataClose, /* xClose - close a cursor */
  11368. dbdataFilter, /* xFilter - configure scan constraints */
  11369. dbdataNext, /* xNext - advance a cursor */
  11370. dbdataEof, /* xEof - check for end of scan */
  11371. dbdataColumn, /* xColumn - read data */
  11372. dbdataRowid, /* xRowid - read data */
  11373. 0, /* xUpdate */
  11374. 0, /* xBegin */
  11375. 0, /* xSync */
  11376. 0, /* xCommit */
  11377. 0, /* xRollback */
  11378. 0, /* xFindMethod */
  11379. 0, /* xRename */
  11380. 0, /* xSavepoint */
  11381. 0, /* xRelease */
  11382. 0, /* xRollbackTo */
  11383. 0 /* xShadowName */
  11384. };
  11385. int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
  11386. if( rc==SQLITE_OK ){
  11387. rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
  11388. }
  11389. return rc;
  11390. }
  11391. #ifdef _WIN32
  11392. #endif
  11393. int sqlite3_dbdata_init(
  11394. sqlite3 *db,
  11395. char **pzErrMsg,
  11396. const sqlite3_api_routines *pApi
  11397. ){
  11398. SQLITE_EXTENSION_INIT2(pApi);
  11399. return sqlite3DbdataRegister(db);
  11400. }
  11401. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  11402. /************************* End ../ext/recover/dbdata.c ********************/
  11403. /************************* Begin ../ext/recover/sqlite3recover.h ******************/
  11404. /*
  11405. ** 2022-08-27
  11406. **
  11407. ** The author disclaims copyright to this source code. In place of
  11408. ** a legal notice, here is a blessing:
  11409. **
  11410. ** May you do good and not evil.
  11411. ** May you find forgiveness for yourself and forgive others.
  11412. ** May you share freely, never taking more than you give.
  11413. **
  11414. *************************************************************************
  11415. **
  11416. ** This file contains the public interface to the "recover" extension -
  11417. ** an SQLite extension designed to recover data from corrupted database
  11418. ** files.
  11419. */
  11420. /*
  11421. ** OVERVIEW:
  11422. **
  11423. ** To use the API to recover data from a corrupted database, an
  11424. ** application:
  11425. **
  11426. ** 1) Creates an sqlite3_recover handle by calling either
  11427. ** sqlite3_recover_init() or sqlite3_recover_init_sql().
  11428. **
  11429. ** 2) Configures the new handle using one or more calls to
  11430. ** sqlite3_recover_config().
  11431. **
  11432. ** 3) Executes the recovery by repeatedly calling sqlite3_recover_step() on
  11433. ** the handle until it returns something other than SQLITE_OK. If it
  11434. ** returns SQLITE_DONE, then the recovery operation completed without
  11435. ** error. If it returns some other non-SQLITE_OK value, then an error
  11436. ** has occurred.
  11437. **
  11438. ** 4) Retrieves any error code and English language error message using the
  11439. ** sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs,
  11440. ** respectively.
  11441. **
  11442. ** 5) Destroys the sqlite3_recover handle and frees all resources
  11443. ** using sqlite3_recover_finish().
  11444. **
  11445. ** The application may abandon the recovery operation at any point
  11446. ** before it is finished by passing the sqlite3_recover handle to
  11447. ** sqlite3_recover_finish(). This is not an error, but the final state
  11448. ** of the output database, or the results of running the partial script
  11449. ** delivered to the SQL callback, are undefined.
  11450. */
  11451. #ifndef _SQLITE_RECOVER_H
  11452. #define _SQLITE_RECOVER_H
  11453. /* #include "sqlite3.h" */
  11454. #ifdef __cplusplus
  11455. extern "C" {
  11456. #endif
  11457. /*
  11458. ** An instance of the sqlite3_recover object represents a recovery
  11459. ** operation in progress.
  11460. **
  11461. ** Constructors:
  11462. **
  11463. ** sqlite3_recover_init()
  11464. ** sqlite3_recover_init_sql()
  11465. **
  11466. ** Destructor:
  11467. **
  11468. ** sqlite3_recover_finish()
  11469. **
  11470. ** Methods:
  11471. **
  11472. ** sqlite3_recover_config()
  11473. ** sqlite3_recover_errcode()
  11474. ** sqlite3_recover_errmsg()
  11475. ** sqlite3_recover_run()
  11476. ** sqlite3_recover_step()
  11477. */
  11478. typedef struct sqlite3_recover sqlite3_recover;
  11479. /*
  11480. ** These two APIs attempt to create and return a new sqlite3_recover object.
  11481. ** In both cases the first two arguments identify the (possibly
  11482. ** corrupt) database to recover data from. The first argument is an open
  11483. ** database handle and the second the name of a database attached to that
  11484. ** handle (i.e. "main", "temp" or the name of an attached database).
  11485. **
  11486. ** If sqlite3_recover_init() is used to create the new sqlite3_recover
  11487. ** handle, then data is recovered into a new database, identified by
  11488. ** string parameter zUri. zUri may be an absolute or relative file path,
  11489. ** or may be an SQLite URI. If the identified database file already exists,
  11490. ** it is overwritten.
  11491. **
  11492. ** If sqlite3_recover_init_sql() is invoked, then any recovered data will
  11493. ** be returned to the user as a series of SQL statements. Executing these
  11494. ** SQL statements results in the same database as would have been created
  11495. ** had sqlite3_recover_init() been used. For each SQL statement in the
  11496. ** output, the callback function passed as the third argument (xSql) is
  11497. ** invoked once. The first parameter is a passed a copy of the fourth argument
  11498. ** to this function (pCtx) as its first parameter, and a pointer to a
  11499. ** nul-terminated buffer containing the SQL statement formated as UTF-8 as
  11500. ** the second. If the xSql callback returns any value other than SQLITE_OK,
  11501. ** then processing is immediately abandoned and the value returned used as
  11502. ** the recover handle error code (see below).
  11503. **
  11504. ** If an out-of-memory error occurs, NULL may be returned instead of
  11505. ** a valid handle. In all other cases, it is the responsibility of the
  11506. ** application to avoid resource leaks by ensuring that
  11507. ** sqlite3_recover_finish() is called on all allocated handles.
  11508. */
  11509. sqlite3_recover *sqlite3_recover_init(
  11510. sqlite3* db,
  11511. const char *zDb,
  11512. const char *zUri
  11513. );
  11514. sqlite3_recover *sqlite3_recover_init_sql(
  11515. sqlite3* db,
  11516. const char *zDb,
  11517. int (*xSql)(void*, const char*),
  11518. void *pCtx
  11519. );
  11520. /*
  11521. ** Configure an sqlite3_recover object that has just been created using
  11522. ** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function
  11523. ** may only be called before the first call to sqlite3_recover_step()
  11524. ** or sqlite3_recover_run() on the object.
  11525. **
  11526. ** The second argument passed to this function must be one of the
  11527. ** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument
  11528. ** depend on the specific SQLITE_RECOVER_* symbol in use.
  11529. **
  11530. ** SQLITE_OK is returned if the configuration operation was successful,
  11531. ** or an SQLite error code otherwise.
  11532. */
  11533. int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg);
  11534. /*
  11535. ** SQLITE_RECOVER_LOST_AND_FOUND:
  11536. ** The pArg argument points to a string buffer containing the name
  11537. ** of a "lost-and-found" table in the output database, or NULL. If
  11538. ** the argument is non-NULL and the database contains seemingly
  11539. ** valid pages that cannot be associated with any table in the
  11540. ** recovered part of the schema, data is extracted from these
  11541. ** pages to add to the lost-and-found table.
  11542. **
  11543. ** SQLITE_RECOVER_FREELIST_CORRUPT:
  11544. ** The pArg value must actually be a pointer to a value of type
  11545. ** int containing value 0 or 1 cast as a (void*). If this option is set
  11546. ** (argument is 1) and a lost-and-found table has been configured using
  11547. ** SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is
  11548. ** corrupt and an attempt is made to recover records from pages that
  11549. ** appear to be linked into the freelist. Otherwise, pages on the freelist
  11550. ** are ignored. Setting this option can recover more data from the
  11551. ** database, but often ends up "recovering" deleted records. The default
  11552. ** value is 0 (clear).
  11553. **
  11554. ** SQLITE_RECOVER_ROWIDS:
  11555. ** The pArg value must actually be a pointer to a value of type
  11556. ** int containing value 0 or 1 cast as a (void*). If this option is set
  11557. ** (argument is 1), then an attempt is made to recover rowid values
  11558. ** that are not also INTEGER PRIMARY KEY values. If this option is
  11559. ** clear, then new rowids are assigned to all recovered rows. The
  11560. ** default value is 1 (set).
  11561. **
  11562. ** SQLITE_RECOVER_SLOWINDEXES:
  11563. ** The pArg value must actually be a pointer to a value of type
  11564. ** int containing value 0 or 1 cast as a (void*). If this option is clear
  11565. ** (argument is 0), then when creating an output database, the recover
  11566. ** module creates and populates non-UNIQUE indexes right at the end of the
  11567. ** recovery operation - after all recoverable data has been inserted
  11568. ** into the new database. This is faster overall, but means that the
  11569. ** final call to sqlite3_recover_step() for a recovery operation may
  11570. ** be need to create a large number of indexes, which may be very slow.
  11571. **
  11572. ** Or, if this option is set (argument is 1), then non-UNIQUE indexes
  11573. ** are created in the output database before it is populated with
  11574. ** recovered data. This is slower overall, but avoids the slow call
  11575. ** to sqlite3_recover_step() at the end of the recovery operation.
  11576. **
  11577. ** The default option value is 0.
  11578. */
  11579. #define SQLITE_RECOVER_LOST_AND_FOUND 1
  11580. #define SQLITE_RECOVER_FREELIST_CORRUPT 2
  11581. #define SQLITE_RECOVER_ROWIDS 3
  11582. #define SQLITE_RECOVER_SLOWINDEXES 4
  11583. /*
  11584. ** Perform a unit of work towards the recovery operation. This function
  11585. ** must normally be called multiple times to complete database recovery.
  11586. **
  11587. ** If no error occurs but the recovery operation is not completed, this
  11588. ** function returns SQLITE_OK. If recovery has been completed successfully
  11589. ** then SQLITE_DONE is returned. If an error has occurred, then an SQLite
  11590. ** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not
  11591. ** considered an error if some or all of the data cannot be recovered
  11592. ** due to database corruption.
  11593. **
  11594. ** Once sqlite3_recover_step() has returned a value other than SQLITE_OK,
  11595. ** all further such calls on the same recover handle are no-ops that return
  11596. ** the same non-SQLITE_OK value.
  11597. */
  11598. int sqlite3_recover_step(sqlite3_recover*);
  11599. /*
  11600. ** Run the recovery operation to completion. Return SQLITE_OK if successful,
  11601. ** or an SQLite error code otherwise. Calling this function is the same
  11602. ** as executing:
  11603. **
  11604. ** while( SQLITE_OK==sqlite3_recover_step(p) );
  11605. ** return sqlite3_recover_errcode(p);
  11606. */
  11607. int sqlite3_recover_run(sqlite3_recover*);
  11608. /*
  11609. ** If an error has been encountered during a prior call to
  11610. ** sqlite3_recover_step(), then this function attempts to return a
  11611. ** pointer to a buffer containing an English language explanation of
  11612. ** the error. If no error message is available, or if an out-of memory
  11613. ** error occurs while attempting to allocate a buffer in which to format
  11614. ** the error message, NULL is returned.
  11615. **
  11616. ** The returned buffer remains valid until the sqlite3_recover handle is
  11617. ** destroyed using sqlite3_recover_finish().
  11618. */
  11619. const char *sqlite3_recover_errmsg(sqlite3_recover*);
  11620. /*
  11621. ** If this function is called on an sqlite3_recover handle after
  11622. ** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK.
  11623. */
  11624. int sqlite3_recover_errcode(sqlite3_recover*);
  11625. /*
  11626. ** Clean up a recovery object created by a call to sqlite3_recover_init().
  11627. ** The results of using a recovery object with any API after it has been
  11628. ** passed to this function are undefined.
  11629. **
  11630. ** This function returns the same value as sqlite3_recover_errcode().
  11631. */
  11632. int sqlite3_recover_finish(sqlite3_recover*);
  11633. #ifdef __cplusplus
  11634. } /* end of the 'extern "C"' block */
  11635. #endif
  11636. #endif /* ifndef _SQLITE_RECOVER_H */
  11637. /************************* End ../ext/recover/sqlite3recover.h ********************/
  11638. /************************* Begin ../ext/recover/sqlite3recover.c ******************/
  11639. /*
  11640. ** 2022-08-27
  11641. **
  11642. ** The author disclaims copyright to this source code. In place of
  11643. ** a legal notice, here is a blessing:
  11644. **
  11645. ** May you do good and not evil.
  11646. ** May you find forgiveness for yourself and forgive others.
  11647. ** May you share freely, never taking more than you give.
  11648. **
  11649. *************************************************************************
  11650. **
  11651. */
  11652. /* #include "sqlite3recover.h" */
  11653. #include <assert.h>
  11654. #include <string.h>
  11655. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11656. /*
  11657. ** Declaration for public API function in file dbdata.c. This may be called
  11658. ** with NULL as the final two arguments to register the sqlite_dbptr and
  11659. ** sqlite_dbdata virtual tables with a database handle.
  11660. */
  11661. #ifdef _WIN32
  11662. #endif
  11663. int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*);
  11664. /* typedef unsigned int u32; */
  11665. /* typedef unsigned char u8; */
  11666. /* typedef sqlite3_int64 i64; */
  11667. typedef struct RecoverTable RecoverTable;
  11668. typedef struct RecoverColumn RecoverColumn;
  11669. /*
  11670. ** When recovering rows of data that can be associated with table
  11671. ** definitions recovered from the sqlite_schema table, each table is
  11672. ** represented by an instance of the following object.
  11673. **
  11674. ** iRoot:
  11675. ** The root page in the original database. Not necessarily (and usually
  11676. ** not) the same in the recovered database.
  11677. **
  11678. ** zTab:
  11679. ** Name of the table.
  11680. **
  11681. ** nCol/aCol[]:
  11682. ** aCol[] is an array of nCol columns. In the order in which they appear
  11683. ** in the table.
  11684. **
  11685. ** bIntkey:
  11686. ** Set to true for intkey tables, false for WITHOUT ROWID.
  11687. **
  11688. ** iRowidBind:
  11689. ** Each column in the aCol[] array has associated with it the index of
  11690. ** the bind parameter its values will be bound to in the INSERT statement
  11691. ** used to construct the output database. If the table does has a rowid
  11692. ** but not an INTEGER PRIMARY KEY column, then iRowidBind contains the
  11693. ** index of the bind paramater to which the rowid value should be bound.
  11694. ** Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
  11695. ** KEY column, then the rowid value should be bound to the index associated
  11696. ** with the column.
  11697. **
  11698. ** pNext:
  11699. ** All RecoverTable objects used by the recovery operation are allocated
  11700. ** and populated as part of creating the recovered database schema in
  11701. ** the output database, before any non-schema data are recovered. They
  11702. ** are then stored in a singly-linked list linked by this variable beginning
  11703. ** at sqlite3_recover.pTblList.
  11704. */
  11705. struct RecoverTable {
  11706. u32 iRoot; /* Root page in original database */
  11707. char *zTab; /* Name of table */
  11708. int nCol; /* Number of columns in table */
  11709. RecoverColumn *aCol; /* Array of columns */
  11710. int bIntkey; /* True for intkey, false for without rowid */
  11711. int iRowidBind; /* If >0, bind rowid to INSERT here */
  11712. RecoverTable *pNext;
  11713. };
  11714. /*
  11715. ** Each database column is represented by an instance of the following object
  11716. ** stored in the RecoverTable.aCol[] array of the associated table.
  11717. **
  11718. ** iField:
  11719. ** The index of the associated field within database records. Or -1 if
  11720. ** there is no associated field (e.g. for virtual generated columns).
  11721. **
  11722. ** iBind:
  11723. ** The bind index of the INSERT statement to bind this columns values
  11724. ** to. Or 0 if there is no such index (iff (iField<0)).
  11725. **
  11726. ** bIPK:
  11727. ** True if this is the INTEGER PRIMARY KEY column.
  11728. **
  11729. ** zCol:
  11730. ** Name of column.
  11731. **
  11732. ** eHidden:
  11733. ** A RECOVER_EHIDDEN_* constant value (see below for interpretation of each).
  11734. */
  11735. struct RecoverColumn {
  11736. int iField; /* Field in record on disk */
  11737. int iBind; /* Binding to use in INSERT */
  11738. int bIPK; /* True for IPK column */
  11739. char *zCol;
  11740. int eHidden;
  11741. };
  11742. #define RECOVER_EHIDDEN_NONE 0 /* Normal database column */
  11743. #define RECOVER_EHIDDEN_HIDDEN 1 /* Column is __HIDDEN__ */
  11744. #define RECOVER_EHIDDEN_VIRTUAL 2 /* Virtual generated column */
  11745. #define RECOVER_EHIDDEN_STORED 3 /* Stored generated column */
  11746. /*
  11747. ** Bitmap object used to track pages in the input database. Allocated
  11748. ** and manipulated only by the following functions:
  11749. **
  11750. ** recoverBitmapAlloc()
  11751. ** recoverBitmapFree()
  11752. ** recoverBitmapSet()
  11753. ** recoverBitmapQuery()
  11754. **
  11755. ** nPg:
  11756. ** Largest page number that may be stored in the bitmap. The range
  11757. ** of valid keys is 1 to nPg, inclusive.
  11758. **
  11759. ** aElem[]:
  11760. ** Array large enough to contain a bit for each key. For key value
  11761. ** iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32].
  11762. ** In other words, the following is true if bit iKey is set, or
  11763. ** false if it is clear:
  11764. **
  11765. ** (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0
  11766. */
  11767. typedef struct RecoverBitmap RecoverBitmap;
  11768. struct RecoverBitmap {
  11769. i64 nPg; /* Size of bitmap */
  11770. u32 aElem[1]; /* Array of 32-bit bitmasks */
  11771. };
  11772. /*
  11773. ** State variables (part of the sqlite3_recover structure) used while
  11774. ** recovering data for tables identified in the recovered schema (state
  11775. ** RECOVER_STATE_WRITING).
  11776. */
  11777. typedef struct RecoverStateW1 RecoverStateW1;
  11778. struct RecoverStateW1 {
  11779. sqlite3_stmt *pTbls;
  11780. sqlite3_stmt *pSel;
  11781. sqlite3_stmt *pInsert;
  11782. int nInsert;
  11783. RecoverTable *pTab; /* Table currently being written */
  11784. int nMax; /* Max column count in any schema table */
  11785. sqlite3_value **apVal; /* Array of nMax values */
  11786. int nVal; /* Number of valid entries in apVal[] */
  11787. int bHaveRowid;
  11788. i64 iRowid;
  11789. i64 iPrevPage;
  11790. int iPrevCell;
  11791. };
  11792. /*
  11793. ** State variables (part of the sqlite3_recover structure) used while
  11794. ** recovering data destined for the lost and found table (states
  11795. ** RECOVER_STATE_LOSTANDFOUND[123]).
  11796. */
  11797. typedef struct RecoverStateLAF RecoverStateLAF;
  11798. struct RecoverStateLAF {
  11799. RecoverBitmap *pUsed;
  11800. i64 nPg; /* Size of db in pages */
  11801. sqlite3_stmt *pAllAndParent;
  11802. sqlite3_stmt *pMapInsert;
  11803. sqlite3_stmt *pMaxField;
  11804. sqlite3_stmt *pUsedPages;
  11805. sqlite3_stmt *pFindRoot;
  11806. sqlite3_stmt *pInsert; /* INSERT INTO lost_and_found ... */
  11807. sqlite3_stmt *pAllPage;
  11808. sqlite3_stmt *pPageData;
  11809. sqlite3_value **apVal;
  11810. int nMaxField;
  11811. };
  11812. /*
  11813. ** Main recover handle structure.
  11814. */
  11815. struct sqlite3_recover {
  11816. /* Copies of sqlite3_recover_init[_sql]() parameters */
  11817. sqlite3 *dbIn; /* Input database */
  11818. char *zDb; /* Name of input db ("main" etc.) */
  11819. char *zUri; /* URI for output database */
  11820. void *pSqlCtx; /* SQL callback context */
  11821. int (*xSql)(void*,const char*); /* Pointer to SQL callback function */
  11822. /* Values configured by sqlite3_recover_config() */
  11823. char *zStateDb; /* State database to use (or NULL) */
  11824. char *zLostAndFound; /* Name of lost-and-found table (or NULL) */
  11825. int bFreelistCorrupt; /* SQLITE_RECOVER_FREELIST_CORRUPT setting */
  11826. int bRecoverRowid; /* SQLITE_RECOVER_ROWIDS setting */
  11827. int bSlowIndexes; /* SQLITE_RECOVER_SLOWINDEXES setting */
  11828. int pgsz;
  11829. int detected_pgsz;
  11830. int nReserve;
  11831. u8 *pPage1Disk;
  11832. u8 *pPage1Cache;
  11833. /* Error code and error message */
  11834. int errCode; /* For sqlite3_recover_errcode() */
  11835. char *zErrMsg; /* For sqlite3_recover_errmsg() */
  11836. int eState;
  11837. int bCloseTransaction;
  11838. /* Variables used with eState==RECOVER_STATE_WRITING */
  11839. RecoverStateW1 w1;
  11840. /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */
  11841. RecoverStateLAF laf;
  11842. /* Fields used within sqlite3_recover_run() */
  11843. sqlite3 *dbOut; /* Output database */
  11844. sqlite3_stmt *pGetPage; /* SELECT against input db sqlite_dbdata */
  11845. RecoverTable *pTblList; /* List of tables recovered from schema */
  11846. };
  11847. /*
  11848. ** The various states in which an sqlite3_recover object may exist:
  11849. **
  11850. ** RECOVER_STATE_INIT:
  11851. ** The object is initially created in this state. sqlite3_recover_step()
  11852. ** has yet to be called. This is the only state in which it is permitted
  11853. ** to call sqlite3_recover_config().
  11854. **
  11855. ** RECOVER_STATE_WRITING:
  11856. **
  11857. ** RECOVER_STATE_LOSTANDFOUND1:
  11858. ** State to populate the bitmap of pages used by other tables or the
  11859. ** database freelist.
  11860. **
  11861. ** RECOVER_STATE_LOSTANDFOUND2:
  11862. ** Populate the recovery.map table - used to figure out a "root" page
  11863. ** for each lost page from in the database from which records are
  11864. ** extracted.
  11865. **
  11866. ** RECOVER_STATE_LOSTANDFOUND3:
  11867. ** Populate the lost-and-found table itself.
  11868. */
  11869. #define RECOVER_STATE_INIT 0
  11870. #define RECOVER_STATE_WRITING 1
  11871. #define RECOVER_STATE_LOSTANDFOUND1 2
  11872. #define RECOVER_STATE_LOSTANDFOUND2 3
  11873. #define RECOVER_STATE_LOSTANDFOUND3 4
  11874. #define RECOVER_STATE_SCHEMA2 5
  11875. #define RECOVER_STATE_DONE 6
  11876. /*
  11877. ** Global variables used by this extension.
  11878. */
  11879. typedef struct RecoverGlobal RecoverGlobal;
  11880. struct RecoverGlobal {
  11881. const sqlite3_io_methods *pMethods;
  11882. sqlite3_recover *p;
  11883. };
  11884. static RecoverGlobal recover_g;
  11885. /*
  11886. ** Use this static SQLite mutex to protect the globals during the
  11887. ** first call to sqlite3_recover_step().
  11888. */
  11889. #define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2
  11890. /*
  11891. ** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid).
  11892. */
  11893. #define RECOVER_ROWID_DEFAULT 1
  11894. /*
  11895. ** Mutex handling:
  11896. **
  11897. ** recoverEnterMutex() - Enter the recovery mutex
  11898. ** recoverLeaveMutex() - Leave the recovery mutex
  11899. ** recoverAssertMutexHeld() - Assert that the recovery mutex is held
  11900. */
  11901. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
  11902. # define recoverEnterMutex()
  11903. # define recoverLeaveMutex()
  11904. #else
  11905. static void recoverEnterMutex(void){
  11906. sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
  11907. }
  11908. static void recoverLeaveMutex(void){
  11909. sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
  11910. }
  11911. #endif
  11912. #if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)
  11913. static void recoverAssertMutexHeld(void){
  11914. assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );
  11915. }
  11916. #else
  11917. # define recoverAssertMutexHeld()
  11918. #endif
  11919. /*
  11920. ** Like strlen(). But handles NULL pointer arguments.
  11921. */
  11922. static int recoverStrlen(const char *zStr){
  11923. if( zStr==0 ) return 0;
  11924. return (int)(strlen(zStr)&0x7fffffff);
  11925. }
  11926. /*
  11927. ** This function is a no-op if the recover handle passed as the first
  11928. ** argument already contains an error (if p->errCode!=SQLITE_OK).
  11929. **
  11930. ** Otherwise, an attempt is made to allocate, zero and return a buffer nByte
  11931. ** bytes in size. If successful, a pointer to the new buffer is returned. Or,
  11932. ** if an OOM error occurs, NULL is returned and the handle error code
  11933. ** (p->errCode) set to SQLITE_NOMEM.
  11934. */
  11935. static void *recoverMalloc(sqlite3_recover *p, i64 nByte){
  11936. void *pRet = 0;
  11937. assert( nByte>0 );
  11938. if( p->errCode==SQLITE_OK ){
  11939. pRet = sqlite3_malloc64(nByte);
  11940. if( pRet ){
  11941. memset(pRet, 0, nByte);
  11942. }else{
  11943. p->errCode = SQLITE_NOMEM;
  11944. }
  11945. }
  11946. return pRet;
  11947. }
  11948. /*
  11949. ** Set the error code and error message for the recover handle passed as
  11950. ** the first argument. The error code is set to the value of parameter
  11951. ** errCode.
  11952. **
  11953. ** Parameter zFmt must be a printf() style formatting string. The handle
  11954. ** error message is set to the result of using any trailing arguments for
  11955. ** parameter substitutions in the formatting string.
  11956. **
  11957. ** For example:
  11958. **
  11959. ** recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename);
  11960. */
  11961. static int recoverError(
  11962. sqlite3_recover *p,
  11963. int errCode,
  11964. const char *zFmt, ...
  11965. ){
  11966. char *z = 0;
  11967. va_list ap;
  11968. va_start(ap, zFmt);
  11969. if( zFmt ){
  11970. z = sqlite3_vmprintf(zFmt, ap);
  11971. va_end(ap);
  11972. }
  11973. sqlite3_free(p->zErrMsg);
  11974. p->zErrMsg = z;
  11975. p->errCode = errCode;
  11976. return errCode;
  11977. }
  11978. /*
  11979. ** This function is a no-op if p->errCode is initially other than SQLITE_OK.
  11980. ** In this case it returns NULL.
  11981. **
  11982. ** Otherwise, an attempt is made to allocate and return a bitmap object
  11983. ** large enough to store a bit for all page numbers between 1 and nPg,
  11984. ** inclusive. The bitmap is initially zeroed.
  11985. */
  11986. static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){
  11987. int nElem = (nPg+1+31) / 32;
  11988. int nByte = sizeof(RecoverBitmap) + nElem*sizeof(u32);
  11989. RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte);
  11990. if( pRet ){
  11991. pRet->nPg = nPg;
  11992. }
  11993. return pRet;
  11994. }
  11995. /*
  11996. ** Free a bitmap object allocated by recoverBitmapAlloc().
  11997. */
  11998. static void recoverBitmapFree(RecoverBitmap *pMap){
  11999. sqlite3_free(pMap);
  12000. }
  12001. /*
  12002. ** Set the bit associated with page iPg in bitvec pMap.
  12003. */
  12004. static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){
  12005. if( iPg<=pMap->nPg ){
  12006. int iElem = (iPg / 32);
  12007. int iBit = (iPg % 32);
  12008. pMap->aElem[iElem] |= (((u32)1) << iBit);
  12009. }
  12010. }
  12011. /*
  12012. ** Query bitmap object pMap for the state of the bit associated with page
  12013. ** iPg. Return 1 if it is set, or 0 otherwise.
  12014. */
  12015. static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){
  12016. int ret = 1;
  12017. if( iPg<=pMap->nPg && iPg>0 ){
  12018. int iElem = (iPg / 32);
  12019. int iBit = (iPg % 32);
  12020. ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0;
  12021. }
  12022. return ret;
  12023. }
  12024. /*
  12025. ** Set the recover handle error to the error code and message returned by
  12026. ** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database
  12027. ** handle db.
  12028. */
  12029. static int recoverDbError(sqlite3_recover *p, sqlite3 *db){
  12030. return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db));
  12031. }
  12032. /*
  12033. ** This function is a no-op if recover handle p already contains an error
  12034. ** (if p->errCode!=SQLITE_OK).
  12035. **
  12036. ** Otherwise, it attempts to prepare the SQL statement in zSql against
  12037. ** database handle db. If successful, the statement handle is returned.
  12038. ** Or, if an error occurs, NULL is returned and an error left in the
  12039. ** recover handle.
  12040. */
  12041. static sqlite3_stmt *recoverPrepare(
  12042. sqlite3_recover *p,
  12043. sqlite3 *db,
  12044. const char *zSql
  12045. ){
  12046. sqlite3_stmt *pStmt = 0;
  12047. if( p->errCode==SQLITE_OK ){
  12048. if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){
  12049. recoverDbError(p, db);
  12050. }
  12051. }
  12052. return pStmt;
  12053. }
  12054. /*
  12055. ** This function is a no-op if recover handle p already contains an error
  12056. ** (if p->errCode!=SQLITE_OK).
  12057. **
  12058. ** Otherwise, argument zFmt is used as a printf() style format string,
  12059. ** along with any trailing arguments, to create an SQL statement. This
  12060. ** SQL statement is prepared against database handle db and, if successful,
  12061. ** the statment handle returned. Or, if an error occurs - either during
  12062. ** the printf() formatting or when preparing the resulting SQL - an
  12063. ** error code and message are left in the recover handle.
  12064. */
  12065. static sqlite3_stmt *recoverPreparePrintf(
  12066. sqlite3_recover *p,
  12067. sqlite3 *db,
  12068. const char *zFmt, ...
  12069. ){
  12070. sqlite3_stmt *pStmt = 0;
  12071. if( p->errCode==SQLITE_OK ){
  12072. va_list ap;
  12073. char *z;
  12074. va_start(ap, zFmt);
  12075. z = sqlite3_vmprintf(zFmt, ap);
  12076. va_end(ap);
  12077. if( z==0 ){
  12078. p->errCode = SQLITE_NOMEM;
  12079. }else{
  12080. pStmt = recoverPrepare(p, db, z);
  12081. sqlite3_free(z);
  12082. }
  12083. }
  12084. return pStmt;
  12085. }
  12086. /*
  12087. ** Reset SQLite statement handle pStmt. If the call to sqlite3_reset()
  12088. ** indicates that an error occurred, and there is not already an error
  12089. ** in the recover handle passed as the first argument, set the error
  12090. ** code and error message appropriately.
  12091. **
  12092. ** This function returns a copy of the statement handle pointer passed
  12093. ** as the second argument.
  12094. */
  12095. static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){
  12096. int rc = sqlite3_reset(pStmt);
  12097. if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){
  12098. recoverDbError(p, sqlite3_db_handle(pStmt));
  12099. }
  12100. return pStmt;
  12101. }
  12102. /*
  12103. ** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset()
  12104. ** indicates that an error occurred, and there is not already an error
  12105. ** in the recover handle passed as the first argument, set the error
  12106. ** code and error message appropriately.
  12107. */
  12108. static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){
  12109. sqlite3 *db = sqlite3_db_handle(pStmt);
  12110. int rc = sqlite3_finalize(pStmt);
  12111. if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){
  12112. recoverDbError(p, db);
  12113. }
  12114. }
  12115. /*
  12116. ** This function is a no-op if recover handle p already contains an error
  12117. ** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
  12118. ** case.
  12119. **
  12120. ** Otherwise, execute SQL script zSql. If successful, return SQLITE_OK.
  12121. ** Or, if an error occurs, leave an error code and message in the recover
  12122. ** handle and return a copy of the error code.
  12123. */
  12124. static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
  12125. if( p->errCode==SQLITE_OK ){
  12126. int rc = sqlite3_exec(db, zSql, 0, 0, 0);
  12127. if( rc ){
  12128. recoverDbError(p, db);
  12129. }
  12130. }
  12131. return p->errCode;
  12132. }
  12133. /*
  12134. ** Bind the value pVal to parameter iBind of statement pStmt. Leave an
  12135. ** error in the recover handle passed as the first argument if an error
  12136. ** (e.g. an OOM) occurs.
  12137. */
  12138. static void recoverBindValue(
  12139. sqlite3_recover *p,
  12140. sqlite3_stmt *pStmt,
  12141. int iBind,
  12142. sqlite3_value *pVal
  12143. ){
  12144. if( p->errCode==SQLITE_OK ){
  12145. int rc = sqlite3_bind_value(pStmt, iBind, pVal);
  12146. if( rc ) recoverError(p, rc, 0);
  12147. }
  12148. }
  12149. /*
  12150. ** This function is a no-op if recover handle p already contains an error
  12151. ** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
  12152. **
  12153. ** Otherwise, an attempt is made to interpret zFmt as a printf() style
  12154. ** formatting string and the result of using the trailing arguments for
  12155. ** parameter substitution with it written into a buffer obtained from
  12156. ** sqlite3_malloc(). If successful, a pointer to the buffer is returned.
  12157. ** It is the responsibility of the caller to eventually free the buffer
  12158. ** using sqlite3_free().
  12159. **
  12160. ** Or, if an error occurs, an error code and message is left in the recover
  12161. ** handle and NULL returned.
  12162. */
  12163. static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){
  12164. va_list ap;
  12165. char *z;
  12166. va_start(ap, zFmt);
  12167. z = sqlite3_vmprintf(zFmt, ap);
  12168. va_end(ap);
  12169. if( p->errCode==SQLITE_OK ){
  12170. if( z==0 ) p->errCode = SQLITE_NOMEM;
  12171. }else{
  12172. sqlite3_free(z);
  12173. z = 0;
  12174. }
  12175. return z;
  12176. }
  12177. /*
  12178. ** This function is a no-op if recover handle p already contains an error
  12179. ** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
  12180. **
  12181. ** Otherwise, execute "PRAGMA page_count" against the input database. If
  12182. ** successful, return the integer result. Or, if an error occurs, leave an
  12183. ** error code and error message in the sqlite3_recover handle and return
  12184. ** zero.
  12185. */
  12186. static i64 recoverPageCount(sqlite3_recover *p){
  12187. i64 nPg = 0;
  12188. if( p->errCode==SQLITE_OK ){
  12189. sqlite3_stmt *pStmt = 0;
  12190. pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb);
  12191. if( pStmt ){
  12192. sqlite3_step(pStmt);
  12193. nPg = sqlite3_column_int64(pStmt, 0);
  12194. }
  12195. recoverFinalize(p, pStmt);
  12196. }
  12197. return nPg;
  12198. }
  12199. /*
  12200. ** Implementation of SQL scalar function "read_i32". The first argument to
  12201. ** this function must be a blob. The second a non-negative integer. This
  12202. ** function reads and returns a 32-bit big-endian integer from byte
  12203. ** offset (4*<arg2>) of the blob.
  12204. **
  12205. ** SELECT read_i32(<blob>, <idx>)
  12206. */
  12207. static void recoverReadI32(
  12208. sqlite3_context *context,
  12209. int argc,
  12210. sqlite3_value **argv
  12211. ){
  12212. const unsigned char *pBlob;
  12213. int nBlob;
  12214. int iInt;
  12215. assert( argc==2 );
  12216. nBlob = sqlite3_value_bytes(argv[0]);
  12217. pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
  12218. iInt = sqlite3_value_int(argv[1]) & 0xFFFF;
  12219. if( (iInt+1)*4<=nBlob ){
  12220. const unsigned char *a = &pBlob[iInt*4];
  12221. i64 iVal = ((i64)a[0]<<24)
  12222. + ((i64)a[1]<<16)
  12223. + ((i64)a[2]<< 8)
  12224. + ((i64)a[3]<< 0);
  12225. sqlite3_result_int64(context, iVal);
  12226. }
  12227. }
  12228. /*
  12229. ** Implementation of SQL scalar function "page_is_used". This function
  12230. ** is used as part of the procedure for locating orphan rows for the
  12231. ** lost-and-found table, and it depends on those routines having populated
  12232. ** the sqlite3_recover.laf.pUsed variable.
  12233. **
  12234. ** The only argument to this function is a page-number. It returns true
  12235. ** if the page has already been used somehow during data recovery, or false
  12236. ** otherwise.
  12237. **
  12238. ** SELECT page_is_used(<pgno>);
  12239. */
  12240. static void recoverPageIsUsed(
  12241. sqlite3_context *pCtx,
  12242. int nArg,
  12243. sqlite3_value **apArg
  12244. ){
  12245. sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
  12246. i64 pgno = sqlite3_value_int64(apArg[0]);
  12247. assert( nArg==1 );
  12248. sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno));
  12249. }
  12250. /*
  12251. ** The implementation of a user-defined SQL function invoked by the
  12252. ** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages
  12253. ** of the database being recovered.
  12254. **
  12255. ** This function always takes a single integer argument. If the argument
  12256. ** is zero, then the value returned is the number of pages in the db being
  12257. ** recovered. If the argument is greater than zero, it is a page number.
  12258. ** The value returned in this case is an SQL blob containing the data for
  12259. ** the identified page of the db being recovered. e.g.
  12260. **
  12261. ** SELECT getpage(0); -- return number of pages in db
  12262. ** SELECT getpage(4); -- return page 4 of db as a blob of data
  12263. */
  12264. static void recoverGetPage(
  12265. sqlite3_context *pCtx,
  12266. int nArg,
  12267. sqlite3_value **apArg
  12268. ){
  12269. sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
  12270. i64 pgno = sqlite3_value_int64(apArg[0]);
  12271. sqlite3_stmt *pStmt = 0;
  12272. assert( nArg==1 );
  12273. if( pgno==0 ){
  12274. i64 nPg = recoverPageCount(p);
  12275. sqlite3_result_int64(pCtx, nPg);
  12276. return;
  12277. }else{
  12278. if( p->pGetPage==0 ){
  12279. pStmt = p->pGetPage = recoverPreparePrintf(
  12280. p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb
  12281. );
  12282. }else if( p->errCode==SQLITE_OK ){
  12283. pStmt = p->pGetPage;
  12284. }
  12285. if( pStmt ){
  12286. sqlite3_bind_int64(pStmt, 1, pgno);
  12287. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  12288. const u8 *aPg;
  12289. int nPg;
  12290. assert( p->errCode==SQLITE_OK );
  12291. aPg = sqlite3_column_blob(pStmt, 0);
  12292. nPg = sqlite3_column_bytes(pStmt, 0);
  12293. if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){
  12294. aPg = p->pPage1Disk;
  12295. }
  12296. sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT);
  12297. }
  12298. recoverReset(p, pStmt);
  12299. }
  12300. }
  12301. if( p->errCode ){
  12302. if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1);
  12303. sqlite3_result_error_code(pCtx, p->errCode);
  12304. }
  12305. }
  12306. /*
  12307. ** Find a string that is not found anywhere in z[]. Return a pointer
  12308. ** to that string.
  12309. **
  12310. ** Try to use zA and zB first. If both of those are already found in z[]
  12311. ** then make up some string and store it in the buffer zBuf.
  12312. */
  12313. static const char *recoverUnusedString(
  12314. const char *z, /* Result must not appear anywhere in z */
  12315. const char *zA, const char *zB, /* Try these first */
  12316. char *zBuf /* Space to store a generated string */
  12317. ){
  12318. unsigned i = 0;
  12319. if( strstr(z, zA)==0 ) return zA;
  12320. if( strstr(z, zB)==0 ) return zB;
  12321. do{
  12322. sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
  12323. }while( strstr(z,zBuf)!=0 );
  12324. return zBuf;
  12325. }
  12326. /*
  12327. ** Implementation of scalar SQL function "escape_crnl". The argument passed to
  12328. ** this function is the output of built-in function quote(). If the first
  12329. ** character of the input is "'", indicating that the value passed to quote()
  12330. ** was a text value, then this function searches the input for "\n" and "\r"
  12331. ** characters and adds a wrapper similar to the following:
  12332. **
  12333. ** replace(replace(<input>, '\n', char(10), '\r', char(13));
  12334. **
  12335. ** Or, if the first character of the input is not "'", then a copy of the input
  12336. ** is returned.
  12337. */
  12338. static void recoverEscapeCrnl(
  12339. sqlite3_context *context,
  12340. int argc,
  12341. sqlite3_value **argv
  12342. ){
  12343. const char *zText = (const char*)sqlite3_value_text(argv[0]);
  12344. if( zText && zText[0]=='\'' ){
  12345. int nText = sqlite3_value_bytes(argv[0]);
  12346. int i;
  12347. char zBuf1[20];
  12348. char zBuf2[20];
  12349. const char *zNL = 0;
  12350. const char *zCR = 0;
  12351. int nCR = 0;
  12352. int nNL = 0;
  12353. for(i=0; zText[i]; i++){
  12354. if( zNL==0 && zText[i]=='\n' ){
  12355. zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1);
  12356. nNL = (int)strlen(zNL);
  12357. }
  12358. if( zCR==0 && zText[i]=='\r' ){
  12359. zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2);
  12360. nCR = (int)strlen(zCR);
  12361. }
  12362. }
  12363. if( zNL || zCR ){
  12364. int iOut = 0;
  12365. i64 nMax = (nNL > nCR) ? nNL : nCR;
  12366. i64 nAlloc = nMax * nText + (nMax+64)*2;
  12367. char *zOut = (char*)sqlite3_malloc64(nAlloc);
  12368. if( zOut==0 ){
  12369. sqlite3_result_error_nomem(context);
  12370. return;
  12371. }
  12372. if( zNL && zCR ){
  12373. memcpy(&zOut[iOut], "replace(replace(", 16);
  12374. iOut += 16;
  12375. }else{
  12376. memcpy(&zOut[iOut], "replace(", 8);
  12377. iOut += 8;
  12378. }
  12379. for(i=0; zText[i]; i++){
  12380. if( zText[i]=='\n' ){
  12381. memcpy(&zOut[iOut], zNL, nNL);
  12382. iOut += nNL;
  12383. }else if( zText[i]=='\r' ){
  12384. memcpy(&zOut[iOut], zCR, nCR);
  12385. iOut += nCR;
  12386. }else{
  12387. zOut[iOut] = zText[i];
  12388. iOut++;
  12389. }
  12390. }
  12391. if( zNL ){
  12392. memcpy(&zOut[iOut], ",'", 2); iOut += 2;
  12393. memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
  12394. memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
  12395. }
  12396. if( zCR ){
  12397. memcpy(&zOut[iOut], ",'", 2); iOut += 2;
  12398. memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
  12399. memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
  12400. }
  12401. sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
  12402. sqlite3_free(zOut);
  12403. return;
  12404. }
  12405. }
  12406. sqlite3_result_value(context, argv[0]);
  12407. }
  12408. /*
  12409. ** This function is a no-op if recover handle p already contains an error
  12410. ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
  12411. ** this case.
  12412. **
  12413. ** Otherwise, attempt to populate temporary table "recovery.schema" with the
  12414. ** parts of the database schema that can be extracted from the input database.
  12415. **
  12416. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  12417. ** and error message are left in the recover handle and a copy of the
  12418. ** error code returned. It is not considered an error if part of all of
  12419. ** the database schema cannot be recovered due to corruption.
  12420. */
  12421. static int recoverCacheSchema(sqlite3_recover *p){
  12422. return recoverExec(p, p->dbOut,
  12423. "WITH RECURSIVE pages(p) AS ("
  12424. " SELECT 1"
  12425. " UNION"
  12426. " SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p"
  12427. ")"
  12428. "INSERT INTO recovery.schema SELECT"
  12429. " max(CASE WHEN field=0 THEN value ELSE NULL END),"
  12430. " max(CASE WHEN field=1 THEN value ELSE NULL END),"
  12431. " max(CASE WHEN field=2 THEN value ELSE NULL END),"
  12432. " max(CASE WHEN field=3 THEN value ELSE NULL END),"
  12433. " max(CASE WHEN field=4 THEN value ELSE NULL END)"
  12434. "FROM sqlite_dbdata('getpage()') WHERE pgno IN ("
  12435. " SELECT p FROM pages"
  12436. ") GROUP BY pgno, cell"
  12437. );
  12438. }
  12439. /*
  12440. ** If this recover handle is not in SQL callback mode (i.e. was not created
  12441. ** using sqlite3_recover_init_sql()) of if an error has already occurred,
  12442. ** this function is a no-op. Otherwise, issue a callback with SQL statement
  12443. ** zSql as the parameter.
  12444. **
  12445. ** If the callback returns non-zero, set the recover handle error code to
  12446. ** the value returned (so that the caller will abandon processing).
  12447. */
  12448. static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){
  12449. if( p->errCode==SQLITE_OK && p->xSql ){
  12450. int res = p->xSql(p->pSqlCtx, zSql);
  12451. if( res ){
  12452. recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res);
  12453. }
  12454. }
  12455. }
  12456. /*
  12457. ** Transfer the following settings from the input database to the output
  12458. ** database:
  12459. **
  12460. ** + page-size,
  12461. ** + auto-vacuum settings,
  12462. ** + database encoding,
  12463. ** + user-version (PRAGMA user_version), and
  12464. ** + application-id (PRAGMA application_id), and
  12465. */
  12466. static void recoverTransferSettings(sqlite3_recover *p){
  12467. const char *aPragma[] = {
  12468. "encoding",
  12469. "page_size",
  12470. "auto_vacuum",
  12471. "user_version",
  12472. "application_id"
  12473. };
  12474. int ii;
  12475. /* Truncate the output database to 0 pages in size. This is done by
  12476. ** opening a new, empty, temp db, then using the backup API to clobber
  12477. ** any existing output db with a copy of it. */
  12478. if( p->errCode==SQLITE_OK ){
  12479. sqlite3 *db2 = 0;
  12480. int rc = sqlite3_open("", &db2);
  12481. if( rc!=SQLITE_OK ){
  12482. recoverDbError(p, db2);
  12483. return;
  12484. }
  12485. for(ii=0; ii<sizeof(aPragma)/sizeof(aPragma[0]); ii++){
  12486. const char *zPrag = aPragma[ii];
  12487. sqlite3_stmt *p1 = 0;
  12488. p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag);
  12489. if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){
  12490. const char *zArg = (const char*)sqlite3_column_text(p1, 0);
  12491. char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg);
  12492. recoverSqlCallback(p, z2);
  12493. recoverExec(p, db2, z2);
  12494. sqlite3_free(z2);
  12495. if( zArg==0 ){
  12496. recoverError(p, SQLITE_NOMEM, 0);
  12497. }
  12498. }
  12499. recoverFinalize(p, p1);
  12500. }
  12501. recoverExec(p, db2, "CREATE TABLE t1(a); DROP TABLE t1;");
  12502. if( p->errCode==SQLITE_OK ){
  12503. sqlite3 *db = p->dbOut;
  12504. sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main");
  12505. if( pBackup ){
  12506. sqlite3_backup_step(pBackup, -1);
  12507. p->errCode = sqlite3_backup_finish(pBackup);
  12508. }else{
  12509. recoverDbError(p, db);
  12510. }
  12511. }
  12512. sqlite3_close(db2);
  12513. }
  12514. }
  12515. /*
  12516. ** This function is a no-op if recover handle p already contains an error
  12517. ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
  12518. ** this case.
  12519. **
  12520. ** Otherwise, an attempt is made to open the output database, attach
  12521. ** and create the schema of the temporary database used to store
  12522. ** intermediate data, and to register all required user functions and
  12523. ** virtual table modules with the output handle.
  12524. **
  12525. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  12526. ** and error message are left in the recover handle and a copy of the
  12527. ** error code returned.
  12528. */
  12529. static int recoverOpenOutput(sqlite3_recover *p){
  12530. struct Func {
  12531. const char *zName;
  12532. int nArg;
  12533. void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
  12534. } aFunc[] = {
  12535. { "getpage", 1, recoverGetPage },
  12536. { "page_is_used", 1, recoverPageIsUsed },
  12537. { "read_i32", 2, recoverReadI32 },
  12538. { "escape_crnl", 1, recoverEscapeCrnl },
  12539. };
  12540. const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
  12541. sqlite3 *db = 0; /* New database handle */
  12542. int ii; /* For iterating through aFunc[] */
  12543. assert( p->dbOut==0 );
  12544. if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){
  12545. recoverDbError(p, db);
  12546. }
  12547. /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules.
  12548. ** These two are registered with the output database handle - this
  12549. ** module depends on the input handle supporting the sqlite_dbpage
  12550. ** virtual table only. */
  12551. if( p->errCode==SQLITE_OK ){
  12552. p->errCode = sqlite3_dbdata_init(db, 0, 0);
  12553. }
  12554. /* Register the custom user-functions with the output handle. */
  12555. for(ii=0; p->errCode==SQLITE_OK && ii<sizeof(aFunc)/sizeof(aFunc[0]); ii++){
  12556. p->errCode = sqlite3_create_function(db, aFunc[ii].zName,
  12557. aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0
  12558. );
  12559. }
  12560. p->dbOut = db;
  12561. return p->errCode;
  12562. }
  12563. /*
  12564. ** Attach the auxiliary database 'recovery' to the output database handle.
  12565. ** This temporary database is used during the recovery process and then
  12566. ** discarded.
  12567. */
  12568. static void recoverOpenRecovery(sqlite3_recover *p){
  12569. char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb);
  12570. recoverExec(p, p->dbOut, zSql);
  12571. recoverExec(p, p->dbOut,
  12572. "PRAGMA writable_schema = 1;"
  12573. "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT);"
  12574. "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
  12575. );
  12576. sqlite3_free(zSql);
  12577. }
  12578. /*
  12579. ** This function is a no-op if recover handle p already contains an error
  12580. ** (if p->errCode!=SQLITE_OK).
  12581. **
  12582. ** Otherwise, argument zName must be the name of a table that has just been
  12583. ** created in the output database. This function queries the output db
  12584. ** for the schema of said table, and creates a RecoverTable object to
  12585. ** store the schema in memory. The new RecoverTable object is linked into
  12586. ** the list at sqlite3_recover.pTblList.
  12587. **
  12588. ** Parameter iRoot must be the root page of table zName in the INPUT
  12589. ** database.
  12590. */
  12591. static void recoverAddTable(
  12592. sqlite3_recover *p,
  12593. const char *zName, /* Name of table created in output db */
  12594. i64 iRoot /* Root page of same table in INPUT db */
  12595. ){
  12596. sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
  12597. "PRAGMA table_xinfo(%Q)", zName
  12598. );
  12599. if( pStmt ){
  12600. int iPk = -1;
  12601. int iBind = 1;
  12602. RecoverTable *pNew = 0;
  12603. int nCol = 0;
  12604. int nName = recoverStrlen(zName);
  12605. int nByte = 0;
  12606. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  12607. nCol++;
  12608. nByte += (sqlite3_column_bytes(pStmt, 1)+1);
  12609. }
  12610. nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1;
  12611. recoverReset(p, pStmt);
  12612. pNew = recoverMalloc(p, nByte);
  12613. if( pNew ){
  12614. int i = 0;
  12615. int iField = 0;
  12616. char *csr = 0;
  12617. pNew->aCol = (RecoverColumn*)&pNew[1];
  12618. pNew->zTab = csr = (char*)&pNew->aCol[nCol];
  12619. pNew->nCol = nCol;
  12620. pNew->iRoot = iRoot;
  12621. memcpy(csr, zName, nName);
  12622. csr += nName+1;
  12623. for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){
  12624. int iPKF = sqlite3_column_int(pStmt, 5);
  12625. int n = sqlite3_column_bytes(pStmt, 1);
  12626. const char *z = (const char*)sqlite3_column_text(pStmt, 1);
  12627. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  12628. int eHidden = sqlite3_column_int(pStmt, 6);
  12629. if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i;
  12630. if( iPKF>1 ) iPk = -2;
  12631. pNew->aCol[i].zCol = csr;
  12632. pNew->aCol[i].eHidden = eHidden;
  12633. if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){
  12634. pNew->aCol[i].iField = -1;
  12635. }else{
  12636. pNew->aCol[i].iField = iField++;
  12637. }
  12638. if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
  12639. && eHidden!=RECOVER_EHIDDEN_STORED
  12640. ){
  12641. pNew->aCol[i].iBind = iBind++;
  12642. }
  12643. memcpy(csr, z, n);
  12644. csr += (n+1);
  12645. }
  12646. pNew->pNext = p->pTblList;
  12647. p->pTblList = pNew;
  12648. pNew->bIntkey = 1;
  12649. }
  12650. recoverFinalize(p, pStmt);
  12651. pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName);
  12652. while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  12653. int iField = sqlite3_column_int(pStmt, 0);
  12654. int iCol = sqlite3_column_int(pStmt, 1);
  12655. assert( iField<pNew->nCol && iCol<pNew->nCol );
  12656. pNew->aCol[iCol].iField = iField;
  12657. pNew->bIntkey = 0;
  12658. iPk = -2;
  12659. }
  12660. recoverFinalize(p, pStmt);
  12661. if( p->errCode==SQLITE_OK ){
  12662. if( iPk>=0 ){
  12663. pNew->aCol[iPk].bIPK = 1;
  12664. }else if( pNew->bIntkey ){
  12665. pNew->iRowidBind = iBind++;
  12666. }
  12667. }
  12668. }
  12669. }
  12670. /*
  12671. ** This function is called after recoverCacheSchema() has cached those parts
  12672. ** of the input database schema that could be recovered in temporary table
  12673. ** "recovery.schema". This function creates in the output database copies
  12674. ** of all parts of that schema that must be created before the tables can
  12675. ** be populated. Specifically, this means:
  12676. **
  12677. ** * all tables that are not VIRTUAL, and
  12678. ** * UNIQUE indexes.
  12679. **
  12680. ** If the recovery handle uses SQL callbacks, then callbacks containing
  12681. ** the associated "CREATE TABLE" and "CREATE INDEX" statements are made.
  12682. **
  12683. ** Additionally, records are added to the sqlite_schema table of the
  12684. ** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE
  12685. ** records are written directly to sqlite_schema, not actually executed.
  12686. ** If the handle is in SQL callback mode, then callbacks are invoked
  12687. ** with equivalent SQL statements.
  12688. */
  12689. static int recoverWriteSchema1(sqlite3_recover *p){
  12690. sqlite3_stmt *pSelect = 0;
  12691. sqlite3_stmt *pTblname = 0;
  12692. pSelect = recoverPrepare(p, p->dbOut,
  12693. "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS ("
  12694. " SELECT rootpage, name, sql, "
  12695. " type='table', "
  12696. " sql LIKE 'create virtual%',"
  12697. " (type='index' AND (sql LIKE '%unique%' OR ?1))"
  12698. " FROM recovery.schema"
  12699. ")"
  12700. "SELECT rootpage, tbl, isVirtual, name, sql"
  12701. " FROM dbschema "
  12702. " WHERE tbl OR isIndex"
  12703. " ORDER BY tbl DESC, name=='sqlite_sequence' DESC"
  12704. );
  12705. pTblname = recoverPrepare(p, p->dbOut,
  12706. "SELECT name FROM sqlite_schema "
  12707. "WHERE type='table' ORDER BY rowid DESC LIMIT 1"
  12708. );
  12709. if( pSelect ){
  12710. sqlite3_bind_int(pSelect, 1, p->bSlowIndexes);
  12711. while( sqlite3_step(pSelect)==SQLITE_ROW ){
  12712. i64 iRoot = sqlite3_column_int64(pSelect, 0);
  12713. int bTable = sqlite3_column_int(pSelect, 1);
  12714. int bVirtual = sqlite3_column_int(pSelect, 2);
  12715. const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
  12716. const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
  12717. char *zFree = 0;
  12718. int rc = SQLITE_OK;
  12719. if( bVirtual ){
  12720. zSql = (const char*)(zFree = recoverMPrintf(p,
  12721. "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
  12722. zName, zName, zSql
  12723. ));
  12724. }
  12725. rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
  12726. if( rc==SQLITE_OK ){
  12727. recoverSqlCallback(p, zSql);
  12728. if( bTable && !bVirtual ){
  12729. if( SQLITE_ROW==sqlite3_step(pTblname) ){
  12730. const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
  12731. recoverAddTable(p, zTbl, iRoot);
  12732. }
  12733. recoverReset(p, pTblname);
  12734. }
  12735. }else if( rc!=SQLITE_ERROR ){
  12736. recoverDbError(p, p->dbOut);
  12737. }
  12738. sqlite3_free(zFree);
  12739. }
  12740. }
  12741. recoverFinalize(p, pSelect);
  12742. recoverFinalize(p, pTblname);
  12743. return p->errCode;
  12744. }
  12745. /*
  12746. ** This function is called after the output database has been populated. It
  12747. ** adds all recovered schema elements that were not created in the output
  12748. ** database by recoverWriteSchema1() - everything except for tables and
  12749. ** UNIQUE indexes. Specifically:
  12750. **
  12751. ** * views,
  12752. ** * triggers,
  12753. ** * non-UNIQUE indexes.
  12754. **
  12755. ** If the recover handle is in SQL callback mode, then equivalent callbacks
  12756. ** are issued to create the schema elements.
  12757. */
  12758. static int recoverWriteSchema2(sqlite3_recover *p){
  12759. sqlite3_stmt *pSelect = 0;
  12760. pSelect = recoverPrepare(p, p->dbOut,
  12761. p->bSlowIndexes ?
  12762. "SELECT rootpage, sql FROM recovery.schema "
  12763. " WHERE type!='table' AND type!='index'"
  12764. :
  12765. "SELECT rootpage, sql FROM recovery.schema "
  12766. " WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')"
  12767. );
  12768. if( pSelect ){
  12769. while( sqlite3_step(pSelect)==SQLITE_ROW ){
  12770. const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
  12771. int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
  12772. if( rc==SQLITE_OK ){
  12773. recoverSqlCallback(p, zSql);
  12774. }else if( rc!=SQLITE_ERROR ){
  12775. recoverDbError(p, p->dbOut);
  12776. }
  12777. }
  12778. }
  12779. recoverFinalize(p, pSelect);
  12780. return p->errCode;
  12781. }
  12782. /*
  12783. ** This function is a no-op if recover handle p already contains an error
  12784. ** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
  12785. **
  12786. ** Otherwise, if the recover handle is configured to create an output
  12787. ** database (was created by sqlite3_recover_init()), then this function
  12788. ** prepares and returns an SQL statement to INSERT a new record into table
  12789. ** pTab, assuming the first nField fields of a record extracted from disk
  12790. ** are valid.
  12791. **
  12792. ** For example, if table pTab is:
  12793. **
  12794. ** CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e);
  12795. **
  12796. ** And nField is 4, then the SQL statement prepared and returned is:
  12797. **
  12798. ** INSERT INTO (a, c, d) VALUES (?1, ?2, ?3);
  12799. **
  12800. ** In this case even though 4 values were extracted from the input db,
  12801. ** only 3 are written to the output, as the generated STORED column
  12802. ** cannot be written.
  12803. **
  12804. ** If the recover handle is in SQL callback mode, then the SQL statement
  12805. ** prepared is such that evaluating it returns a single row containing
  12806. ** a single text value - itself an SQL statement similar to the above,
  12807. ** except with SQL literals in place of the variables. For example:
  12808. **
  12809. ** SELECT 'INSERT INTO (a, c, d) VALUES ('
  12810. ** || quote(?1) || ', '
  12811. ** || quote(?2) || ', '
  12812. ** || quote(?3) || ')';
  12813. **
  12814. ** In either case, it is the responsibility of the caller to eventually
  12815. ** free the statement handle using sqlite3_finalize().
  12816. */
  12817. static sqlite3_stmt *recoverInsertStmt(
  12818. sqlite3_recover *p,
  12819. RecoverTable *pTab,
  12820. int nField
  12821. ){
  12822. sqlite3_stmt *pRet = 0;
  12823. const char *zSep = "";
  12824. const char *zSqlSep = "";
  12825. char *zSql = 0;
  12826. char *zFinal = 0;
  12827. char *zBind = 0;
  12828. int ii;
  12829. int bSql = p->xSql ? 1 : 0;
  12830. if( nField<=0 ) return 0;
  12831. assert( nField<=pTab->nCol );
  12832. zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
  12833. if( pTab->iRowidBind ){
  12834. assert( pTab->bIntkey );
  12835. zSql = recoverMPrintf(p, "%z_rowid_", zSql);
  12836. if( bSql ){
  12837. zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
  12838. }else{
  12839. zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
  12840. }
  12841. zSqlSep = "||', '||";
  12842. zSep = ", ";
  12843. }
  12844. for(ii=0; ii<nField; ii++){
  12845. int eHidden = pTab->aCol[ii].eHidden;
  12846. if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
  12847. && eHidden!=RECOVER_EHIDDEN_STORED
  12848. ){
  12849. assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 );
  12850. zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol);
  12851. if( bSql ){
  12852. zBind = recoverMPrintf(p,
  12853. "%z%sescape_crnl(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind
  12854. );
  12855. zSqlSep = "||', '||";
  12856. }else{
  12857. zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind);
  12858. }
  12859. zSep = ", ";
  12860. }
  12861. }
  12862. if( bSql ){
  12863. zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'",
  12864. zSql, zBind
  12865. );
  12866. }else{
  12867. zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind);
  12868. }
  12869. pRet = recoverPrepare(p, p->dbOut, zFinal);
  12870. sqlite3_free(zSql);
  12871. sqlite3_free(zBind);
  12872. sqlite3_free(zFinal);
  12873. return pRet;
  12874. }
  12875. /*
  12876. ** Search the list of RecoverTable objects at p->pTblList for one that
  12877. ** has root page iRoot in the input database. If such an object is found,
  12878. ** return a pointer to it. Otherwise, return NULL.
  12879. */
  12880. static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){
  12881. RecoverTable *pRet = 0;
  12882. for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext);
  12883. return pRet;
  12884. }
  12885. /*
  12886. ** This function attempts to create a lost and found table within the
  12887. ** output db. If successful, it returns a pointer to a buffer containing
  12888. ** the name of the new table. It is the responsibility of the caller to
  12889. ** eventually free this buffer using sqlite3_free().
  12890. **
  12891. ** If an error occurs, NULL is returned and an error code and error
  12892. ** message left in the recover handle.
  12893. */
  12894. static char *recoverLostAndFoundCreate(
  12895. sqlite3_recover *p, /* Recover object */
  12896. int nField /* Number of column fields in new table */
  12897. ){
  12898. char *zTbl = 0;
  12899. sqlite3_stmt *pProbe = 0;
  12900. int ii = 0;
  12901. pProbe = recoverPrepare(p, p->dbOut,
  12902. "SELECT 1 FROM sqlite_schema WHERE name=?"
  12903. );
  12904. for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){
  12905. int bFail = 0;
  12906. if( ii<0 ){
  12907. zTbl = recoverMPrintf(p, "%s", p->zLostAndFound);
  12908. }else{
  12909. zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii);
  12910. }
  12911. if( p->errCode==SQLITE_OK ){
  12912. sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC);
  12913. if( SQLITE_ROW==sqlite3_step(pProbe) ){
  12914. bFail = 1;
  12915. }
  12916. recoverReset(p, pProbe);
  12917. }
  12918. if( bFail ){
  12919. sqlite3_clear_bindings(pProbe);
  12920. sqlite3_free(zTbl);
  12921. zTbl = 0;
  12922. }
  12923. }
  12924. recoverFinalize(p, pProbe);
  12925. if( zTbl ){
  12926. const char *zSep = 0;
  12927. char *zField = 0;
  12928. char *zSql = 0;
  12929. zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, ";
  12930. for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){
  12931. zField = recoverMPrintf(p, "%z%sc%d", zField, zSep, ii);
  12932. zSep = ", ";
  12933. }
  12934. zSql = recoverMPrintf(p, "CREATE TABLE %s(%s)", zTbl, zField);
  12935. sqlite3_free(zField);
  12936. recoverExec(p, p->dbOut, zSql);
  12937. recoverSqlCallback(p, zSql);
  12938. sqlite3_free(zSql);
  12939. }else if( p->errCode==SQLITE_OK ){
  12940. recoverError(
  12941. p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound
  12942. );
  12943. }
  12944. return zTbl;
  12945. }
  12946. /*
  12947. ** Synthesize and prepare an INSERT statement to write to the lost_and_found
  12948. ** table in the output database. The name of the table is zTab, and it has
  12949. ** nField c* fields.
  12950. */
  12951. static sqlite3_stmt *recoverLostAndFoundInsert(
  12952. sqlite3_recover *p,
  12953. const char *zTab,
  12954. int nField
  12955. ){
  12956. int nTotal = nField + 4;
  12957. int ii;
  12958. char *zBind = 0;
  12959. sqlite3_stmt *pRet = 0;
  12960. if( p->xSql==0 ){
  12961. for(ii=0; ii<nTotal; ii++){
  12962. zBind = recoverMPrintf(p, "%z%s?", zBind, zBind?", ":"", ii);
  12963. }
  12964. pRet = recoverPreparePrintf(
  12965. p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind
  12966. );
  12967. }else{
  12968. const char *zSep = "";
  12969. for(ii=0; ii<nTotal; ii++){
  12970. zBind = recoverMPrintf(p, "%z%squote(?)", zBind, zSep);
  12971. zSep = "|| ', ' ||";
  12972. }
  12973. pRet = recoverPreparePrintf(
  12974. p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind
  12975. );
  12976. }
  12977. sqlite3_free(zBind);
  12978. return pRet;
  12979. }
  12980. /*
  12981. ** Input database page iPg contains data that will be written to the
  12982. ** lost-and-found table of the output database. This function attempts
  12983. ** to identify the root page of the tree that page iPg belonged to.
  12984. ** If successful, it sets output variable (*piRoot) to the page number
  12985. ** of the root page and returns SQLITE_OK. Otherwise, if an error occurs,
  12986. ** an SQLite error code is returned and the final value of *piRoot
  12987. ** undefined.
  12988. */
  12989. static int recoverLostAndFoundFindRoot(
  12990. sqlite3_recover *p,
  12991. i64 iPg,
  12992. i64 *piRoot
  12993. ){
  12994. RecoverStateLAF *pLaf = &p->laf;
  12995. if( pLaf->pFindRoot==0 ){
  12996. pLaf->pFindRoot = recoverPrepare(p, p->dbOut,
  12997. "WITH RECURSIVE p(pgno) AS ("
  12998. " SELECT ?"
  12999. " UNION"
  13000. " SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno"
  13001. ") "
  13002. "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno "
  13003. " AND m.parent IS NULL"
  13004. );
  13005. }
  13006. if( p->errCode==SQLITE_OK ){
  13007. sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg);
  13008. if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){
  13009. *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0);
  13010. }else{
  13011. *piRoot = iPg;
  13012. }
  13013. recoverReset(p, pLaf->pFindRoot);
  13014. }
  13015. return p->errCode;
  13016. }
  13017. /*
  13018. ** Recover data from page iPage of the input database and write it to
  13019. ** the lost-and-found table in the output database.
  13020. */
  13021. static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){
  13022. RecoverStateLAF *pLaf = &p->laf;
  13023. sqlite3_value **apVal = pLaf->apVal;
  13024. sqlite3_stmt *pPageData = pLaf->pPageData;
  13025. sqlite3_stmt *pInsert = pLaf->pInsert;
  13026. int nVal = -1;
  13027. int iPrevCell = 0;
  13028. i64 iRoot = 0;
  13029. int bHaveRowid = 0;
  13030. i64 iRowid = 0;
  13031. int ii = 0;
  13032. if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return;
  13033. sqlite3_bind_int64(pPageData, 1, iPage);
  13034. while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){
  13035. int iCell = sqlite3_column_int64(pPageData, 0);
  13036. int iField = sqlite3_column_int64(pPageData, 1);
  13037. if( iPrevCell!=iCell && nVal>=0 ){
  13038. /* Insert the new row */
  13039. sqlite3_bind_int64(pInsert, 1, iRoot); /* rootpgno */
  13040. sqlite3_bind_int64(pInsert, 2, iPage); /* pgno */
  13041. sqlite3_bind_int(pInsert, 3, nVal); /* nfield */
  13042. if( bHaveRowid ){
  13043. sqlite3_bind_int64(pInsert, 4, iRowid); /* id */
  13044. }
  13045. for(ii=0; ii<nVal; ii++){
  13046. recoverBindValue(p, pInsert, 5+ii, apVal[ii]);
  13047. }
  13048. if( sqlite3_step(pInsert)==SQLITE_ROW ){
  13049. recoverSqlCallback(p, (const char*)sqlite3_column_text(pInsert, 0));
  13050. }
  13051. recoverReset(p, pInsert);
  13052. /* Discard the accumulated row data */
  13053. for(ii=0; ii<nVal; ii++){
  13054. sqlite3_value_free(apVal[ii]);
  13055. apVal[ii] = 0;
  13056. }
  13057. sqlite3_clear_bindings(pInsert);
  13058. bHaveRowid = 0;
  13059. nVal = -1;
  13060. }
  13061. if( iCell<0 ) break;
  13062. if( iField<0 ){
  13063. assert( nVal==-1 );
  13064. iRowid = sqlite3_column_int64(pPageData, 2);
  13065. bHaveRowid = 1;
  13066. nVal = 0;
  13067. }else if( iField<pLaf->nMaxField ){
  13068. sqlite3_value *pVal = sqlite3_column_value(pPageData, 2);
  13069. apVal[iField] = sqlite3_value_dup(pVal);
  13070. assert( iField==nVal || (nVal==-1 && iField==0) );
  13071. nVal = iField+1;
  13072. if( apVal[iField]==0 ){
  13073. recoverError(p, SQLITE_NOMEM, 0);
  13074. }
  13075. }
  13076. iPrevCell = iCell;
  13077. }
  13078. recoverReset(p, pPageData);
  13079. for(ii=0; ii<nVal; ii++){
  13080. sqlite3_value_free(apVal[ii]);
  13081. apVal[ii] = 0;
  13082. }
  13083. }
  13084. /*
  13085. ** Perform one step (sqlite3_recover_step()) of work for the connection
  13086. ** passed as the only argument, which is guaranteed to be in
  13087. ** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
  13088. ** table of the output database is populated with recovered data that can
  13089. ** not be assigned to any recovered schema object.
  13090. */
  13091. static int recoverLostAndFound3Step(sqlite3_recover *p){
  13092. RecoverStateLAF *pLaf = &p->laf;
  13093. if( p->errCode==SQLITE_OK ){
  13094. if( pLaf->pInsert==0 ){
  13095. return SQLITE_DONE;
  13096. }else{
  13097. if( p->errCode==SQLITE_OK ){
  13098. int res = sqlite3_step(pLaf->pAllPage);
  13099. if( res==SQLITE_ROW ){
  13100. i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0);
  13101. if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){
  13102. recoverLostAndFoundOnePage(p, iPage);
  13103. }
  13104. }else{
  13105. recoverReset(p, pLaf->pAllPage);
  13106. return SQLITE_DONE;
  13107. }
  13108. }
  13109. }
  13110. }
  13111. return SQLITE_OK;
  13112. }
  13113. /*
  13114. ** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3
  13115. ** state - during which the lost-and-found table of the output database
  13116. ** is populated with recovered data that can not be assigned to any
  13117. ** recovered schema object.
  13118. */
  13119. static void recoverLostAndFound3Init(sqlite3_recover *p){
  13120. RecoverStateLAF *pLaf = &p->laf;
  13121. if( pLaf->nMaxField>0 ){
  13122. char *zTab = 0; /* Name of lost_and_found table */
  13123. zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField);
  13124. pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField);
  13125. sqlite3_free(zTab);
  13126. pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut,
  13127. "WITH RECURSIVE seq(ii) AS ("
  13128. " SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
  13129. ")"
  13130. "SELECT ii FROM seq" , p->laf.nPg
  13131. );
  13132. pLaf->pPageData = recoverPrepare(p, p->dbOut,
  13133. "SELECT cell, field, value "
  13134. "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? "
  13135. "UNION ALL "
  13136. "SELECT -1, -1, -1"
  13137. );
  13138. pLaf->apVal = (sqlite3_value**)recoverMalloc(p,
  13139. pLaf->nMaxField*sizeof(sqlite3_value*)
  13140. );
  13141. }
  13142. }
  13143. /*
  13144. ** Initialize resources required in RECOVER_STATE_WRITING state - during which
  13145. ** tables recovered from the schema of the input database are populated with
  13146. ** recovered data.
  13147. */
  13148. static int recoverWriteDataInit(sqlite3_recover *p){
  13149. RecoverStateW1 *p1 = &p->w1;
  13150. RecoverTable *pTbl = 0;
  13151. int nByte = 0;
  13152. /* Figure out the maximum number of columns for any table in the schema */
  13153. assert( p1->nMax==0 );
  13154. for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){
  13155. if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol;
  13156. }
  13157. /* Allocate an array of (sqlite3_value*) in which to accumulate the values
  13158. ** that will be written to the output database in a single row. */
  13159. nByte = sizeof(sqlite3_value*) * (p1->nMax+1);
  13160. p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte);
  13161. if( p1->apVal==0 ) return p->errCode;
  13162. /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT
  13163. ** to loop through cells that appear to belong to a single table (pSel). */
  13164. p1->pTbls = recoverPrepare(p, p->dbOut,
  13165. "SELECT rootpage FROM recovery.schema "
  13166. " WHERE type='table' AND (sql NOT LIKE 'create virtual%')"
  13167. " ORDER BY (tbl_name='sqlite_sequence') ASC"
  13168. );
  13169. p1->pSel = recoverPrepare(p, p->dbOut,
  13170. "WITH RECURSIVE pages(page) AS ("
  13171. " SELECT ?1"
  13172. " UNION"
  13173. " SELECT child FROM sqlite_dbptr('getpage()'), pages "
  13174. " WHERE pgno=page"
  13175. ") "
  13176. "SELECT page, cell, field, value "
  13177. "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno "
  13178. "UNION ALL "
  13179. "SELECT 0, 0, 0, 0"
  13180. );
  13181. return p->errCode;
  13182. }
  13183. /*
  13184. ** Clean up resources allocated by recoverWriteDataInit() (stuff in
  13185. ** sqlite3_recover.w1).
  13186. */
  13187. static void recoverWriteDataCleanup(sqlite3_recover *p){
  13188. RecoverStateW1 *p1 = &p->w1;
  13189. int ii;
  13190. for(ii=0; ii<p1->nVal; ii++){
  13191. sqlite3_value_free(p1->apVal[ii]);
  13192. }
  13193. sqlite3_free(p1->apVal);
  13194. recoverFinalize(p, p1->pInsert);
  13195. recoverFinalize(p, p1->pTbls);
  13196. recoverFinalize(p, p1->pSel);
  13197. memset(p1, 0, sizeof(*p1));
  13198. }
  13199. /*
  13200. ** Perform one step (sqlite3_recover_step()) of work for the connection
  13201. ** passed as the only argument, which is guaranteed to be in
  13202. ** RECOVER_STATE_WRITING state - during which tables recovered from the
  13203. ** schema of the input database are populated with recovered data.
  13204. */
  13205. static int recoverWriteDataStep(sqlite3_recover *p){
  13206. RecoverStateW1 *p1 = &p->w1;
  13207. sqlite3_stmt *pSel = p1->pSel;
  13208. sqlite3_value **apVal = p1->apVal;
  13209. if( p->errCode==SQLITE_OK && p1->pTab==0 ){
  13210. if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){
  13211. i64 iRoot = sqlite3_column_int64(p1->pTbls, 0);
  13212. p1->pTab = recoverFindTable(p, iRoot);
  13213. recoverFinalize(p, p1->pInsert);
  13214. p1->pInsert = 0;
  13215. /* If this table is unknown, return early. The caller will invoke this
  13216. ** function again and it will move on to the next table. */
  13217. if( p1->pTab==0 ) return p->errCode;
  13218. /* If this is the sqlite_sequence table, delete any rows added by
  13219. ** earlier INSERT statements on tables with AUTOINCREMENT primary
  13220. ** keys before recovering its contents. The p1->pTbls SELECT statement
  13221. ** is rigged to deliver "sqlite_sequence" last of all, so we don't
  13222. ** worry about it being modified after it is recovered. */
  13223. if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){
  13224. recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence");
  13225. recoverSqlCallback(p, "DELETE FROM sqlite_sequence");
  13226. }
  13227. /* Bind the root page of this table within the original database to
  13228. ** SELECT statement p1->pSel. The SELECT statement will then iterate
  13229. ** through cells that look like they belong to table pTab. */
  13230. sqlite3_bind_int64(pSel, 1, iRoot);
  13231. p1->nVal = 0;
  13232. p1->bHaveRowid = 0;
  13233. p1->iPrevPage = -1;
  13234. p1->iPrevCell = -1;
  13235. }else{
  13236. return SQLITE_DONE;
  13237. }
  13238. }
  13239. assert( p->errCode!=SQLITE_OK || p1->pTab );
  13240. if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){
  13241. RecoverTable *pTab = p1->pTab;
  13242. i64 iPage = sqlite3_column_int64(pSel, 0);
  13243. int iCell = sqlite3_column_int(pSel, 1);
  13244. int iField = sqlite3_column_int(pSel, 2);
  13245. sqlite3_value *pVal = sqlite3_column_value(pSel, 3);
  13246. int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell);
  13247. assert( bNewCell==0 || (iField==-1 || iField==0) );
  13248. assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol );
  13249. if( bNewCell ){
  13250. int ii = 0;
  13251. if( p1->nVal>=0 ){
  13252. if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){
  13253. recoverFinalize(p, p1->pInsert);
  13254. p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal);
  13255. p1->nInsert = p1->nVal;
  13256. }
  13257. if( p1->nVal>0 ){
  13258. sqlite3_stmt *pInsert = p1->pInsert;
  13259. for(ii=0; ii<pTab->nCol; ii++){
  13260. RecoverColumn *pCol = &pTab->aCol[ii];
  13261. int iBind = pCol->iBind;
  13262. if( iBind>0 ){
  13263. if( pCol->bIPK ){
  13264. sqlite3_bind_int64(pInsert, iBind, p1->iRowid);
  13265. }else if( pCol->iField<p1->nVal ){
  13266. recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]);
  13267. }
  13268. }
  13269. }
  13270. if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){
  13271. sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid);
  13272. }
  13273. if( SQLITE_ROW==sqlite3_step(pInsert) ){
  13274. const char *z = (const char*)sqlite3_column_text(pInsert, 0);
  13275. recoverSqlCallback(p, z);
  13276. }
  13277. recoverReset(p, pInsert);
  13278. assert( p->errCode || pInsert );
  13279. if( pInsert ) sqlite3_clear_bindings(pInsert);
  13280. }
  13281. }
  13282. for(ii=0; ii<p1->nVal; ii++){
  13283. sqlite3_value_free(apVal[ii]);
  13284. apVal[ii] = 0;
  13285. }
  13286. p1->nVal = -1;
  13287. p1->bHaveRowid = 0;
  13288. }
  13289. if( iPage!=0 ){
  13290. if( iField<0 ){
  13291. p1->iRowid = sqlite3_column_int64(pSel, 3);
  13292. assert( p1->nVal==-1 );
  13293. p1->nVal = 0;
  13294. p1->bHaveRowid = 1;
  13295. }else if( iField<pTab->nCol ){
  13296. assert( apVal[iField]==0 );
  13297. apVal[iField] = sqlite3_value_dup( pVal );
  13298. if( apVal[iField]==0 ){
  13299. recoverError(p, SQLITE_NOMEM, 0);
  13300. }
  13301. p1->nVal = iField+1;
  13302. }
  13303. p1->iPrevCell = iCell;
  13304. p1->iPrevPage = iPage;
  13305. }
  13306. }else{
  13307. recoverReset(p, pSel);
  13308. p1->pTab = 0;
  13309. }
  13310. return p->errCode;
  13311. }
  13312. /*
  13313. ** Initialize resources required by sqlite3_recover_step() in
  13314. ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
  13315. ** already allocated to a recovered schema element is determined.
  13316. */
  13317. static void recoverLostAndFound1Init(sqlite3_recover *p){
  13318. RecoverStateLAF *pLaf = &p->laf;
  13319. sqlite3_stmt *pStmt = 0;
  13320. assert( p->laf.pUsed==0 );
  13321. pLaf->nPg = recoverPageCount(p);
  13322. pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg);
  13323. /* Prepare a statement to iterate through all pages that are part of any tree
  13324. ** in the recoverable part of the input database schema to the bitmap. And,
  13325. ** if !p->bFreelistCorrupt, add all pages that appear to be part of the
  13326. ** freelist. */
  13327. pStmt = recoverPrepare(
  13328. p, p->dbOut,
  13329. "WITH trunk(pgno) AS ("
  13330. " SELECT read_i32(getpage(1), 8) AS x WHERE x>0"
  13331. " UNION"
  13332. " SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0"
  13333. "),"
  13334. "trunkdata(pgno, data) AS ("
  13335. " SELECT pgno, getpage(pgno) FROM trunk"
  13336. "),"
  13337. "freelist(data, n, freepgno) AS ("
  13338. " SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata"
  13339. " UNION ALL"
  13340. " SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0"
  13341. "),"
  13342. ""
  13343. "roots(r) AS ("
  13344. " SELECT 1 UNION ALL"
  13345. " SELECT rootpage FROM recovery.schema WHERE rootpage>0"
  13346. "),"
  13347. "used(page) AS ("
  13348. " SELECT r FROM roots"
  13349. " UNION"
  13350. " SELECT child FROM sqlite_dbptr('getpage()'), used "
  13351. " WHERE pgno=page"
  13352. ") "
  13353. "SELECT page FROM used"
  13354. " UNION ALL "
  13355. "SELECT freepgno FROM freelist WHERE NOT ?"
  13356. );
  13357. if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt);
  13358. pLaf->pUsedPages = pStmt;
  13359. }
  13360. /*
  13361. ** Perform one step (sqlite3_recover_step()) of work for the connection
  13362. ** passed as the only argument, which is guaranteed to be in
  13363. ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
  13364. ** already allocated to a recovered schema element is determined.
  13365. */
  13366. static int recoverLostAndFound1Step(sqlite3_recover *p){
  13367. RecoverStateLAF *pLaf = &p->laf;
  13368. int rc = p->errCode;
  13369. if( rc==SQLITE_OK ){
  13370. rc = sqlite3_step(pLaf->pUsedPages);
  13371. if( rc==SQLITE_ROW ){
  13372. i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0);
  13373. recoverBitmapSet(pLaf->pUsed, iPg);
  13374. rc = SQLITE_OK;
  13375. }else{
  13376. recoverFinalize(p, pLaf->pUsedPages);
  13377. pLaf->pUsedPages = 0;
  13378. }
  13379. }
  13380. return rc;
  13381. }
  13382. /*
  13383. ** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2
  13384. ** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
  13385. ** are sorted into sets that likely belonged to the same database tree.
  13386. */
  13387. static void recoverLostAndFound2Init(sqlite3_recover *p){
  13388. RecoverStateLAF *pLaf = &p->laf;
  13389. assert( p->laf.pAllAndParent==0 );
  13390. assert( p->laf.pMapInsert==0 );
  13391. assert( p->laf.pMaxField==0 );
  13392. assert( p->laf.nMaxField==0 );
  13393. pLaf->pMapInsert = recoverPrepare(p, p->dbOut,
  13394. "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)"
  13395. );
  13396. pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut,
  13397. "WITH RECURSIVE seq(ii) AS ("
  13398. " SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
  13399. ")"
  13400. "SELECT pgno, child FROM sqlite_dbptr('getpage()') "
  13401. " UNION ALL "
  13402. "SELECT NULL, ii FROM seq", p->laf.nPg
  13403. );
  13404. pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut,
  13405. "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?"
  13406. );
  13407. }
  13408. /*
  13409. ** Perform one step (sqlite3_recover_step()) of work for the connection
  13410. ** passed as the only argument, which is guaranteed to be in
  13411. ** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
  13412. ** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged
  13413. ** to the same database tree.
  13414. */
  13415. static int recoverLostAndFound2Step(sqlite3_recover *p){
  13416. RecoverStateLAF *pLaf = &p->laf;
  13417. if( p->errCode==SQLITE_OK ){
  13418. int res = sqlite3_step(pLaf->pAllAndParent);
  13419. if( res==SQLITE_ROW ){
  13420. i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1);
  13421. if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){
  13422. sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild);
  13423. sqlite3_bind_value(pLaf->pMapInsert, 2,
  13424. sqlite3_column_value(pLaf->pAllAndParent, 0)
  13425. );
  13426. sqlite3_step(pLaf->pMapInsert);
  13427. recoverReset(p, pLaf->pMapInsert);
  13428. sqlite3_bind_int64(pLaf->pMaxField, 1, iChild);
  13429. if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){
  13430. int nMax = sqlite3_column_int(pLaf->pMaxField, 0);
  13431. if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax;
  13432. }
  13433. recoverReset(p, pLaf->pMaxField);
  13434. }
  13435. }else{
  13436. recoverFinalize(p, pLaf->pAllAndParent);
  13437. pLaf->pAllAndParent =0;
  13438. return SQLITE_DONE;
  13439. }
  13440. }
  13441. return p->errCode;
  13442. }
  13443. /*
  13444. ** Free all resources allocated as part of sqlite3_recover_step() calls
  13445. ** in one of the RECOVER_STATE_LOSTANDFOUND[123] states.
  13446. */
  13447. static void recoverLostAndFoundCleanup(sqlite3_recover *p){
  13448. recoverBitmapFree(p->laf.pUsed);
  13449. p->laf.pUsed = 0;
  13450. sqlite3_finalize(p->laf.pUsedPages);
  13451. sqlite3_finalize(p->laf.pAllAndParent);
  13452. sqlite3_finalize(p->laf.pMapInsert);
  13453. sqlite3_finalize(p->laf.pMaxField);
  13454. sqlite3_finalize(p->laf.pFindRoot);
  13455. sqlite3_finalize(p->laf.pInsert);
  13456. sqlite3_finalize(p->laf.pAllPage);
  13457. sqlite3_finalize(p->laf.pPageData);
  13458. p->laf.pUsedPages = 0;
  13459. p->laf.pAllAndParent = 0;
  13460. p->laf.pMapInsert = 0;
  13461. p->laf.pMaxField = 0;
  13462. p->laf.pFindRoot = 0;
  13463. p->laf.pInsert = 0;
  13464. p->laf.pAllPage = 0;
  13465. p->laf.pPageData = 0;
  13466. sqlite3_free(p->laf.apVal);
  13467. p->laf.apVal = 0;
  13468. }
  13469. /*
  13470. ** Free all resources allocated as part of sqlite3_recover_step() calls.
  13471. */
  13472. static void recoverFinalCleanup(sqlite3_recover *p){
  13473. RecoverTable *pTab = 0;
  13474. RecoverTable *pNext = 0;
  13475. recoverWriteDataCleanup(p);
  13476. recoverLostAndFoundCleanup(p);
  13477. for(pTab=p->pTblList; pTab; pTab=pNext){
  13478. pNext = pTab->pNext;
  13479. sqlite3_free(pTab);
  13480. }
  13481. p->pTblList = 0;
  13482. sqlite3_finalize(p->pGetPage);
  13483. p->pGetPage = 0;
  13484. {
  13485. #ifndef NDEBUG
  13486. int res =
  13487. #endif
  13488. sqlite3_close(p->dbOut);
  13489. assert( res==SQLITE_OK );
  13490. }
  13491. p->dbOut = 0;
  13492. }
  13493. /*
  13494. ** Decode and return an unsigned 16-bit big-endian integer value from
  13495. ** buffer a[].
  13496. */
  13497. static u32 recoverGetU16(const u8 *a){
  13498. return (((u32)a[0])<<8) + ((u32)a[1]);
  13499. }
  13500. /*
  13501. ** Decode and return an unsigned 32-bit big-endian integer value from
  13502. ** buffer a[].
  13503. */
  13504. static u32 recoverGetU32(const u8 *a){
  13505. return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]);
  13506. }
  13507. /*
  13508. ** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal)
  13509. ** and return the number of bytes consumed.
  13510. */
  13511. static int recoverGetVarint(const u8 *a, i64 *pVal){
  13512. sqlite3_uint64 u = 0;
  13513. int i;
  13514. for(i=0; i<8; i++){
  13515. u = (u<<7) + (a[i]&0x7f);
  13516. if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
  13517. }
  13518. u = (u<<8) + (a[i]&0xff);
  13519. *pVal = (sqlite3_int64)u;
  13520. return 9;
  13521. }
  13522. /*
  13523. ** The second argument points to a buffer n bytes in size. If this buffer
  13524. ** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
  13525. ** return the page-size in bytes. Otherwise, if the buffer does not
  13526. ** appear to contain a well-formed b-tree page, return 0.
  13527. */
  13528. static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){
  13529. u8 *aUsed = aTmp;
  13530. int nFrag = 0;
  13531. int nActual = 0;
  13532. int iFree = 0;
  13533. int nCell = 0; /* Number of cells on page */
  13534. int iCellOff = 0; /* Offset of cell array in page */
  13535. int iContent = 0;
  13536. int eType = 0;
  13537. int ii = 0;
  13538. eType = (int)a[0];
  13539. if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0;
  13540. iFree = (int)recoverGetU16(&a[1]);
  13541. nCell = (int)recoverGetU16(&a[3]);
  13542. iContent = (int)recoverGetU16(&a[5]);
  13543. if( iContent==0 ) iContent = 65536;
  13544. nFrag = (int)a[7];
  13545. if( iContent>n ) return 0;
  13546. memset(aUsed, 0, n);
  13547. memset(aUsed, 0xFF, iContent);
  13548. /* Follow the free-list. This is the same format for all b-tree pages. */
  13549. if( iFree && iFree<=iContent ) return 0;
  13550. while( iFree ){
  13551. int iNext = 0;
  13552. int nByte = 0;
  13553. if( iFree>(n-4) ) return 0;
  13554. iNext = recoverGetU16(&a[iFree]);
  13555. nByte = recoverGetU16(&a[iFree+2]);
  13556. if( iFree+nByte>n ) return 0;
  13557. if( iNext && iNext<iFree+nByte ) return 0;
  13558. memset(&aUsed[iFree], 0xFF, nByte);
  13559. iFree = iNext;
  13560. }
  13561. /* Run through the cells */
  13562. if( eType==0x02 || eType==0x05 ){
  13563. iCellOff = 12;
  13564. }else{
  13565. iCellOff = 8;
  13566. }
  13567. if( (iCellOff + 2*nCell)>iContent ) return 0;
  13568. for(ii=0; ii<nCell; ii++){
  13569. int iByte;
  13570. i64 nPayload = 0;
  13571. int nByte = 0;
  13572. int iOff = recoverGetU16(&a[iCellOff + 2*ii]);
  13573. if( iOff<iContent || iOff>n ){
  13574. return 0;
  13575. }
  13576. if( eType==0x05 || eType==0x02 ) nByte += 4;
  13577. nByte += recoverGetVarint(&a[iOff+nByte], &nPayload);
  13578. if( eType==0x0D ){
  13579. i64 dummy = 0;
  13580. nByte += recoverGetVarint(&a[iOff+nByte], &dummy);
  13581. }
  13582. if( eType!=0x05 ){
  13583. int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23);
  13584. int M = ((n-12)*32/255)-23;
  13585. int K = M+((nPayload-M)%(n-4));
  13586. if( nPayload<X ){
  13587. nByte += nPayload;
  13588. }else if( K<=X ){
  13589. nByte += K+4;
  13590. }else{
  13591. nByte += M+4;
  13592. }
  13593. }
  13594. if( iOff+nByte>n ){
  13595. return 0;
  13596. }
  13597. for(iByte=iOff; iByte<(iOff+nByte); iByte++){
  13598. if( aUsed[iByte]!=0 ){
  13599. return 0;
  13600. }
  13601. aUsed[iByte] = 0xFF;
  13602. }
  13603. }
  13604. nActual = 0;
  13605. for(ii=0; ii<n; ii++){
  13606. if( aUsed[ii]==0 ) nActual++;
  13607. }
  13608. return (nActual==nFrag);
  13609. }
  13610. static int recoverVfsClose(sqlite3_file*);
  13611. static int recoverVfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  13612. static int recoverVfsWrite(sqlite3_file*, const void*, int, sqlite3_int64);
  13613. static int recoverVfsTruncate(sqlite3_file*, sqlite3_int64 size);
  13614. static int recoverVfsSync(sqlite3_file*, int flags);
  13615. static int recoverVfsFileSize(sqlite3_file*, sqlite3_int64 *pSize);
  13616. static int recoverVfsLock(sqlite3_file*, int);
  13617. static int recoverVfsUnlock(sqlite3_file*, int);
  13618. static int recoverVfsCheckReservedLock(sqlite3_file*, int *pResOut);
  13619. static int recoverVfsFileControl(sqlite3_file*, int op, void *pArg);
  13620. static int recoverVfsSectorSize(sqlite3_file*);
  13621. static int recoverVfsDeviceCharacteristics(sqlite3_file*);
  13622. static int recoverVfsShmMap(sqlite3_file*, int, int, int, void volatile**);
  13623. static int recoverVfsShmLock(sqlite3_file*, int offset, int n, int flags);
  13624. static void recoverVfsShmBarrier(sqlite3_file*);
  13625. static int recoverVfsShmUnmap(sqlite3_file*, int deleteFlag);
  13626. static int recoverVfsFetch(sqlite3_file*, sqlite3_int64, int, void**);
  13627. static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p);
  13628. static sqlite3_io_methods recover_methods = {
  13629. 2, /* iVersion */
  13630. recoverVfsClose,
  13631. recoverVfsRead,
  13632. recoverVfsWrite,
  13633. recoverVfsTruncate,
  13634. recoverVfsSync,
  13635. recoverVfsFileSize,
  13636. recoverVfsLock,
  13637. recoverVfsUnlock,
  13638. recoverVfsCheckReservedLock,
  13639. recoverVfsFileControl,
  13640. recoverVfsSectorSize,
  13641. recoverVfsDeviceCharacteristics,
  13642. recoverVfsShmMap,
  13643. recoverVfsShmLock,
  13644. recoverVfsShmBarrier,
  13645. recoverVfsShmUnmap,
  13646. recoverVfsFetch,
  13647. recoverVfsUnfetch
  13648. };
  13649. static int recoverVfsClose(sqlite3_file *pFd){
  13650. assert( pFd->pMethods!=&recover_methods );
  13651. return pFd->pMethods->xClose(pFd);
  13652. }
  13653. /*
  13654. ** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
  13655. */
  13656. static void recoverPutU16(u8 *a, u32 v){
  13657. a[0] = (v>>8) & 0x00FF;
  13658. a[1] = (v>>0) & 0x00FF;
  13659. }
  13660. /*
  13661. ** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
  13662. */
  13663. static void recoverPutU32(u8 *a, u32 v){
  13664. a[0] = (v>>24) & 0x00FF;
  13665. a[1] = (v>>16) & 0x00FF;
  13666. a[2] = (v>>8) & 0x00FF;
  13667. a[3] = (v>>0) & 0x00FF;
  13668. }
  13669. /*
  13670. ** Detect the page-size of the database opened by file-handle pFd by
  13671. ** searching the first part of the file for a well-formed SQLite b-tree
  13672. ** page. If parameter nReserve is non-zero, then as well as searching for
  13673. ** a b-tree page with zero reserved bytes, this function searches for one
  13674. ** with nReserve reserved bytes at the end of it.
  13675. **
  13676. ** If successful, set variable p->detected_pgsz to the detected page-size
  13677. ** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page
  13678. ** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
  13679. ** if an error occurs (e.g. an IO or OOM error), then an SQLite error code
  13680. ** is returned. The final value of p->detected_pgsz is undefined in this
  13681. ** case.
  13682. */
  13683. static int recoverVfsDetectPagesize(
  13684. sqlite3_recover *p, /* Recover handle */
  13685. sqlite3_file *pFd, /* File-handle open on input database */
  13686. u32 nReserve, /* Possible nReserve value */
  13687. i64 nSz /* Size of database file in bytes */
  13688. ){
  13689. int rc = SQLITE_OK;
  13690. const int nMin = 512;
  13691. const int nMax = 65536;
  13692. const int nMaxBlk = 4;
  13693. u32 pgsz = 0;
  13694. int iBlk = 0;
  13695. u8 *aPg = 0;
  13696. u8 *aTmp = 0;
  13697. int nBlk = 0;
  13698. aPg = (u8*)sqlite3_malloc(2*nMax);
  13699. if( aPg==0 ) return SQLITE_NOMEM;
  13700. aTmp = &aPg[nMax];
  13701. nBlk = (nSz+nMax-1)/nMax;
  13702. if( nBlk>nMaxBlk ) nBlk = nMaxBlk;
  13703. do {
  13704. for(iBlk=0; rc==SQLITE_OK && iBlk<nBlk; iBlk++){
  13705. int nByte = (nSz>=((iBlk+1)*nMax)) ? nMax : (nSz % nMax);
  13706. memset(aPg, 0, nMax);
  13707. rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax);
  13708. if( rc==SQLITE_OK ){
  13709. int pgsz2;
  13710. for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){
  13711. int iOff;
  13712. for(iOff=0; iOff<nMax; iOff+=pgsz2){
  13713. if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){
  13714. pgsz = pgsz2;
  13715. break;
  13716. }
  13717. }
  13718. }
  13719. }
  13720. }
  13721. if( pgsz>(u32)p->detected_pgsz ){
  13722. p->detected_pgsz = pgsz;
  13723. p->nReserve = nReserve;
  13724. }
  13725. if( nReserve==0 ) break;
  13726. nReserve = 0;
  13727. }while( 1 );
  13728. p->detected_pgsz = pgsz;
  13729. sqlite3_free(aPg);
  13730. return rc;
  13731. }
  13732. /*
  13733. ** The xRead() method of the wrapper VFS. This is used to intercept calls
  13734. ** to read page 1 of the input database.
  13735. */
  13736. static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){
  13737. int rc = SQLITE_OK;
  13738. if( pFd->pMethods==&recover_methods ){
  13739. pFd->pMethods = recover_g.pMethods;
  13740. rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
  13741. if( nByte==16 ){
  13742. sqlite3_randomness(16, aBuf);
  13743. }else
  13744. if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){
  13745. /* Ensure that the database has a valid header file. The only fields
  13746. ** that really matter to recovery are:
  13747. **
  13748. ** + Database page size (16-bits at offset 16)
  13749. ** + Size of db in pages (32-bits at offset 28)
  13750. ** + Database encoding (32-bits at offset 56)
  13751. **
  13752. ** Also preserved are:
  13753. **
  13754. ** + first freelist page (32-bits at offset 32)
  13755. ** + size of freelist (32-bits at offset 36)
  13756. **
  13757. ** We also try to preserve the auto-vacuum, incr-value, user-version
  13758. ** and application-id fields - all 32 bit quantities at offsets
  13759. ** 52, 60, 64 and 68. All other fields are set to known good values.
  13760. **
  13761. ** Byte offset 105 should also contain the page-size as a 16-bit
  13762. ** integer.
  13763. */
  13764. const int aPreserve[] = {32, 36, 52, 60, 64, 68};
  13765. u8 aHdr[108] = {
  13766. 0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66,
  13767. 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
  13768. 0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20,
  13769. 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
  13770. 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  13771. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
  13772. 0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
  13773. 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  13774. 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  13775. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  13776. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  13777. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  13778. 0x00, 0x2e, 0x5b, 0x30,
  13779. 0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00
  13780. };
  13781. u8 *a = (u8*)aBuf;
  13782. u32 pgsz = recoverGetU16(&a[16]);
  13783. u32 nReserve = a[20];
  13784. u32 enc = recoverGetU32(&a[56]);
  13785. u32 dbsz = 0;
  13786. i64 dbFileSize = 0;
  13787. int ii;
  13788. sqlite3_recover *p = recover_g.p;
  13789. if( pgsz==0x01 ) pgsz = 65536;
  13790. rc = pFd->pMethods->xFileSize(pFd, &dbFileSize);
  13791. if( rc==SQLITE_OK && p->detected_pgsz==0 ){
  13792. rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize);
  13793. }
  13794. if( p->detected_pgsz ){
  13795. pgsz = p->detected_pgsz;
  13796. nReserve = p->nReserve;
  13797. }
  13798. if( pgsz ){
  13799. dbsz = dbFileSize / pgsz;
  13800. }
  13801. if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){
  13802. enc = SQLITE_UTF8;
  13803. }
  13804. sqlite3_free(p->pPage1Cache);
  13805. p->pPage1Cache = 0;
  13806. p->pPage1Disk = 0;
  13807. p->pgsz = nByte;
  13808. p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2);
  13809. if( p->pPage1Cache ){
  13810. p->pPage1Disk = &p->pPage1Cache[nByte];
  13811. memcpy(p->pPage1Disk, aBuf, nByte);
  13812. recoverPutU32(&aHdr[28], dbsz);
  13813. recoverPutU32(&aHdr[56], enc);
  13814. recoverPutU16(&aHdr[105], pgsz-nReserve);
  13815. if( pgsz==65536 ) pgsz = 1;
  13816. recoverPutU16(&aHdr[16], pgsz);
  13817. aHdr[20] = nReserve;
  13818. for(ii=0; ii<sizeof(aPreserve)/sizeof(aPreserve[0]); ii++){
  13819. memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4);
  13820. }
  13821. memcpy(aBuf, aHdr, sizeof(aHdr));
  13822. memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr));
  13823. memcpy(p->pPage1Cache, aBuf, nByte);
  13824. }else{
  13825. rc = p->errCode;
  13826. }
  13827. }
  13828. pFd->pMethods = &recover_methods;
  13829. }else{
  13830. rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
  13831. }
  13832. return rc;
  13833. }
  13834. /*
  13835. ** Used to make sqlite3_io_methods wrapper methods less verbose.
  13836. */
  13837. #define RECOVER_VFS_WRAPPER(code) \
  13838. int rc = SQLITE_OK; \
  13839. if( pFd->pMethods==&recover_methods ){ \
  13840. pFd->pMethods = recover_g.pMethods; \
  13841. rc = code; \
  13842. pFd->pMethods = &recover_methods; \
  13843. }else{ \
  13844. rc = code; \
  13845. } \
  13846. return rc;
  13847. /*
  13848. ** Methods of the wrapper VFS. All methods except for xRead() and xClose()
  13849. ** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent
  13850. ** method on the lower level VFS, then reinstall the wrapper before returning.
  13851. ** Those that return an integer value use the RECOVER_VFS_WRAPPER macro.
  13852. */
  13853. static int recoverVfsWrite(
  13854. sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff
  13855. ){
  13856. RECOVER_VFS_WRAPPER (
  13857. pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff)
  13858. );
  13859. }
  13860. static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){
  13861. RECOVER_VFS_WRAPPER (
  13862. pFd->pMethods->xTruncate(pFd, size)
  13863. );
  13864. }
  13865. static int recoverVfsSync(sqlite3_file *pFd, int flags){
  13866. RECOVER_VFS_WRAPPER (
  13867. pFd->pMethods->xSync(pFd, flags)
  13868. );
  13869. }
  13870. static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){
  13871. RECOVER_VFS_WRAPPER (
  13872. pFd->pMethods->xFileSize(pFd, pSize)
  13873. );
  13874. }
  13875. static int recoverVfsLock(sqlite3_file *pFd, int eLock){
  13876. RECOVER_VFS_WRAPPER (
  13877. pFd->pMethods->xLock(pFd, eLock)
  13878. );
  13879. }
  13880. static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){
  13881. RECOVER_VFS_WRAPPER (
  13882. pFd->pMethods->xUnlock(pFd, eLock)
  13883. );
  13884. }
  13885. static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){
  13886. RECOVER_VFS_WRAPPER (
  13887. pFd->pMethods->xCheckReservedLock(pFd, pResOut)
  13888. );
  13889. }
  13890. static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){
  13891. RECOVER_VFS_WRAPPER (
  13892. (pFd->pMethods ? pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND)
  13893. );
  13894. }
  13895. static int recoverVfsSectorSize(sqlite3_file *pFd){
  13896. RECOVER_VFS_WRAPPER (
  13897. pFd->pMethods->xSectorSize(pFd)
  13898. );
  13899. }
  13900. static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){
  13901. RECOVER_VFS_WRAPPER (
  13902. pFd->pMethods->xDeviceCharacteristics(pFd)
  13903. );
  13904. }
  13905. static int recoverVfsShmMap(
  13906. sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp
  13907. ){
  13908. RECOVER_VFS_WRAPPER (
  13909. pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp)
  13910. );
  13911. }
  13912. static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){
  13913. RECOVER_VFS_WRAPPER (
  13914. pFd->pMethods->xShmLock(pFd, offset, n, flags)
  13915. );
  13916. }
  13917. static void recoverVfsShmBarrier(sqlite3_file *pFd){
  13918. if( pFd->pMethods==&recover_methods ){
  13919. pFd->pMethods = recover_g.pMethods;
  13920. pFd->pMethods->xShmBarrier(pFd);
  13921. pFd->pMethods = &recover_methods;
  13922. }else{
  13923. pFd->pMethods->xShmBarrier(pFd);
  13924. }
  13925. }
  13926. static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){
  13927. RECOVER_VFS_WRAPPER (
  13928. pFd->pMethods->xShmUnmap(pFd, deleteFlag)
  13929. );
  13930. }
  13931. static int recoverVfsFetch(
  13932. sqlite3_file *pFd,
  13933. sqlite3_int64 iOff,
  13934. int iAmt,
  13935. void **pp
  13936. ){
  13937. *pp = 0;
  13938. return SQLITE_OK;
  13939. }
  13940. static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){
  13941. return SQLITE_OK;
  13942. }
  13943. /*
  13944. ** Install the VFS wrapper around the file-descriptor open on the input
  13945. ** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held
  13946. ** when this function is called.
  13947. */
  13948. static void recoverInstallWrapper(sqlite3_recover *p){
  13949. sqlite3_file *pFd = 0;
  13950. assert( recover_g.pMethods==0 );
  13951. recoverAssertMutexHeld();
  13952. sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd);
  13953. assert( pFd==0 || pFd->pMethods!=&recover_methods );
  13954. if( pFd && pFd->pMethods ){
  13955. int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0);
  13956. recover_g.pMethods = pFd->pMethods;
  13957. recover_g.p = p;
  13958. recover_methods.iVersion = iVersion;
  13959. pFd->pMethods = &recover_methods;
  13960. }
  13961. }
  13962. /*
  13963. ** Uninstall the VFS wrapper that was installed around the file-descriptor open
  13964. ** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be
  13965. ** held when this function is called.
  13966. */
  13967. static void recoverUninstallWrapper(sqlite3_recover *p){
  13968. sqlite3_file *pFd = 0;
  13969. recoverAssertMutexHeld();
  13970. sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd);
  13971. if( pFd && pFd->pMethods ){
  13972. pFd->pMethods = recover_g.pMethods;
  13973. recover_g.pMethods = 0;
  13974. recover_g.p = 0;
  13975. }
  13976. }
  13977. /*
  13978. ** This function does the work of a single sqlite3_recover_step() call. It
  13979. ** is guaranteed that the handle is not in an error state when this
  13980. ** function is called.
  13981. */
  13982. static void recoverStep(sqlite3_recover *p){
  13983. assert( p && p->errCode==SQLITE_OK );
  13984. switch( p->eState ){
  13985. case RECOVER_STATE_INIT:
  13986. /* This is the very first call to sqlite3_recover_step() on this object.
  13987. */
  13988. recoverSqlCallback(p, "BEGIN");
  13989. recoverSqlCallback(p, "PRAGMA writable_schema = on");
  13990. recoverEnterMutex();
  13991. recoverInstallWrapper(p);
  13992. /* Open the output database. And register required virtual tables and
  13993. ** user functions with the new handle. */
  13994. recoverOpenOutput(p);
  13995. /* Open transactions on both the input and output databases. */
  13996. recoverExec(p, p->dbIn, "PRAGMA writable_schema = on");
  13997. recoverExec(p, p->dbIn, "BEGIN");
  13998. if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1;
  13999. recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema");
  14000. recoverTransferSettings(p);
  14001. recoverOpenRecovery(p);
  14002. recoverCacheSchema(p);
  14003. recoverUninstallWrapper(p);
  14004. recoverLeaveMutex();
  14005. recoverExec(p, p->dbOut, "BEGIN");
  14006. recoverWriteSchema1(p);
  14007. p->eState = RECOVER_STATE_WRITING;
  14008. break;
  14009. case RECOVER_STATE_WRITING: {
  14010. if( p->w1.pTbls==0 ){
  14011. recoverWriteDataInit(p);
  14012. }
  14013. if( SQLITE_DONE==recoverWriteDataStep(p) ){
  14014. recoverWriteDataCleanup(p);
  14015. if( p->zLostAndFound ){
  14016. p->eState = RECOVER_STATE_LOSTANDFOUND1;
  14017. }else{
  14018. p->eState = RECOVER_STATE_SCHEMA2;
  14019. }
  14020. }
  14021. break;
  14022. }
  14023. case RECOVER_STATE_LOSTANDFOUND1: {
  14024. if( p->laf.pUsed==0 ){
  14025. recoverLostAndFound1Init(p);
  14026. }
  14027. if( SQLITE_DONE==recoverLostAndFound1Step(p) ){
  14028. p->eState = RECOVER_STATE_LOSTANDFOUND2;
  14029. }
  14030. break;
  14031. }
  14032. case RECOVER_STATE_LOSTANDFOUND2: {
  14033. if( p->laf.pAllAndParent==0 ){
  14034. recoverLostAndFound2Init(p);
  14035. }
  14036. if( SQLITE_DONE==recoverLostAndFound2Step(p) ){
  14037. p->eState = RECOVER_STATE_LOSTANDFOUND3;
  14038. }
  14039. break;
  14040. }
  14041. case RECOVER_STATE_LOSTANDFOUND3: {
  14042. if( p->laf.pInsert==0 ){
  14043. recoverLostAndFound3Init(p);
  14044. }
  14045. if( SQLITE_DONE==recoverLostAndFound3Step(p) ){
  14046. p->eState = RECOVER_STATE_SCHEMA2;
  14047. }
  14048. break;
  14049. }
  14050. case RECOVER_STATE_SCHEMA2: {
  14051. int rc = SQLITE_OK;
  14052. recoverWriteSchema2(p);
  14053. p->eState = RECOVER_STATE_DONE;
  14054. /* If no error has occurred, commit the write transaction on the output
  14055. ** database. Regardless of whether or not an error has occurred, make
  14056. ** an attempt to end the read transaction on the input database. */
  14057. recoverExec(p, p->dbOut, "COMMIT");
  14058. rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
  14059. if( p->errCode==SQLITE_OK ) p->errCode = rc;
  14060. recoverSqlCallback(p, "PRAGMA writable_schema = off");
  14061. recoverSqlCallback(p, "COMMIT");
  14062. p->eState = RECOVER_STATE_DONE;
  14063. recoverFinalCleanup(p);
  14064. break;
  14065. };
  14066. case RECOVER_STATE_DONE: {
  14067. /* no-op */
  14068. break;
  14069. };
  14070. }
  14071. }
  14072. /*
  14073. ** This is a worker function that does the heavy lifting for both init
  14074. ** functions:
  14075. **
  14076. ** sqlite3_recover_init()
  14077. ** sqlite3_recover_init_sql()
  14078. **
  14079. ** All this function does is allocate space for the recover handle and
  14080. ** take copies of the input parameters. All the real work is done within
  14081. ** sqlite3_recover_run().
  14082. */
  14083. sqlite3_recover *recoverInit(
  14084. sqlite3* db,
  14085. const char *zDb,
  14086. const char *zUri, /* Output URI for _recover_init() */
  14087. int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */
  14088. void *pSqlCtx /* Context arg for _recover_init_sql() */
  14089. ){
  14090. sqlite3_recover *pRet = 0;
  14091. int nDb = 0;
  14092. int nUri = 0;
  14093. int nByte = 0;
  14094. if( zDb==0 ){ zDb = "main"; }
  14095. nDb = recoverStrlen(zDb);
  14096. nUri = recoverStrlen(zUri);
  14097. nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1;
  14098. pRet = (sqlite3_recover*)sqlite3_malloc(nByte);
  14099. if( pRet ){
  14100. memset(pRet, 0, nByte);
  14101. pRet->dbIn = db;
  14102. pRet->zDb = (char*)&pRet[1];
  14103. pRet->zUri = &pRet->zDb[nDb+1];
  14104. memcpy(pRet->zDb, zDb, nDb);
  14105. if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri);
  14106. pRet->xSql = xSql;
  14107. pRet->pSqlCtx = pSqlCtx;
  14108. pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT;
  14109. }
  14110. return pRet;
  14111. }
  14112. /*
  14113. ** Initialize a recovery handle that creates a new database containing
  14114. ** the recovered data.
  14115. */
  14116. sqlite3_recover *sqlite3_recover_init(
  14117. sqlite3* db,
  14118. const char *zDb,
  14119. const char *zUri
  14120. ){
  14121. return recoverInit(db, zDb, zUri, 0, 0);
  14122. }
  14123. /*
  14124. ** Initialize a recovery handle that returns recovered data in the
  14125. ** form of SQL statements via a callback.
  14126. */
  14127. sqlite3_recover *sqlite3_recover_init_sql(
  14128. sqlite3* db,
  14129. const char *zDb,
  14130. int (*xSql)(void*, const char*),
  14131. void *pSqlCtx
  14132. ){
  14133. return recoverInit(db, zDb, 0, xSql, pSqlCtx);
  14134. }
  14135. /*
  14136. ** Return the handle error message, if any.
  14137. */
  14138. const char *sqlite3_recover_errmsg(sqlite3_recover *p){
  14139. return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory";
  14140. }
  14141. /*
  14142. ** Return the handle error code.
  14143. */
  14144. int sqlite3_recover_errcode(sqlite3_recover *p){
  14145. return p ? p->errCode : SQLITE_NOMEM;
  14146. }
  14147. /*
  14148. ** Configure the handle.
  14149. */
  14150. int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){
  14151. int rc = SQLITE_OK;
  14152. if( p==0 ){
  14153. rc = SQLITE_NOMEM;
  14154. }else if( p->eState!=RECOVER_STATE_INIT ){
  14155. rc = SQLITE_MISUSE;
  14156. }else{
  14157. switch( op ){
  14158. case 789:
  14159. /* This undocumented magic configuration option is used to set the
  14160. ** name of the auxiliary database that is ATTACH-ed to the database
  14161. ** connection and used to hold state information during the
  14162. ** recovery process. This option is for debugging use only and
  14163. ** is subject to change or removal at any time. */
  14164. sqlite3_free(p->zStateDb);
  14165. p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg);
  14166. break;
  14167. case SQLITE_RECOVER_LOST_AND_FOUND: {
  14168. const char *zArg = (const char*)pArg;
  14169. sqlite3_free(p->zLostAndFound);
  14170. if( zArg ){
  14171. p->zLostAndFound = recoverMPrintf(p, "%s", zArg);
  14172. }else{
  14173. p->zLostAndFound = 0;
  14174. }
  14175. break;
  14176. }
  14177. case SQLITE_RECOVER_FREELIST_CORRUPT:
  14178. p->bFreelistCorrupt = *(int*)pArg;
  14179. break;
  14180. case SQLITE_RECOVER_ROWIDS:
  14181. p->bRecoverRowid = *(int*)pArg;
  14182. break;
  14183. case SQLITE_RECOVER_SLOWINDEXES:
  14184. p->bSlowIndexes = *(int*)pArg;
  14185. break;
  14186. default:
  14187. rc = SQLITE_NOTFOUND;
  14188. break;
  14189. }
  14190. }
  14191. return rc;
  14192. }
  14193. /*
  14194. ** Do a unit of work towards the recovery job. Return SQLITE_OK if
  14195. ** no error has occurred but database recovery is not finished, SQLITE_DONE
  14196. ** if database recovery has been successfully completed, or an SQLite
  14197. ** error code if an error has occurred.
  14198. */
  14199. int sqlite3_recover_step(sqlite3_recover *p){
  14200. if( p==0 ) return SQLITE_NOMEM;
  14201. if( p->errCode==SQLITE_OK ) recoverStep(p);
  14202. if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){
  14203. return SQLITE_DONE;
  14204. }
  14205. return p->errCode;
  14206. }
  14207. /*
  14208. ** Do the configured recovery operation. Return SQLITE_OK if successful, or
  14209. ** else an SQLite error code.
  14210. */
  14211. int sqlite3_recover_run(sqlite3_recover *p){
  14212. while( SQLITE_OK==sqlite3_recover_step(p) );
  14213. return sqlite3_recover_errcode(p);
  14214. }
  14215. /*
  14216. ** Free all resources associated with the recover handle passed as the only
  14217. ** argument. The results of using a handle with any sqlite3_recover_**
  14218. ** API function after it has been passed to this function are undefined.
  14219. **
  14220. ** A copy of the value returned by the first call made to sqlite3_recover_run()
  14221. ** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has
  14222. ** not been called on this handle.
  14223. */
  14224. int sqlite3_recover_finish(sqlite3_recover *p){
  14225. int rc;
  14226. if( p==0 ){
  14227. rc = SQLITE_NOMEM;
  14228. }else{
  14229. recoverFinalCleanup(p);
  14230. if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
  14231. rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
  14232. if( p->errCode==SQLITE_OK ) p->errCode = rc;
  14233. }
  14234. rc = p->errCode;
  14235. sqlite3_free(p->zErrMsg);
  14236. sqlite3_free(p->zStateDb);
  14237. sqlite3_free(p->zLostAndFound);
  14238. sqlite3_free(p->pPage1Cache);
  14239. sqlite3_free(p);
  14240. }
  14241. return rc;
  14242. }
  14243. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  14244. /************************* End ../ext/recover/sqlite3recover.c ********************/
  14245. #endif
  14246. #if defined(SQLITE_ENABLE_SESSION)
  14247. /*
  14248. ** State information for a single open session
  14249. */
  14250. typedef struct OpenSession OpenSession;
  14251. struct OpenSession {
  14252. char *zName; /* Symbolic name for this session */
  14253. int nFilter; /* Number of xFilter rejection GLOB patterns */
  14254. char **azFilter; /* Array of xFilter rejection GLOB patterns */
  14255. sqlite3_session *p; /* The open session */
  14256. };
  14257. #endif
  14258. typedef struct ExpertInfo ExpertInfo;
  14259. struct ExpertInfo {
  14260. sqlite3expert *pExpert;
  14261. int bVerbose;
  14262. };
  14263. /* A single line in the EQP output */
  14264. typedef struct EQPGraphRow EQPGraphRow;
  14265. struct EQPGraphRow {
  14266. int iEqpId; /* ID for this row */
  14267. int iParentId; /* ID of the parent row */
  14268. EQPGraphRow *pNext; /* Next row in sequence */
  14269. char zText[1]; /* Text to display for this row */
  14270. };
  14271. /* All EQP output is collected into an instance of the following */
  14272. typedef struct EQPGraph EQPGraph;
  14273. struct EQPGraph {
  14274. EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
  14275. EQPGraphRow *pLast; /* Last element of the pRow list */
  14276. char zPrefix[100]; /* Graph prefix */
  14277. };
  14278. /* Parameters affecting columnar mode result display (defaulting together) */
  14279. typedef struct ColModeOpts {
  14280. int iWrap; /* In columnar modes, wrap lines reaching this limit */
  14281. u8 bQuote; /* Quote results for .mode box and table */
  14282. u8 bWordWrap; /* In columnar modes, wrap at word boundaries */
  14283. } ColModeOpts;
  14284. #define ColModeOpts_default { 60, 0, 0 }
  14285. #define ColModeOpts_default_qbox { 60, 1, 0 }
  14286. /*
  14287. ** State information about the database connection is contained in an
  14288. ** instance of the following structure.
  14289. */
  14290. typedef struct ShellState ShellState;
  14291. struct ShellState {
  14292. sqlite3 *db; /* The database */
  14293. u8 autoExplain; /* Automatically turn on .explain mode */
  14294. u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
  14295. u8 autoEQPtest; /* autoEQP is in test mode */
  14296. u8 autoEQPtrace; /* autoEQP is in trace mode */
  14297. u8 scanstatsOn; /* True to display scan stats before each finalize */
  14298. u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
  14299. u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
  14300. u8 nEqpLevel; /* Depth of the EQP output graph */
  14301. u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
  14302. u8 bSafeMode; /* True to prohibit unsafe operations */
  14303. u8 bSafeModePersist; /* The long-term value of bSafeMode */
  14304. ColModeOpts cmOpts; /* Option values affecting columnar mode output */
  14305. unsigned statsOn; /* True to display memory stats before each finalize */
  14306. unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
  14307. int inputNesting; /* Track nesting level of .read and other redirects */
  14308. int outCount; /* Revert to stdout when reaching zero */
  14309. int cnt; /* Number of records displayed so far */
  14310. int lineno; /* Line number of last line read from in */
  14311. int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
  14312. FILE *in; /* Read commands from this stream */
  14313. FILE *out; /* Write results here */
  14314. FILE *traceOut; /* Output for sqlite3_trace() */
  14315. int nErr; /* Number of errors seen */
  14316. int mode; /* An output mode setting */
  14317. int modePrior; /* Saved mode */
  14318. int cMode; /* temporary output mode for the current query */
  14319. int normalMode; /* Output mode before ".explain on" */
  14320. int writableSchema; /* True if PRAGMA writable_schema=ON */
  14321. int showHeader; /* True to show column names in List or Column mode */
  14322. int nCheck; /* Number of ".check" commands run */
  14323. unsigned nProgress; /* Number of progress callbacks encountered */
  14324. unsigned mxProgress; /* Maximum progress callbacks before failing */
  14325. unsigned flgProgress; /* Flags for the progress callback */
  14326. unsigned shellFlgs; /* Various flags */
  14327. unsigned priorShFlgs; /* Saved copy of flags */
  14328. sqlite3_int64 szMax; /* --maxsize argument to .open */
  14329. char *zDestTable; /* Name of destination table when MODE_Insert */
  14330. char *zTempFile; /* Temporary file that might need deleting */
  14331. char zTestcase[30]; /* Name of current test case */
  14332. char colSeparator[20]; /* Column separator character for several modes */
  14333. char rowSeparator[20]; /* Row separator character for MODE_Ascii */
  14334. char colSepPrior[20]; /* Saved column separator */
  14335. char rowSepPrior[20]; /* Saved row separator */
  14336. int *colWidth; /* Requested width of each column in columnar modes */
  14337. int *actualWidth; /* Actual width of each column */
  14338. int nWidth; /* Number of slots in colWidth[] and actualWidth[] */
  14339. char nullValue[20]; /* The text to print when a NULL comes back from
  14340. ** the database */
  14341. char outfile[FILENAME_MAX]; /* Filename for *out */
  14342. sqlite3_stmt *pStmt; /* Current statement if any. */
  14343. FILE *pLog; /* Write log output here */
  14344. struct AuxDb { /* Storage space for auxiliary database connections */
  14345. sqlite3 *db; /* Connection pointer */
  14346. const char *zDbFilename; /* Filename used to open the connection */
  14347. char *zFreeOnClose; /* Free this memory allocation on close */
  14348. #if defined(SQLITE_ENABLE_SESSION)
  14349. int nSession; /* Number of active sessions */
  14350. OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
  14351. #endif
  14352. } aAuxDb[5], /* Array of all database connections */
  14353. *pAuxDb; /* Currently active database connection */
  14354. int *aiIndent; /* Array of indents used in MODE_Explain */
  14355. int nIndent; /* Size of array aiIndent[] */
  14356. int iIndent; /* Index of current op in aiIndent[] */
  14357. char *zNonce; /* Nonce for temporary safe-mode excapes */
  14358. EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
  14359. ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
  14360. #ifdef SQLITE_SHELL_FIDDLE
  14361. struct {
  14362. const char * zInput; /* Input string from wasm/JS proxy */
  14363. const char * zPos; /* Cursor pos into zInput */
  14364. const char * zDefaultDbName; /* Default name for db file */
  14365. } wasm;
  14366. #endif
  14367. };
  14368. #ifdef SQLITE_SHELL_FIDDLE
  14369. static ShellState shellState;
  14370. #endif
  14371. /* Allowed values for ShellState.autoEQP
  14372. */
  14373. #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
  14374. #define AUTOEQP_on 1 /* Automatic EQP is on */
  14375. #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
  14376. #define AUTOEQP_full 3 /* Show full EXPLAIN */
  14377. /* Allowed values for ShellState.openMode
  14378. */
  14379. #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
  14380. #define SHELL_OPEN_NORMAL 1 /* Normal database file */
  14381. #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
  14382. #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
  14383. #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
  14384. #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
  14385. #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
  14386. /* Allowed values for ShellState.eTraceType
  14387. */
  14388. #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
  14389. #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
  14390. #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
  14391. /* Bits in the ShellState.flgProgress variable */
  14392. #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
  14393. #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
  14394. ** callback limit is reached, and for each
  14395. ** top-level SQL statement */
  14396. #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
  14397. /*
  14398. ** These are the allowed shellFlgs values
  14399. */
  14400. #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
  14401. #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
  14402. #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
  14403. #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
  14404. #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
  14405. #define SHFLG_CountChanges 0x00000020 /* .changes setting */
  14406. #define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */
  14407. #define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */
  14408. #define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */
  14409. #define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */
  14410. /*
  14411. ** Macros for testing and setting shellFlgs
  14412. */
  14413. #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
  14414. #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
  14415. #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
  14416. /*
  14417. ** These are the allowed modes.
  14418. */
  14419. #define MODE_Line 0 /* One column per line. Blank line between records */
  14420. #define MODE_Column 1 /* One record per line in neat columns */
  14421. #define MODE_List 2 /* One record per line with a separator */
  14422. #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
  14423. #define MODE_Html 4 /* Generate an XHTML table */
  14424. #define MODE_Insert 5 /* Generate SQL "insert" statements */
  14425. #define MODE_Quote 6 /* Quote values as for SQL */
  14426. #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
  14427. #define MODE_Csv 8 /* Quote strings, numbers are plain */
  14428. #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
  14429. #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
  14430. #define MODE_Pretty 11 /* Pretty-print schemas */
  14431. #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
  14432. #define MODE_Json 13 /* Output JSON */
  14433. #define MODE_Markdown 14 /* Markdown formatting */
  14434. #define MODE_Table 15 /* MySQL-style table formatting */
  14435. #define MODE_Box 16 /* Unicode box-drawing characters */
  14436. #define MODE_Count 17 /* Output only a count of the rows of output */
  14437. #define MODE_Off 18 /* No query output shown */
  14438. static const char *modeDescr[] = {
  14439. "line",
  14440. "column",
  14441. "list",
  14442. "semi",
  14443. "html",
  14444. "insert",
  14445. "quote",
  14446. "tcl",
  14447. "csv",
  14448. "explain",
  14449. "ascii",
  14450. "prettyprint",
  14451. "eqp",
  14452. "json",
  14453. "markdown",
  14454. "table",
  14455. "box",
  14456. "count",
  14457. "off"
  14458. };
  14459. /*
  14460. ** These are the column/row/line separators used by the various
  14461. ** import/export modes.
  14462. */
  14463. #define SEP_Column "|"
  14464. #define SEP_Row "\n"
  14465. #define SEP_Tab "\t"
  14466. #define SEP_Space " "
  14467. #define SEP_Comma ","
  14468. #define SEP_CrLf "\r\n"
  14469. #define SEP_Unit "\x1F"
  14470. #define SEP_Record "\x1E"
  14471. /*
  14472. ** Limit input nesting via .read or any other input redirect.
  14473. ** It's not too expensive, so a generous allowance can be made.
  14474. */
  14475. #define MAX_INPUT_NESTING 25
  14476. /*
  14477. ** A callback for the sqlite3_log() interface.
  14478. */
  14479. static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  14480. ShellState *p = (ShellState*)pArg;
  14481. if( p->pLog==0 ) return;
  14482. utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  14483. fflush(p->pLog);
  14484. }
  14485. /*
  14486. ** SQL function: shell_putsnl(X)
  14487. **
  14488. ** Write the text X to the screen (or whatever output is being directed)
  14489. ** adding a newline at the end, and then return X.
  14490. */
  14491. static void shellPutsFunc(
  14492. sqlite3_context *pCtx,
  14493. int nVal,
  14494. sqlite3_value **apVal
  14495. ){
  14496. ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
  14497. (void)nVal;
  14498. utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
  14499. sqlite3_result_value(pCtx, apVal[0]);
  14500. }
  14501. /*
  14502. ** If in safe mode, print an error message described by the arguments
  14503. ** and exit immediately.
  14504. */
  14505. static void failIfSafeMode(
  14506. ShellState *p,
  14507. const char *zErrMsg,
  14508. ...
  14509. ){
  14510. if( p->bSafeMode ){
  14511. va_list ap;
  14512. char *zMsg;
  14513. va_start(ap, zErrMsg);
  14514. zMsg = sqlite3_vmprintf(zErrMsg, ap);
  14515. va_end(ap);
  14516. raw_printf(stderr, "line %d: ", p->lineno);
  14517. utf8_printf(stderr, "%s\n", zMsg);
  14518. exit(1);
  14519. }
  14520. }
  14521. /*
  14522. ** SQL function: edit(VALUE)
  14523. ** edit(VALUE,EDITOR)
  14524. **
  14525. ** These steps:
  14526. **
  14527. ** (1) Write VALUE into a temporary file.
  14528. ** (2) Run program EDITOR on that temporary file.
  14529. ** (3) Read the temporary file back and return its content as the result.
  14530. ** (4) Delete the temporary file
  14531. **
  14532. ** If the EDITOR argument is omitted, use the value in the VISUAL
  14533. ** environment variable. If still there is no EDITOR, through an error.
  14534. **
  14535. ** Also throw an error if the EDITOR program returns a non-zero exit code.
  14536. */
  14537. #ifndef SQLITE_NOHAVE_SYSTEM
  14538. static void editFunc(
  14539. sqlite3_context *context,
  14540. int argc,
  14541. sqlite3_value **argv
  14542. ){
  14543. const char *zEditor;
  14544. char *zTempFile = 0;
  14545. sqlite3 *db;
  14546. char *zCmd = 0;
  14547. int bBin;
  14548. int rc;
  14549. int hasCRNL = 0;
  14550. FILE *f = 0;
  14551. sqlite3_int64 sz;
  14552. sqlite3_int64 x;
  14553. unsigned char *p = 0;
  14554. if( argc==2 ){
  14555. zEditor = (const char*)sqlite3_value_text(argv[1]);
  14556. }else{
  14557. zEditor = getenv("VISUAL");
  14558. }
  14559. if( zEditor==0 ){
  14560. sqlite3_result_error(context, "no editor for edit()", -1);
  14561. return;
  14562. }
  14563. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  14564. sqlite3_result_error(context, "NULL input to edit()", -1);
  14565. return;
  14566. }
  14567. db = sqlite3_context_db_handle(context);
  14568. zTempFile = 0;
  14569. sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
  14570. if( zTempFile==0 ){
  14571. sqlite3_uint64 r = 0;
  14572. sqlite3_randomness(sizeof(r), &r);
  14573. zTempFile = sqlite3_mprintf("temp%llx", r);
  14574. if( zTempFile==0 ){
  14575. sqlite3_result_error_nomem(context);
  14576. return;
  14577. }
  14578. }
  14579. bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
  14580. /* When writing the file to be edited, do \n to \r\n conversions on systems
  14581. ** that want \r\n line endings */
  14582. f = fopen(zTempFile, bBin ? "wb" : "w");
  14583. if( f==0 ){
  14584. sqlite3_result_error(context, "edit() cannot open temp file", -1);
  14585. goto edit_func_end;
  14586. }
  14587. sz = sqlite3_value_bytes(argv[0]);
  14588. if( bBin ){
  14589. x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
  14590. }else{
  14591. const char *z = (const char*)sqlite3_value_text(argv[0]);
  14592. /* Remember whether or not the value originally contained \r\n */
  14593. if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
  14594. x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
  14595. }
  14596. fclose(f);
  14597. f = 0;
  14598. if( x!=sz ){
  14599. sqlite3_result_error(context, "edit() could not write the whole file", -1);
  14600. goto edit_func_end;
  14601. }
  14602. zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
  14603. if( zCmd==0 ){
  14604. sqlite3_result_error_nomem(context);
  14605. goto edit_func_end;
  14606. }
  14607. rc = system(zCmd);
  14608. sqlite3_free(zCmd);
  14609. if( rc ){
  14610. sqlite3_result_error(context, "EDITOR returned non-zero", -1);
  14611. goto edit_func_end;
  14612. }
  14613. f = fopen(zTempFile, "rb");
  14614. if( f==0 ){
  14615. sqlite3_result_error(context,
  14616. "edit() cannot reopen temp file after edit", -1);
  14617. goto edit_func_end;
  14618. }
  14619. fseek(f, 0, SEEK_END);
  14620. sz = ftell(f);
  14621. rewind(f);
  14622. p = sqlite3_malloc64( sz+1 );
  14623. if( p==0 ){
  14624. sqlite3_result_error_nomem(context);
  14625. goto edit_func_end;
  14626. }
  14627. x = fread(p, 1, (size_t)sz, f);
  14628. fclose(f);
  14629. f = 0;
  14630. if( x!=sz ){
  14631. sqlite3_result_error(context, "could not read back the whole file", -1);
  14632. goto edit_func_end;
  14633. }
  14634. if( bBin ){
  14635. sqlite3_result_blob64(context, p, sz, sqlite3_free);
  14636. }else{
  14637. sqlite3_int64 i, j;
  14638. if( hasCRNL ){
  14639. /* If the original contains \r\n then do no conversions back to \n */
  14640. }else{
  14641. /* If the file did not originally contain \r\n then convert any new
  14642. ** \r\n back into \n */
  14643. for(i=j=0; i<sz; i++){
  14644. if( p[i]=='\r' && p[i+1]=='\n' ) i++;
  14645. p[j++] = p[i];
  14646. }
  14647. sz = j;
  14648. p[sz] = 0;
  14649. }
  14650. sqlite3_result_text64(context, (const char*)p, sz,
  14651. sqlite3_free, SQLITE_UTF8);
  14652. }
  14653. p = 0;
  14654. edit_func_end:
  14655. if( f ) fclose(f);
  14656. unlink(zTempFile);
  14657. sqlite3_free(zTempFile);
  14658. sqlite3_free(p);
  14659. }
  14660. #endif /* SQLITE_NOHAVE_SYSTEM */
  14661. /*
  14662. ** Save or restore the current output mode
  14663. */
  14664. static void outputModePush(ShellState *p){
  14665. p->modePrior = p->mode;
  14666. p->priorShFlgs = p->shellFlgs;
  14667. memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
  14668. memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
  14669. }
  14670. static void outputModePop(ShellState *p){
  14671. p->mode = p->modePrior;
  14672. p->shellFlgs = p->priorShFlgs;
  14673. memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
  14674. memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
  14675. }
  14676. /*
  14677. ** Output the given string as a hex-encoded blob (eg. X'1234' )
  14678. */
  14679. static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  14680. int i;
  14681. unsigned char *aBlob = (unsigned char*)pBlob;
  14682. char *zStr = sqlite3_malloc(nBlob*2 + 1);
  14683. shell_check_oom(zStr);
  14684. for(i=0; i<nBlob; i++){
  14685. static const char aHex[] = {
  14686. '0', '1', '2', '3', '4', '5', '6', '7',
  14687. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
  14688. };
  14689. zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
  14690. zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
  14691. }
  14692. zStr[i*2] = '\0';
  14693. raw_printf(out,"X'%s'", zStr);
  14694. sqlite3_free(zStr);
  14695. }
  14696. /*
  14697. ** Find a string that is not found anywhere in z[]. Return a pointer
  14698. ** to that string.
  14699. **
  14700. ** Try to use zA and zB first. If both of those are already found in z[]
  14701. ** then make up some string and store it in the buffer zBuf.
  14702. */
  14703. static const char *unused_string(
  14704. const char *z, /* Result must not appear anywhere in z */
  14705. const char *zA, const char *zB, /* Try these first */
  14706. char *zBuf /* Space to store a generated string */
  14707. ){
  14708. unsigned i = 0;
  14709. if( strstr(z, zA)==0 ) return zA;
  14710. if( strstr(z, zB)==0 ) return zB;
  14711. do{
  14712. sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
  14713. }while( strstr(z,zBuf)!=0 );
  14714. return zBuf;
  14715. }
  14716. /*
  14717. ** Output the given string as a quoted string using SQL quoting conventions.
  14718. **
  14719. ** See also: output_quoted_escaped_string()
  14720. */
  14721. static void output_quoted_string(FILE *out, const char *z){
  14722. int i;
  14723. char c;
  14724. setBinaryMode(out, 1);
  14725. for(i=0; (c = z[i])!=0 && c!='\''; i++){}
  14726. if( c==0 ){
  14727. utf8_printf(out,"'%s'",z);
  14728. }else{
  14729. raw_printf(out, "'");
  14730. while( *z ){
  14731. for(i=0; (c = z[i])!=0 && c!='\''; i++){}
  14732. if( c=='\'' ) i++;
  14733. if( i ){
  14734. utf8_printf(out, "%.*s", i, z);
  14735. z += i;
  14736. }
  14737. if( c=='\'' ){
  14738. raw_printf(out, "'");
  14739. continue;
  14740. }
  14741. if( c==0 ){
  14742. break;
  14743. }
  14744. z++;
  14745. }
  14746. raw_printf(out, "'");
  14747. }
  14748. setTextMode(out, 1);
  14749. }
  14750. /*
  14751. ** Output the given string as a quoted string using SQL quoting conventions.
  14752. ** Additionallly , escape the "\n" and "\r" characters so that they do not
  14753. ** get corrupted by end-of-line translation facilities in some operating
  14754. ** systems.
  14755. **
  14756. ** This is like output_quoted_string() but with the addition of the \r\n
  14757. ** escape mechanism.
  14758. */
  14759. static void output_quoted_escaped_string(FILE *out, const char *z){
  14760. int i;
  14761. char c;
  14762. setBinaryMode(out, 1);
  14763. for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
  14764. if( c==0 ){
  14765. utf8_printf(out,"'%s'",z);
  14766. }else{
  14767. const char *zNL = 0;
  14768. const char *zCR = 0;
  14769. int nNL = 0;
  14770. int nCR = 0;
  14771. char zBuf1[20], zBuf2[20];
  14772. for(i=0; z[i]; i++){
  14773. if( z[i]=='\n' ) nNL++;
  14774. if( z[i]=='\r' ) nCR++;
  14775. }
  14776. if( nNL ){
  14777. raw_printf(out, "replace(");
  14778. zNL = unused_string(z, "\\n", "\\012", zBuf1);
  14779. }
  14780. if( nCR ){
  14781. raw_printf(out, "replace(");
  14782. zCR = unused_string(z, "\\r", "\\015", zBuf2);
  14783. }
  14784. raw_printf(out, "'");
  14785. while( *z ){
  14786. for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
  14787. if( c=='\'' ) i++;
  14788. if( i ){
  14789. utf8_printf(out, "%.*s", i, z);
  14790. z += i;
  14791. }
  14792. if( c=='\'' ){
  14793. raw_printf(out, "'");
  14794. continue;
  14795. }
  14796. if( c==0 ){
  14797. break;
  14798. }
  14799. z++;
  14800. if( c=='\n' ){
  14801. raw_printf(out, "%s", zNL);
  14802. continue;
  14803. }
  14804. raw_printf(out, "%s", zCR);
  14805. }
  14806. raw_printf(out, "'");
  14807. if( nCR ){
  14808. raw_printf(out, ",'%s',char(13))", zCR);
  14809. }
  14810. if( nNL ){
  14811. raw_printf(out, ",'%s',char(10))", zNL);
  14812. }
  14813. }
  14814. setTextMode(out, 1);
  14815. }
  14816. /*
  14817. ** Output the given string as a quoted according to C or TCL quoting rules.
  14818. */
  14819. static void output_c_string(FILE *out, const char *z){
  14820. unsigned int c;
  14821. fputc('"', out);
  14822. while( (c = *(z++))!=0 ){
  14823. if( c=='\\' ){
  14824. fputc(c, out);
  14825. fputc(c, out);
  14826. }else if( c=='"' ){
  14827. fputc('\\', out);
  14828. fputc('"', out);
  14829. }else if( c=='\t' ){
  14830. fputc('\\', out);
  14831. fputc('t', out);
  14832. }else if( c=='\n' ){
  14833. fputc('\\', out);
  14834. fputc('n', out);
  14835. }else if( c=='\r' ){
  14836. fputc('\\', out);
  14837. fputc('r', out);
  14838. }else if( !isprint(c&0xff) ){
  14839. raw_printf(out, "\\%03o", c&0xff);
  14840. }else{
  14841. fputc(c, out);
  14842. }
  14843. }
  14844. fputc('"', out);
  14845. }
  14846. /*
  14847. ** Output the given string as a quoted according to JSON quoting rules.
  14848. */
  14849. static void output_json_string(FILE *out, const char *z, i64 n){
  14850. unsigned int c;
  14851. if( n<0 ) n = strlen(z);
  14852. fputc('"', out);
  14853. while( n-- ){
  14854. c = *(z++);
  14855. if( c=='\\' || c=='"' ){
  14856. fputc('\\', out);
  14857. fputc(c, out);
  14858. }else if( c<=0x1f ){
  14859. fputc('\\', out);
  14860. if( c=='\b' ){
  14861. fputc('b', out);
  14862. }else if( c=='\f' ){
  14863. fputc('f', out);
  14864. }else if( c=='\n' ){
  14865. fputc('n', out);
  14866. }else if( c=='\r' ){
  14867. fputc('r', out);
  14868. }else if( c=='\t' ){
  14869. fputc('t', out);
  14870. }else{
  14871. raw_printf(out, "u%04x",c);
  14872. }
  14873. }else{
  14874. fputc(c, out);
  14875. }
  14876. }
  14877. fputc('"', out);
  14878. }
  14879. /*
  14880. ** Output the given string with characters that are special to
  14881. ** HTML escaped.
  14882. */
  14883. static void output_html_string(FILE *out, const char *z){
  14884. int i;
  14885. if( z==0 ) z = "";
  14886. while( *z ){
  14887. for(i=0; z[i]
  14888. && z[i]!='<'
  14889. && z[i]!='&'
  14890. && z[i]!='>'
  14891. && z[i]!='\"'
  14892. && z[i]!='\'';
  14893. i++){}
  14894. if( i>0 ){
  14895. utf8_printf(out,"%.*s",i,z);
  14896. }
  14897. if( z[i]=='<' ){
  14898. raw_printf(out,"&lt;");
  14899. }else if( z[i]=='&' ){
  14900. raw_printf(out,"&amp;");
  14901. }else if( z[i]=='>' ){
  14902. raw_printf(out,"&gt;");
  14903. }else if( z[i]=='\"' ){
  14904. raw_printf(out,"&quot;");
  14905. }else if( z[i]=='\'' ){
  14906. raw_printf(out,"&#39;");
  14907. }else{
  14908. break;
  14909. }
  14910. z += i + 1;
  14911. }
  14912. }
  14913. /*
  14914. ** If a field contains any character identified by a 1 in the following
  14915. ** array, then the string must be quoted for CSV.
  14916. */
  14917. static const char needCsvQuote[] = {
  14918. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  14919. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  14920. 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  14921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  14922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  14923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  14924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  14925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  14926. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  14927. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  14928. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  14929. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  14930. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  14931. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  14932. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  14933. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  14934. };
  14935. /*
  14936. ** Output a single term of CSV. Actually, p->colSeparator is used for
  14937. ** the separator, which may or may not be a comma. p->nullValue is
  14938. ** the null value. Strings are quoted if necessary. The separator
  14939. ** is only issued if bSep is true.
  14940. */
  14941. static void output_csv(ShellState *p, const char *z, int bSep){
  14942. FILE *out = p->out;
  14943. if( z==0 ){
  14944. utf8_printf(out,"%s",p->nullValue);
  14945. }else{
  14946. unsigned i;
  14947. for(i=0; z[i]; i++){
  14948. if( needCsvQuote[((unsigned char*)z)[i]] ){
  14949. i = 0;
  14950. break;
  14951. }
  14952. }
  14953. if( i==0 || strstr(z, p->colSeparator)!=0 ){
  14954. char *zQuoted = sqlite3_mprintf("\"%w\"", z);
  14955. shell_check_oom(zQuoted);
  14956. utf8_printf(out, "%s", zQuoted);
  14957. sqlite3_free(zQuoted);
  14958. }else{
  14959. utf8_printf(out, "%s", z);
  14960. }
  14961. }
  14962. if( bSep ){
  14963. utf8_printf(p->out, "%s", p->colSeparator);
  14964. }
  14965. }
  14966. /*
  14967. ** This routine runs when the user presses Ctrl-C
  14968. */
  14969. static void interrupt_handler(int NotUsed){
  14970. UNUSED_PARAMETER(NotUsed);
  14971. seenInterrupt++;
  14972. if( seenInterrupt>2 ) exit(1);
  14973. if( globalDb ) sqlite3_interrupt(globalDb);
  14974. }
  14975. #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
  14976. /*
  14977. ** This routine runs for console events (e.g. Ctrl-C) on Win32
  14978. */
  14979. static BOOL WINAPI ConsoleCtrlHandler(
  14980. DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
  14981. ){
  14982. if( dwCtrlType==CTRL_C_EVENT ){
  14983. interrupt_handler(0);
  14984. return TRUE;
  14985. }
  14986. return FALSE;
  14987. }
  14988. #endif
  14989. #ifndef SQLITE_OMIT_AUTHORIZATION
  14990. /*
  14991. ** This authorizer runs in safe mode.
  14992. */
  14993. static int safeModeAuth(
  14994. void *pClientData,
  14995. int op,
  14996. const char *zA1,
  14997. const char *zA2,
  14998. const char *zA3,
  14999. const char *zA4
  15000. ){
  15001. ShellState *p = (ShellState*)pClientData;
  15002. static const char *azProhibitedFunctions[] = {
  15003. "edit",
  15004. "fts3_tokenizer",
  15005. "load_extension",
  15006. "readfile",
  15007. "writefile",
  15008. "zipfile",
  15009. "zipfile_cds",
  15010. };
  15011. UNUSED_PARAMETER(zA2);
  15012. UNUSED_PARAMETER(zA3);
  15013. UNUSED_PARAMETER(zA4);
  15014. switch( op ){
  15015. case SQLITE_ATTACH: {
  15016. #ifndef SQLITE_SHELL_FIDDLE
  15017. /* In WASM builds the filesystem is a virtual sandbox, so
  15018. ** there's no harm in using ATTACH. */
  15019. failIfSafeMode(p, "cannot run ATTACH in safe mode");
  15020. #endif
  15021. break;
  15022. }
  15023. case SQLITE_FUNCTION: {
  15024. int i;
  15025. for(i=0; i<ArraySize(azProhibitedFunctions); i++){
  15026. if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
  15027. failIfSafeMode(p, "cannot use the %s() function in safe mode",
  15028. azProhibitedFunctions[i]);
  15029. }
  15030. }
  15031. break;
  15032. }
  15033. }
  15034. return SQLITE_OK;
  15035. }
  15036. /*
  15037. ** When the ".auth ON" is set, the following authorizer callback is
  15038. ** invoked. It always returns SQLITE_OK.
  15039. */
  15040. static int shellAuth(
  15041. void *pClientData,
  15042. int op,
  15043. const char *zA1,
  15044. const char *zA2,
  15045. const char *zA3,
  15046. const char *zA4
  15047. ){
  15048. ShellState *p = (ShellState*)pClientData;
  15049. static const char *azAction[] = { 0,
  15050. "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
  15051. "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
  15052. "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
  15053. "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
  15054. "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
  15055. "DROP_TRIGGER", "DROP_VIEW", "INSERT",
  15056. "PRAGMA", "READ", "SELECT",
  15057. "TRANSACTION", "UPDATE", "ATTACH",
  15058. "DETACH", "ALTER_TABLE", "REINDEX",
  15059. "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
  15060. "FUNCTION", "SAVEPOINT", "RECURSIVE"
  15061. };
  15062. int i;
  15063. const char *az[4];
  15064. az[0] = zA1;
  15065. az[1] = zA2;
  15066. az[2] = zA3;
  15067. az[3] = zA4;
  15068. utf8_printf(p->out, "authorizer: %s", azAction[op]);
  15069. for(i=0; i<4; i++){
  15070. raw_printf(p->out, " ");
  15071. if( az[i] ){
  15072. output_c_string(p->out, az[i]);
  15073. }else{
  15074. raw_printf(p->out, "NULL");
  15075. }
  15076. }
  15077. raw_printf(p->out, "\n");
  15078. if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
  15079. return SQLITE_OK;
  15080. }
  15081. #endif
  15082. /*
  15083. ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
  15084. **
  15085. ** This routine converts some CREATE TABLE statements for shadow tables
  15086. ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
  15087. **
  15088. ** If the schema statement in z[] contains a start-of-comment and if
  15089. ** sqlite3_complete() returns false, try to terminate the comment before
  15090. ** printing the result. https://sqlite.org/forum/forumpost/d7be961c5c
  15091. */
  15092. static void printSchemaLine(FILE *out, const char *z, const char *zTail){
  15093. char *zToFree = 0;
  15094. if( z==0 ) return;
  15095. if( zTail==0 ) return;
  15096. if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
  15097. const char *zOrig = z;
  15098. static const char *azTerm[] = { "", "*/", "\n" };
  15099. int i;
  15100. for(i=0; i<ArraySize(azTerm); i++){
  15101. char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
  15102. if( sqlite3_complete(zNew) ){
  15103. size_t n = strlen(zNew);
  15104. zNew[n-1] = 0;
  15105. zToFree = zNew;
  15106. z = zNew;
  15107. break;
  15108. }
  15109. sqlite3_free(zNew);
  15110. }
  15111. }
  15112. if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
  15113. utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
  15114. }else{
  15115. utf8_printf(out, "%s%s", z, zTail);
  15116. }
  15117. sqlite3_free(zToFree);
  15118. }
  15119. static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
  15120. char c = z[n];
  15121. z[n] = 0;
  15122. printSchemaLine(out, z, zTail);
  15123. z[n] = c;
  15124. }
  15125. /*
  15126. ** Return true if string z[] has nothing but whitespace and comments to the
  15127. ** end of the first line.
  15128. */
  15129. static int wsToEol(const char *z){
  15130. int i;
  15131. for(i=0; z[i]; i++){
  15132. if( z[i]=='\n' ) return 1;
  15133. if( IsSpace(z[i]) ) continue;
  15134. if( z[i]=='-' && z[i+1]=='-' ) return 1;
  15135. return 0;
  15136. }
  15137. return 1;
  15138. }
  15139. /*
  15140. ** Add a new entry to the EXPLAIN QUERY PLAN data
  15141. */
  15142. static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
  15143. EQPGraphRow *pNew;
  15144. i64 nText;
  15145. if( zText==0 ) return;
  15146. nText = strlen(zText);
  15147. if( p->autoEQPtest ){
  15148. utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
  15149. }
  15150. pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
  15151. shell_check_oom(pNew);
  15152. pNew->iEqpId = iEqpId;
  15153. pNew->iParentId = p2;
  15154. memcpy(pNew->zText, zText, nText+1);
  15155. pNew->pNext = 0;
  15156. if( p->sGraph.pLast ){
  15157. p->sGraph.pLast->pNext = pNew;
  15158. }else{
  15159. p->sGraph.pRow = pNew;
  15160. }
  15161. p->sGraph.pLast = pNew;
  15162. }
  15163. /*
  15164. ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
  15165. ** in p->sGraph.
  15166. */
  15167. static void eqp_reset(ShellState *p){
  15168. EQPGraphRow *pRow, *pNext;
  15169. for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
  15170. pNext = pRow->pNext;
  15171. sqlite3_free(pRow);
  15172. }
  15173. memset(&p->sGraph, 0, sizeof(p->sGraph));
  15174. }
  15175. /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
  15176. ** pOld, or return the first such line if pOld is NULL
  15177. */
  15178. static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
  15179. EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
  15180. while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
  15181. return pRow;
  15182. }
  15183. /* Render a single level of the graph that has iEqpId as its parent. Called
  15184. ** recursively to render sublevels.
  15185. */
  15186. static void eqp_render_level(ShellState *p, int iEqpId){
  15187. EQPGraphRow *pRow, *pNext;
  15188. i64 n = strlen(p->sGraph.zPrefix);
  15189. char *z;
  15190. for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
  15191. pNext = eqp_next_row(p, iEqpId, pRow);
  15192. z = pRow->zText;
  15193. utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
  15194. pNext ? "|--" : "`--", z);
  15195. if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
  15196. memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
  15197. eqp_render_level(p, pRow->iEqpId);
  15198. p->sGraph.zPrefix[n] = 0;
  15199. }
  15200. }
  15201. }
  15202. /*
  15203. ** Display and reset the EXPLAIN QUERY PLAN data
  15204. */
  15205. static void eqp_render(ShellState *p){
  15206. EQPGraphRow *pRow = p->sGraph.pRow;
  15207. if( pRow ){
  15208. if( pRow->zText[0]=='-' ){
  15209. if( pRow->pNext==0 ){
  15210. eqp_reset(p);
  15211. return;
  15212. }
  15213. utf8_printf(p->out, "%s\n", pRow->zText+3);
  15214. p->sGraph.pRow = pRow->pNext;
  15215. sqlite3_free(pRow);
  15216. }else{
  15217. utf8_printf(p->out, "QUERY PLAN\n");
  15218. }
  15219. p->sGraph.zPrefix[0] = 0;
  15220. eqp_render_level(p, 0);
  15221. eqp_reset(p);
  15222. }
  15223. }
  15224. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  15225. /*
  15226. ** Progress handler callback.
  15227. */
  15228. static int progress_handler(void *pClientData) {
  15229. ShellState *p = (ShellState*)pClientData;
  15230. p->nProgress++;
  15231. if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
  15232. raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
  15233. if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
  15234. if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
  15235. return 1;
  15236. }
  15237. if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
  15238. raw_printf(p->out, "Progress %u\n", p->nProgress);
  15239. }
  15240. return 0;
  15241. }
  15242. #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
  15243. /*
  15244. ** Print N dashes
  15245. */
  15246. static void print_dashes(FILE *out, int N){
  15247. const char zDash[] = "--------------------------------------------------";
  15248. const int nDash = sizeof(zDash) - 1;
  15249. while( N>nDash ){
  15250. fputs(zDash, out);
  15251. N -= nDash;
  15252. }
  15253. raw_printf(out, "%.*s", N, zDash);
  15254. }
  15255. /*
  15256. ** Print a markdown or table-style row separator using ascii-art
  15257. */
  15258. static void print_row_separator(
  15259. ShellState *p,
  15260. int nArg,
  15261. const char *zSep
  15262. ){
  15263. int i;
  15264. if( nArg>0 ){
  15265. fputs(zSep, p->out);
  15266. print_dashes(p->out, p->actualWidth[0]+2);
  15267. for(i=1; i<nArg; i++){
  15268. fputs(zSep, p->out);
  15269. print_dashes(p->out, p->actualWidth[i]+2);
  15270. }
  15271. fputs(zSep, p->out);
  15272. }
  15273. fputs("\n", p->out);
  15274. }
  15275. /*
  15276. ** This is the callback routine that the shell
  15277. ** invokes for each row of a query result.
  15278. */
  15279. static int shell_callback(
  15280. void *pArg,
  15281. int nArg, /* Number of result columns */
  15282. char **azArg, /* Text of each result column */
  15283. char **azCol, /* Column names */
  15284. int *aiType /* Column types. Might be NULL */
  15285. ){
  15286. int i;
  15287. ShellState *p = (ShellState*)pArg;
  15288. if( azArg==0 ) return 0;
  15289. switch( p->cMode ){
  15290. case MODE_Count:
  15291. case MODE_Off: {
  15292. break;
  15293. }
  15294. case MODE_Line: {
  15295. int w = 5;
  15296. if( azArg==0 ) break;
  15297. for(i=0; i<nArg; i++){
  15298. int len = strlen30(azCol[i] ? azCol[i] : "");
  15299. if( len>w ) w = len;
  15300. }
  15301. if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
  15302. for(i=0; i<nArg; i++){
  15303. utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
  15304. azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
  15305. }
  15306. break;
  15307. }
  15308. case MODE_Explain: {
  15309. static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
  15310. if( nArg>ArraySize(aExplainWidth) ){
  15311. nArg = ArraySize(aExplainWidth);
  15312. }
  15313. if( p->cnt++==0 ){
  15314. for(i=0; i<nArg; i++){
  15315. int w = aExplainWidth[i];
  15316. utf8_width_print(p->out, w, azCol[i]);
  15317. fputs(i==nArg-1 ? "\n" : " ", p->out);
  15318. }
  15319. for(i=0; i<nArg; i++){
  15320. int w = aExplainWidth[i];
  15321. print_dashes(p->out, w);
  15322. fputs(i==nArg-1 ? "\n" : " ", p->out);
  15323. }
  15324. }
  15325. if( azArg==0 ) break;
  15326. for(i=0; i<nArg; i++){
  15327. int w = aExplainWidth[i];
  15328. if( i==nArg-1 ) w = 0;
  15329. if( azArg[i] && strlenChar(azArg[i])>w ){
  15330. w = strlenChar(azArg[i]);
  15331. }
  15332. if( i==1 && p->aiIndent && p->pStmt ){
  15333. if( p->iIndent<p->nIndent ){
  15334. utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
  15335. }
  15336. p->iIndent++;
  15337. }
  15338. utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
  15339. fputs(i==nArg-1 ? "\n" : " ", p->out);
  15340. }
  15341. break;
  15342. }
  15343. case MODE_Semi: { /* .schema and .fullschema output */
  15344. printSchemaLine(p->out, azArg[0], ";\n");
  15345. break;
  15346. }
  15347. case MODE_Pretty: { /* .schema and .fullschema with --indent */
  15348. char *z;
  15349. int j;
  15350. int nParen = 0;
  15351. char cEnd = 0;
  15352. char c;
  15353. int nLine = 0;
  15354. assert( nArg==1 );
  15355. if( azArg[0]==0 ) break;
  15356. if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
  15357. || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
  15358. ){
  15359. utf8_printf(p->out, "%s;\n", azArg[0]);
  15360. break;
  15361. }
  15362. z = sqlite3_mprintf("%s", azArg[0]);
  15363. shell_check_oom(z);
  15364. j = 0;
  15365. for(i=0; IsSpace(z[i]); i++){}
  15366. for(; (c = z[i])!=0; i++){
  15367. if( IsSpace(c) ){
  15368. if( z[j-1]=='\r' ) z[j-1] = '\n';
  15369. if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
  15370. }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
  15371. j--;
  15372. }
  15373. z[j++] = c;
  15374. }
  15375. while( j>0 && IsSpace(z[j-1]) ){ j--; }
  15376. z[j] = 0;
  15377. if( strlen30(z)>=79 ){
  15378. for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
  15379. if( c==cEnd ){
  15380. cEnd = 0;
  15381. }else if( c=='"' || c=='\'' || c=='`' ){
  15382. cEnd = c;
  15383. }else if( c=='[' ){
  15384. cEnd = ']';
  15385. }else if( c=='-' && z[i+1]=='-' ){
  15386. cEnd = '\n';
  15387. }else if( c=='(' ){
  15388. nParen++;
  15389. }else if( c==')' ){
  15390. nParen--;
  15391. if( nLine>0 && nParen==0 && j>0 ){
  15392. printSchemaLineN(p->out, z, j, "\n");
  15393. j = 0;
  15394. }
  15395. }
  15396. z[j++] = c;
  15397. if( nParen==1 && cEnd==0
  15398. && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
  15399. ){
  15400. if( c=='\n' ) j--;
  15401. printSchemaLineN(p->out, z, j, "\n ");
  15402. j = 0;
  15403. nLine++;
  15404. while( IsSpace(z[i+1]) ){ i++; }
  15405. }
  15406. }
  15407. z[j] = 0;
  15408. }
  15409. printSchemaLine(p->out, z, ";\n");
  15410. sqlite3_free(z);
  15411. break;
  15412. }
  15413. case MODE_List: {
  15414. if( p->cnt++==0 && p->showHeader ){
  15415. for(i=0; i<nArg; i++){
  15416. utf8_printf(p->out,"%s%s",azCol[i],
  15417. i==nArg-1 ? p->rowSeparator : p->colSeparator);
  15418. }
  15419. }
  15420. if( azArg==0 ) break;
  15421. for(i=0; i<nArg; i++){
  15422. char *z = azArg[i];
  15423. if( z==0 ) z = p->nullValue;
  15424. utf8_printf(p->out, "%s", z);
  15425. if( i<nArg-1 ){
  15426. utf8_printf(p->out, "%s", p->colSeparator);
  15427. }else{
  15428. utf8_printf(p->out, "%s", p->rowSeparator);
  15429. }
  15430. }
  15431. break;
  15432. }
  15433. case MODE_Html: {
  15434. if( p->cnt++==0 && p->showHeader ){
  15435. raw_printf(p->out,"<TR>");
  15436. for(i=0; i<nArg; i++){
  15437. raw_printf(p->out,"<TH>");
  15438. output_html_string(p->out, azCol[i]);
  15439. raw_printf(p->out,"</TH>\n");
  15440. }
  15441. raw_printf(p->out,"</TR>\n");
  15442. }
  15443. if( azArg==0 ) break;
  15444. raw_printf(p->out,"<TR>");
  15445. for(i=0; i<nArg; i++){
  15446. raw_printf(p->out,"<TD>");
  15447. output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  15448. raw_printf(p->out,"</TD>\n");
  15449. }
  15450. raw_printf(p->out,"</TR>\n");
  15451. break;
  15452. }
  15453. case MODE_Tcl: {
  15454. if( p->cnt++==0 && p->showHeader ){
  15455. for(i=0; i<nArg; i++){
  15456. output_c_string(p->out,azCol[i] ? azCol[i] : "");
  15457. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  15458. }
  15459. utf8_printf(p->out, "%s", p->rowSeparator);
  15460. }
  15461. if( azArg==0 ) break;
  15462. for(i=0; i<nArg; i++){
  15463. output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  15464. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  15465. }
  15466. utf8_printf(p->out, "%s", p->rowSeparator);
  15467. break;
  15468. }
  15469. case MODE_Csv: {
  15470. setBinaryMode(p->out, 1);
  15471. if( p->cnt++==0 && p->showHeader ){
  15472. for(i=0; i<nArg; i++){
  15473. output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  15474. }
  15475. utf8_printf(p->out, "%s", p->rowSeparator);
  15476. }
  15477. if( nArg>0 ){
  15478. for(i=0; i<nArg; i++){
  15479. output_csv(p, azArg[i], i<nArg-1);
  15480. }
  15481. utf8_printf(p->out, "%s", p->rowSeparator);
  15482. }
  15483. setTextMode(p->out, 1);
  15484. break;
  15485. }
  15486. case MODE_Insert: {
  15487. if( azArg==0 ) break;
  15488. utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
  15489. if( p->showHeader ){
  15490. raw_printf(p->out,"(");
  15491. for(i=0; i<nArg; i++){
  15492. if( i>0 ) raw_printf(p->out, ",");
  15493. if( quoteChar(azCol[i]) ){
  15494. char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
  15495. shell_check_oom(z);
  15496. utf8_printf(p->out, "%s", z);
  15497. sqlite3_free(z);
  15498. }else{
  15499. raw_printf(p->out, "%s", azCol[i]);
  15500. }
  15501. }
  15502. raw_printf(p->out,")");
  15503. }
  15504. p->cnt++;
  15505. for(i=0; i<nArg; i++){
  15506. raw_printf(p->out, i>0 ? "," : " VALUES(");
  15507. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  15508. utf8_printf(p->out,"NULL");
  15509. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  15510. if( ShellHasFlag(p, SHFLG_Newlines) ){
  15511. output_quoted_string(p->out, azArg[i]);
  15512. }else{
  15513. output_quoted_escaped_string(p->out, azArg[i]);
  15514. }
  15515. }else if( aiType && aiType[i]==SQLITE_INTEGER ){
  15516. utf8_printf(p->out,"%s", azArg[i]);
  15517. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  15518. char z[50];
  15519. double r = sqlite3_column_double(p->pStmt, i);
  15520. sqlite3_uint64 ur;
  15521. memcpy(&ur,&r,sizeof(r));
  15522. if( ur==0x7ff0000000000000LL ){
  15523. raw_printf(p->out, "1e999");
  15524. }else if( ur==0xfff0000000000000LL ){
  15525. raw_printf(p->out, "-1e999");
  15526. }else{
  15527. sqlite3_int64 ir = (sqlite3_int64)r;
  15528. if( r==(double)ir ){
  15529. sqlite3_snprintf(50,z,"%lld.0", ir);
  15530. }else{
  15531. sqlite3_snprintf(50,z,"%!.20g", r);
  15532. }
  15533. raw_printf(p->out, "%s", z);
  15534. }
  15535. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  15536. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  15537. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  15538. output_hex_blob(p->out, pBlob, nBlob);
  15539. }else if( isNumber(azArg[i], 0) ){
  15540. utf8_printf(p->out,"%s", azArg[i]);
  15541. }else if( ShellHasFlag(p, SHFLG_Newlines) ){
  15542. output_quoted_string(p->out, azArg[i]);
  15543. }else{
  15544. output_quoted_escaped_string(p->out, azArg[i]);
  15545. }
  15546. }
  15547. raw_printf(p->out,");\n");
  15548. break;
  15549. }
  15550. case MODE_Json: {
  15551. if( azArg==0 ) break;
  15552. if( p->cnt==0 ){
  15553. fputs("[{", p->out);
  15554. }else{
  15555. fputs(",\n{", p->out);
  15556. }
  15557. p->cnt++;
  15558. for(i=0; i<nArg; i++){
  15559. output_json_string(p->out, azCol[i], -1);
  15560. putc(':', p->out);
  15561. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  15562. fputs("null",p->out);
  15563. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  15564. char z[50];
  15565. double r = sqlite3_column_double(p->pStmt, i);
  15566. sqlite3_uint64 ur;
  15567. memcpy(&ur,&r,sizeof(r));
  15568. if( ur==0x7ff0000000000000LL ){
  15569. raw_printf(p->out, "1e999");
  15570. }else if( ur==0xfff0000000000000LL ){
  15571. raw_printf(p->out, "-1e999");
  15572. }else{
  15573. sqlite3_snprintf(50,z,"%!.20g", r);
  15574. raw_printf(p->out, "%s", z);
  15575. }
  15576. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  15577. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  15578. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  15579. output_json_string(p->out, pBlob, nBlob);
  15580. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  15581. output_json_string(p->out, azArg[i], -1);
  15582. }else{
  15583. utf8_printf(p->out,"%s", azArg[i]);
  15584. }
  15585. if( i<nArg-1 ){
  15586. putc(',', p->out);
  15587. }
  15588. }
  15589. putc('}', p->out);
  15590. break;
  15591. }
  15592. case MODE_Quote: {
  15593. if( azArg==0 ) break;
  15594. if( p->cnt==0 && p->showHeader ){
  15595. for(i=0; i<nArg; i++){
  15596. if( i>0 ) fputs(p->colSeparator, p->out);
  15597. output_quoted_string(p->out, azCol[i]);
  15598. }
  15599. fputs(p->rowSeparator, p->out);
  15600. }
  15601. p->cnt++;
  15602. for(i=0; i<nArg; i++){
  15603. if( i>0 ) fputs(p->colSeparator, p->out);
  15604. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  15605. utf8_printf(p->out,"NULL");
  15606. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  15607. output_quoted_string(p->out, azArg[i]);
  15608. }else if( aiType && aiType[i]==SQLITE_INTEGER ){
  15609. utf8_printf(p->out,"%s", azArg[i]);
  15610. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  15611. char z[50];
  15612. double r = sqlite3_column_double(p->pStmt, i);
  15613. sqlite3_snprintf(50,z,"%!.20g", r);
  15614. raw_printf(p->out, "%s", z);
  15615. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  15616. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  15617. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  15618. output_hex_blob(p->out, pBlob, nBlob);
  15619. }else if( isNumber(azArg[i], 0) ){
  15620. utf8_printf(p->out,"%s", azArg[i]);
  15621. }else{
  15622. output_quoted_string(p->out, azArg[i]);
  15623. }
  15624. }
  15625. fputs(p->rowSeparator, p->out);
  15626. break;
  15627. }
  15628. case MODE_Ascii: {
  15629. if( p->cnt++==0 && p->showHeader ){
  15630. for(i=0; i<nArg; i++){
  15631. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  15632. utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
  15633. }
  15634. utf8_printf(p->out, "%s", p->rowSeparator);
  15635. }
  15636. if( azArg==0 ) break;
  15637. for(i=0; i<nArg; i++){
  15638. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  15639. utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
  15640. }
  15641. utf8_printf(p->out, "%s", p->rowSeparator);
  15642. break;
  15643. }
  15644. case MODE_EQP: {
  15645. eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
  15646. break;
  15647. }
  15648. }
  15649. return 0;
  15650. }
  15651. /*
  15652. ** This is the callback routine that the SQLite library
  15653. ** invokes for each row of a query result.
  15654. */
  15655. static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  15656. /* since we don't have type info, call the shell_callback with a NULL value */
  15657. return shell_callback(pArg, nArg, azArg, azCol, NULL);
  15658. }
  15659. /*
  15660. ** This is the callback routine from sqlite3_exec() that appends all
  15661. ** output onto the end of a ShellText object.
  15662. */
  15663. static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
  15664. ShellText *p = (ShellText*)pArg;
  15665. int i;
  15666. UNUSED_PARAMETER(az);
  15667. if( azArg==0 ) return 0;
  15668. if( p->n ) appendText(p, "|", 0);
  15669. for(i=0; i<nArg; i++){
  15670. if( i ) appendText(p, ",", 0);
  15671. if( azArg[i] ) appendText(p, azArg[i], 0);
  15672. }
  15673. return 0;
  15674. }
  15675. /*
  15676. ** Generate an appropriate SELFTEST table in the main database.
  15677. */
  15678. static void createSelftestTable(ShellState *p){
  15679. char *zErrMsg = 0;
  15680. sqlite3_exec(p->db,
  15681. "SAVEPOINT selftest_init;\n"
  15682. "CREATE TABLE IF NOT EXISTS selftest(\n"
  15683. " tno INTEGER PRIMARY KEY,\n" /* Test number */
  15684. " op TEXT,\n" /* Operator: memo run */
  15685. " cmd TEXT,\n" /* Command text */
  15686. " ans TEXT\n" /* Desired answer */
  15687. ");"
  15688. "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
  15689. "INSERT INTO [_shell$self](rowid,op,cmd)\n"
  15690. " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
  15691. " 'memo','Tests generated by --init');\n"
  15692. "INSERT INTO [_shell$self]\n"
  15693. " SELECT 'run',\n"
  15694. " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
  15695. "FROM sqlite_schema ORDER BY 2'',224))',\n"
  15696. " hex(sha3_query('SELECT type,name,tbl_name,sql "
  15697. "FROM sqlite_schema ORDER BY 2',224));\n"
  15698. "INSERT INTO [_shell$self]\n"
  15699. " SELECT 'run',"
  15700. " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
  15701. " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
  15702. " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
  15703. " FROM (\n"
  15704. " SELECT name FROM sqlite_schema\n"
  15705. " WHERE type='table'\n"
  15706. " AND name<>'selftest'\n"
  15707. " AND coalesce(rootpage,0)>0\n"
  15708. " )\n"
  15709. " ORDER BY name;\n"
  15710. "INSERT INTO [_shell$self]\n"
  15711. " VALUES('run','PRAGMA integrity_check','ok');\n"
  15712. "INSERT INTO selftest(tno,op,cmd,ans)"
  15713. " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
  15714. "DROP TABLE [_shell$self];"
  15715. ,0,0,&zErrMsg);
  15716. if( zErrMsg ){
  15717. utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
  15718. sqlite3_free(zErrMsg);
  15719. }
  15720. sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
  15721. }
  15722. /*
  15723. ** Set the destination table field of the ShellState structure to
  15724. ** the name of the table given. Escape any quote characters in the
  15725. ** table name.
  15726. */
  15727. static void set_table_name(ShellState *p, const char *zName){
  15728. int i, n;
  15729. char cQuote;
  15730. char *z;
  15731. if( p->zDestTable ){
  15732. free(p->zDestTable);
  15733. p->zDestTable = 0;
  15734. }
  15735. if( zName==0 ) return;
  15736. cQuote = quoteChar(zName);
  15737. n = strlen30(zName);
  15738. if( cQuote ) n += n+2;
  15739. z = p->zDestTable = malloc( n+1 );
  15740. shell_check_oom(z);
  15741. n = 0;
  15742. if( cQuote ) z[n++] = cQuote;
  15743. for(i=0; zName[i]; i++){
  15744. z[n++] = zName[i];
  15745. if( zName[i]==cQuote ) z[n++] = cQuote;
  15746. }
  15747. if( cQuote ) z[n++] = cQuote;
  15748. z[n] = 0;
  15749. }
  15750. /*
  15751. ** Maybe construct two lines of text that point out the position of a
  15752. ** syntax error. Return a pointer to the text, in memory obtained from
  15753. ** sqlite3_malloc(). Or, if the most recent error does not involve a
  15754. ** specific token that we can point to, return an empty string.
  15755. **
  15756. ** In all cases, the memory returned is obtained from sqlite3_malloc64()
  15757. ** and should be released by the caller invoking sqlite3_free().
  15758. */
  15759. static char *shell_error_context(const char *zSql, sqlite3 *db){
  15760. int iOffset;
  15761. size_t len;
  15762. char *zCode;
  15763. char *zMsg;
  15764. int i;
  15765. if( db==0
  15766. || zSql==0
  15767. || (iOffset = sqlite3_error_offset(db))<0
  15768. ){
  15769. return sqlite3_mprintf("");
  15770. }
  15771. while( iOffset>50 ){
  15772. iOffset--;
  15773. zSql++;
  15774. while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
  15775. }
  15776. len = strlen(zSql);
  15777. if( len>78 ){
  15778. len = 78;
  15779. while( (zSql[len]&0xc0)==0x80 ) len--;
  15780. }
  15781. zCode = sqlite3_mprintf("%.*s", len, zSql);
  15782. shell_check_oom(zCode);
  15783. for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
  15784. if( iOffset<25 ){
  15785. zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode, iOffset, "");
  15786. }else{
  15787. zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode, iOffset-14, "");
  15788. }
  15789. return zMsg;
  15790. }
  15791. /*
  15792. ** Execute a query statement that will generate SQL output. Print
  15793. ** the result columns, comma-separated, on a line and then add a
  15794. ** semicolon terminator to the end of that line.
  15795. **
  15796. ** If the number of columns is 1 and that column contains text "--"
  15797. ** then write the semicolon on a separate line. That way, if a
  15798. ** "--" comment occurs at the end of the statement, the comment
  15799. ** won't consume the semicolon terminator.
  15800. */
  15801. static int run_table_dump_query(
  15802. ShellState *p, /* Query context */
  15803. const char *zSelect /* SELECT statement to extract content */
  15804. ){
  15805. sqlite3_stmt *pSelect;
  15806. int rc;
  15807. int nResult;
  15808. int i;
  15809. const char *z;
  15810. rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
  15811. if( rc!=SQLITE_OK || !pSelect ){
  15812. char *zContext = shell_error_context(zSelect, p->db);
  15813. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
  15814. sqlite3_errmsg(p->db), zContext);
  15815. sqlite3_free(zContext);
  15816. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  15817. return rc;
  15818. }
  15819. rc = sqlite3_step(pSelect);
  15820. nResult = sqlite3_column_count(pSelect);
  15821. while( rc==SQLITE_ROW ){
  15822. z = (const char*)sqlite3_column_text(pSelect, 0);
  15823. utf8_printf(p->out, "%s", z);
  15824. for(i=1; i<nResult; i++){
  15825. utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
  15826. }
  15827. if( z==0 ) z = "";
  15828. while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
  15829. if( z[0] ){
  15830. raw_printf(p->out, "\n;\n");
  15831. }else{
  15832. raw_printf(p->out, ";\n");
  15833. }
  15834. rc = sqlite3_step(pSelect);
  15835. }
  15836. rc = sqlite3_finalize(pSelect);
  15837. if( rc!=SQLITE_OK ){
  15838. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  15839. sqlite3_errmsg(p->db));
  15840. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  15841. }
  15842. return rc;
  15843. }
  15844. /*
  15845. ** Allocate space and save off string indicating current error.
  15846. */
  15847. static char *save_err_msg(
  15848. sqlite3 *db, /* Database to query */
  15849. const char *zPhase, /* When the error occcurs */
  15850. int rc, /* Error code returned from API */
  15851. const char *zSql /* SQL string, or NULL */
  15852. ){
  15853. char *zErr;
  15854. char *zContext;
  15855. sqlite3_str *pStr = sqlite3_str_new(0);
  15856. sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
  15857. if( rc>1 ){
  15858. sqlite3_str_appendf(pStr, " (%d)", rc);
  15859. }
  15860. zContext = shell_error_context(zSql, db);
  15861. if( zContext ){
  15862. sqlite3_str_appendall(pStr, zContext);
  15863. sqlite3_free(zContext);
  15864. }
  15865. zErr = sqlite3_str_finish(pStr);
  15866. shell_check_oom(zErr);
  15867. return zErr;
  15868. }
  15869. #ifdef __linux__
  15870. /*
  15871. ** Attempt to display I/O stats on Linux using /proc/PID/io
  15872. */
  15873. static void displayLinuxIoStats(FILE *out){
  15874. FILE *in;
  15875. char z[200];
  15876. sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
  15877. in = fopen(z, "rb");
  15878. if( in==0 ) return;
  15879. while( fgets(z, sizeof(z), in)!=0 ){
  15880. static const struct {
  15881. const char *zPattern;
  15882. const char *zDesc;
  15883. } aTrans[] = {
  15884. { "rchar: ", "Bytes received by read():" },
  15885. { "wchar: ", "Bytes sent to write():" },
  15886. { "syscr: ", "Read() system calls:" },
  15887. { "syscw: ", "Write() system calls:" },
  15888. { "read_bytes: ", "Bytes read from storage:" },
  15889. { "write_bytes: ", "Bytes written to storage:" },
  15890. { "cancelled_write_bytes: ", "Cancelled write bytes:" },
  15891. };
  15892. int i;
  15893. for(i=0; i<ArraySize(aTrans); i++){
  15894. int n = strlen30(aTrans[i].zPattern);
  15895. if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
  15896. utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
  15897. break;
  15898. }
  15899. }
  15900. }
  15901. fclose(in);
  15902. }
  15903. #endif
  15904. /*
  15905. ** Display a single line of status using 64-bit values.
  15906. */
  15907. static void displayStatLine(
  15908. ShellState *p, /* The shell context */
  15909. char *zLabel, /* Label for this one line */
  15910. char *zFormat, /* Format for the result */
  15911. int iStatusCtrl, /* Which status to display */
  15912. int bReset /* True to reset the stats */
  15913. ){
  15914. sqlite3_int64 iCur = -1;
  15915. sqlite3_int64 iHiwtr = -1;
  15916. int i, nPercent;
  15917. char zLine[200];
  15918. sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
  15919. for(i=0, nPercent=0; zFormat[i]; i++){
  15920. if( zFormat[i]=='%' ) nPercent++;
  15921. }
  15922. if( nPercent>1 ){
  15923. sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
  15924. }else{
  15925. sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
  15926. }
  15927. raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
  15928. }
  15929. /*
  15930. ** Display memory stats.
  15931. */
  15932. static int display_stats(
  15933. sqlite3 *db, /* Database to query */
  15934. ShellState *pArg, /* Pointer to ShellState */
  15935. int bReset /* True to reset the stats */
  15936. ){
  15937. int iCur;
  15938. int iHiwtr;
  15939. FILE *out;
  15940. if( pArg==0 || pArg->out==0 ) return 0;
  15941. out = pArg->out;
  15942. if( pArg->pStmt && pArg->statsOn==2 ){
  15943. int nCol, i, x;
  15944. sqlite3_stmt *pStmt = pArg->pStmt;
  15945. char z[100];
  15946. nCol = sqlite3_column_count(pStmt);
  15947. raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
  15948. for(i=0; i<nCol; i++){
  15949. sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
  15950. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
  15951. #ifndef SQLITE_OMIT_DECLTYPE
  15952. sqlite3_snprintf(30, z+x, "declared type:");
  15953. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
  15954. #endif
  15955. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  15956. sqlite3_snprintf(30, z+x, "database name:");
  15957. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
  15958. sqlite3_snprintf(30, z+x, "table name:");
  15959. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
  15960. sqlite3_snprintf(30, z+x, "origin name:");
  15961. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
  15962. #endif
  15963. }
  15964. }
  15965. if( pArg->statsOn==3 ){
  15966. if( pArg->pStmt ){
  15967. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
  15968. raw_printf(pArg->out, "VM-steps: %d\n", iCur);
  15969. }
  15970. return 0;
  15971. }
  15972. displayStatLine(pArg, "Memory Used:",
  15973. "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
  15974. displayStatLine(pArg, "Number of Outstanding Allocations:",
  15975. "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
  15976. if( pArg->shellFlgs & SHFLG_Pagecache ){
  15977. displayStatLine(pArg, "Number of Pcache Pages Used:",
  15978. "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
  15979. }
  15980. displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
  15981. "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
  15982. displayStatLine(pArg, "Largest Allocation:",
  15983. "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
  15984. displayStatLine(pArg, "Largest Pcache Allocation:",
  15985. "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
  15986. #ifdef YYTRACKMAXSTACKDEPTH
  15987. displayStatLine(pArg, "Deepest Parser Stack:",
  15988. "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
  15989. #endif
  15990. if( db ){
  15991. if( pArg->shellFlgs & SHFLG_Lookaside ){
  15992. iHiwtr = iCur = -1;
  15993. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
  15994. &iCur, &iHiwtr, bReset);
  15995. raw_printf(pArg->out,
  15996. "Lookaside Slots Used: %d (max %d)\n",
  15997. iCur, iHiwtr);
  15998. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
  15999. &iCur, &iHiwtr, bReset);
  16000. raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
  16001. iHiwtr);
  16002. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
  16003. &iCur, &iHiwtr, bReset);
  16004. raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
  16005. iHiwtr);
  16006. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
  16007. &iCur, &iHiwtr, bReset);
  16008. raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
  16009. iHiwtr);
  16010. }
  16011. iHiwtr = iCur = -1;
  16012. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
  16013. raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
  16014. iCur);
  16015. iHiwtr = iCur = -1;
  16016. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
  16017. raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
  16018. iHiwtr = iCur = -1;
  16019. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
  16020. raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
  16021. iHiwtr = iCur = -1;
  16022. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
  16023. raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
  16024. iHiwtr = iCur = -1;
  16025. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
  16026. raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
  16027. iHiwtr = iCur = -1;
  16028. sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
  16029. raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
  16030. iCur);
  16031. iHiwtr = iCur = -1;
  16032. sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
  16033. raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
  16034. iCur);
  16035. }
  16036. if( pArg->pStmt ){
  16037. int iHit, iMiss;
  16038. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
  16039. bReset);
  16040. raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
  16041. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
  16042. raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
  16043. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
  16044. raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
  16045. iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
  16046. iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
  16047. if( iHit || iMiss ){
  16048. raw_printf(pArg->out, "Bloom filter bypass taken: %d/%d\n",
  16049. iHit, iHit+iMiss);
  16050. }
  16051. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
  16052. raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
  16053. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
  16054. raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
  16055. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
  16056. raw_printf(pArg->out, "Number of times run: %d\n", iCur);
  16057. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
  16058. raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
  16059. }
  16060. #ifdef __linux__
  16061. displayLinuxIoStats(pArg->out);
  16062. #endif
  16063. /* Do not remove this machine readable comment: extra-stats-output-here */
  16064. return 0;
  16065. }
  16066. /*
  16067. ** Display scan stats.
  16068. */
  16069. static void display_scanstats(
  16070. sqlite3 *db, /* Database to query */
  16071. ShellState *pArg /* Pointer to ShellState */
  16072. ){
  16073. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  16074. UNUSED_PARAMETER(db);
  16075. UNUSED_PARAMETER(pArg);
  16076. #else
  16077. int i, k, n, mx;
  16078. raw_printf(pArg->out, "-------- scanstats --------\n");
  16079. mx = 0;
  16080. for(k=0; k<=mx; k++){
  16081. double rEstLoop = 1.0;
  16082. for(i=n=0; 1; i++){
  16083. sqlite3_stmt *p = pArg->pStmt;
  16084. sqlite3_int64 nLoop, nVisit;
  16085. double rEst;
  16086. int iSid;
  16087. const char *zExplain;
  16088. if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
  16089. break;
  16090. }
  16091. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
  16092. if( iSid>mx ) mx = iSid;
  16093. if( iSid!=k ) continue;
  16094. if( n==0 ){
  16095. rEstLoop = (double)nLoop;
  16096. if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
  16097. }
  16098. n++;
  16099. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
  16100. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
  16101. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
  16102. utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
  16103. rEstLoop *= rEst;
  16104. raw_printf(pArg->out,
  16105. " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
  16106. nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
  16107. );
  16108. }
  16109. }
  16110. raw_printf(pArg->out, "---------------------------\n");
  16111. #endif
  16112. }
  16113. /*
  16114. ** Parameter azArray points to a zero-terminated array of strings. zStr
  16115. ** points to a single nul-terminated string. Return non-zero if zStr
  16116. ** is equal, according to strcmp(), to any of the strings in the array.
  16117. ** Otherwise, return zero.
  16118. */
  16119. static int str_in_array(const char *zStr, const char **azArray){
  16120. int i;
  16121. for(i=0; azArray[i]; i++){
  16122. if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
  16123. }
  16124. return 0;
  16125. }
  16126. /*
  16127. ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
  16128. ** and populate the ShellState.aiIndent[] array with the number of
  16129. ** spaces each opcode should be indented before it is output.
  16130. **
  16131. ** The indenting rules are:
  16132. **
  16133. ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
  16134. ** all opcodes that occur between the p2 jump destination and the opcode
  16135. ** itself by 2 spaces.
  16136. **
  16137. ** * Do the previous for "Return" instructions for when P2 is positive.
  16138. ** See tag-20220407a in wherecode.c and vdbe.c.
  16139. **
  16140. ** * For each "Goto", if the jump destination is earlier in the program
  16141. ** and ends on one of:
  16142. ** Yield SeekGt SeekLt RowSetRead Rewind
  16143. ** or if the P1 parameter is one instead of zero,
  16144. ** then indent all opcodes between the earlier instruction
  16145. ** and "Goto" by 2 spaces.
  16146. */
  16147. static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
  16148. const char *zSql; /* The text of the SQL statement */
  16149. const char *z; /* Used to check if this is an EXPLAIN */
  16150. int *abYield = 0; /* True if op is an OP_Yield */
  16151. int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
  16152. int iOp; /* Index of operation in p->aiIndent[] */
  16153. const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
  16154. "Return", 0 };
  16155. const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
  16156. "Rewind", 0 };
  16157. const char *azGoto[] = { "Goto", 0 };
  16158. /* Try to figure out if this is really an EXPLAIN statement. If this
  16159. ** cannot be verified, return early. */
  16160. if( sqlite3_column_count(pSql)!=8 ){
  16161. p->cMode = p->mode;
  16162. return;
  16163. }
  16164. zSql = sqlite3_sql(pSql);
  16165. if( zSql==0 ) return;
  16166. for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
  16167. if( sqlite3_strnicmp(z, "explain", 7) ){
  16168. p->cMode = p->mode;
  16169. return;
  16170. }
  16171. for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
  16172. int i;
  16173. int iAddr = sqlite3_column_int(pSql, 0);
  16174. const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
  16175. /* Set p2 to the P2 field of the current opcode. Then, assuming that
  16176. ** p2 is an instruction address, set variable p2op to the index of that
  16177. ** instruction in the aiIndent[] array. p2 and p2op may be different if
  16178. ** the current instruction is part of a sub-program generated by an
  16179. ** SQL trigger or foreign key. */
  16180. int p2 = sqlite3_column_int(pSql, 3);
  16181. int p2op = (p2 + (iOp-iAddr));
  16182. /* Grow the p->aiIndent array as required */
  16183. if( iOp>=nAlloc ){
  16184. if( iOp==0 ){
  16185. /* Do further verfication that this is explain output. Abort if
  16186. ** it is not */
  16187. static const char *explainCols[] = {
  16188. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
  16189. int jj;
  16190. for(jj=0; jj<ArraySize(explainCols); jj++){
  16191. if( cli_strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
  16192. p->cMode = p->mode;
  16193. sqlite3_reset(pSql);
  16194. return;
  16195. }
  16196. }
  16197. }
  16198. nAlloc += 100;
  16199. p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
  16200. shell_check_oom(p->aiIndent);
  16201. abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
  16202. shell_check_oom(abYield);
  16203. }
  16204. abYield[iOp] = str_in_array(zOp, azYield);
  16205. p->aiIndent[iOp] = 0;
  16206. p->nIndent = iOp+1;
  16207. if( str_in_array(zOp, azNext) && p2op>0 ){
  16208. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  16209. }
  16210. if( str_in_array(zOp, azGoto) && p2op<p->nIndent
  16211. && (abYield[p2op] || sqlite3_column_int(pSql, 2))
  16212. ){
  16213. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  16214. }
  16215. }
  16216. p->iIndent = 0;
  16217. sqlite3_free(abYield);
  16218. sqlite3_reset(pSql);
  16219. }
  16220. /*
  16221. ** Free the array allocated by explain_data_prepare().
  16222. */
  16223. static void explain_data_delete(ShellState *p){
  16224. sqlite3_free(p->aiIndent);
  16225. p->aiIndent = 0;
  16226. p->nIndent = 0;
  16227. p->iIndent = 0;
  16228. }
  16229. /*
  16230. ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
  16231. */
  16232. static unsigned int savedSelectTrace;
  16233. static unsigned int savedWhereTrace;
  16234. static void disable_debug_trace_modes(void){
  16235. unsigned int zero = 0;
  16236. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
  16237. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
  16238. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
  16239. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
  16240. }
  16241. static void restore_debug_trace_modes(void){
  16242. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
  16243. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
  16244. }
  16245. /* Create the TEMP table used to store parameter bindings */
  16246. static void bind_table_init(ShellState *p){
  16247. int wrSchema = 0;
  16248. int defensiveMode = 0;
  16249. sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
  16250. sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
  16251. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
  16252. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
  16253. sqlite3_exec(p->db,
  16254. "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
  16255. " key TEXT PRIMARY KEY,\n"
  16256. " value\n"
  16257. ") WITHOUT ROWID;",
  16258. 0, 0, 0);
  16259. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
  16260. sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
  16261. }
  16262. /*
  16263. ** Bind parameters on a prepared statement.
  16264. **
  16265. ** Parameter bindings are taken from a TEMP table of the form:
  16266. **
  16267. ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
  16268. ** WITHOUT ROWID;
  16269. **
  16270. ** No bindings occur if this table does not exist. The name of the table
  16271. ** begins with "sqlite_" so that it will not collide with ordinary application
  16272. ** tables. The table must be in the TEMP schema.
  16273. */
  16274. static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
  16275. int nVar;
  16276. int i;
  16277. int rc;
  16278. sqlite3_stmt *pQ = 0;
  16279. nVar = sqlite3_bind_parameter_count(pStmt);
  16280. if( nVar==0 ) return; /* Nothing to do */
  16281. if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
  16282. "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
  16283. return; /* Parameter table does not exist */
  16284. }
  16285. rc = sqlite3_prepare_v2(pArg->db,
  16286. "SELECT value FROM temp.sqlite_parameters"
  16287. " WHERE key=?1", -1, &pQ, 0);
  16288. if( rc || pQ==0 ) return;
  16289. for(i=1; i<=nVar; i++){
  16290. char zNum[30];
  16291. const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
  16292. if( zVar==0 ){
  16293. sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
  16294. zVar = zNum;
  16295. }
  16296. sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
  16297. if( sqlite3_step(pQ)==SQLITE_ROW ){
  16298. sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
  16299. }else{
  16300. sqlite3_bind_null(pStmt, i);
  16301. }
  16302. sqlite3_reset(pQ);
  16303. }
  16304. sqlite3_finalize(pQ);
  16305. }
  16306. /*
  16307. ** UTF8 box-drawing characters. Imagine box lines like this:
  16308. **
  16309. ** 1
  16310. ** |
  16311. ** 4 --+-- 2
  16312. ** |
  16313. ** 3
  16314. **
  16315. ** Each box characters has between 2 and 4 of the lines leading from
  16316. ** the center. The characters are here identified by the numbers of
  16317. ** their corresponding lines.
  16318. */
  16319. #define BOX_24 "\342\224\200" /* U+2500 --- */
  16320. #define BOX_13 "\342\224\202" /* U+2502 | */
  16321. #define BOX_23 "\342\224\214" /* U+250c ,- */
  16322. #define BOX_34 "\342\224\220" /* U+2510 -, */
  16323. #define BOX_12 "\342\224\224" /* U+2514 '- */
  16324. #define BOX_14 "\342\224\230" /* U+2518 -' */
  16325. #define BOX_123 "\342\224\234" /* U+251c |- */
  16326. #define BOX_134 "\342\224\244" /* U+2524 -| */
  16327. #define BOX_234 "\342\224\254" /* U+252c -,- */
  16328. #define BOX_124 "\342\224\264" /* U+2534 -'- */
  16329. #define BOX_1234 "\342\224\274" /* U+253c -|- */
  16330. /* Draw horizontal line N characters long using unicode box
  16331. ** characters
  16332. */
  16333. static void print_box_line(FILE *out, int N){
  16334. const char zDash[] =
  16335. BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
  16336. BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
  16337. const int nDash = sizeof(zDash) - 1;
  16338. N *= 3;
  16339. while( N>nDash ){
  16340. utf8_printf(out, zDash);
  16341. N -= nDash;
  16342. }
  16343. utf8_printf(out, "%.*s", N, zDash);
  16344. }
  16345. /*
  16346. ** Draw a horizontal separator for a MODE_Box table.
  16347. */
  16348. static void print_box_row_separator(
  16349. ShellState *p,
  16350. int nArg,
  16351. const char *zSep1,
  16352. const char *zSep2,
  16353. const char *zSep3
  16354. ){
  16355. int i;
  16356. if( nArg>0 ){
  16357. utf8_printf(p->out, "%s", zSep1);
  16358. print_box_line(p->out, p->actualWidth[0]+2);
  16359. for(i=1; i<nArg; i++){
  16360. utf8_printf(p->out, "%s", zSep2);
  16361. print_box_line(p->out, p->actualWidth[i]+2);
  16362. }
  16363. utf8_printf(p->out, "%s", zSep3);
  16364. }
  16365. fputs("\n", p->out);
  16366. }
  16367. /*
  16368. ** z[] is a line of text that is to be displayed the .mode box or table or
  16369. ** similar tabular formats. z[] might contain control characters such
  16370. ** as \n, \t, \f, or \r.
  16371. **
  16372. ** Compute characters to display on the first line of z[]. Stop at the
  16373. ** first \r, \n, or \f. Expand \t into spaces. Return a copy (obtained
  16374. ** from malloc()) of that first line, which caller should free sometime.
  16375. ** Write anything to display on the next line into *pzTail. If this is
  16376. ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
  16377. */
  16378. static char *translateForDisplayAndDup(
  16379. const unsigned char *z, /* Input text to be transformed */
  16380. const unsigned char **pzTail, /* OUT: Tail of the input for next line */
  16381. int mxWidth, /* Max width. 0 means no limit */
  16382. u8 bWordWrap /* If true, avoid breaking mid-word */
  16383. ){
  16384. int i; /* Input bytes consumed */
  16385. int j; /* Output bytes generated */
  16386. int k; /* Input bytes to be displayed */
  16387. int n; /* Output column number */
  16388. unsigned char *zOut; /* Output text */
  16389. if( z==0 ){
  16390. *pzTail = 0;
  16391. return 0;
  16392. }
  16393. if( mxWidth<0 ) mxWidth = -mxWidth;
  16394. if( mxWidth==0 ) mxWidth = 1000000;
  16395. i = j = n = 0;
  16396. while( n<mxWidth ){
  16397. if( z[i]>=' ' ){
  16398. n++;
  16399. do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
  16400. continue;
  16401. }
  16402. if( z[i]=='\t' ){
  16403. do{
  16404. n++;
  16405. j++;
  16406. }while( (n&7)!=0 && n<mxWidth );
  16407. i++;
  16408. continue;
  16409. }
  16410. break;
  16411. }
  16412. if( n>=mxWidth && bWordWrap ){
  16413. /* Perhaps try to back up to a better place to break the line */
  16414. for(k=i; k>i/2; k--){
  16415. if( isspace(z[k-1]) ) break;
  16416. }
  16417. if( k<=i/2 ){
  16418. for(k=i; k>i/2; k--){
  16419. if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
  16420. }
  16421. }
  16422. if( k<=i/2 ){
  16423. k = i;
  16424. }else{
  16425. i = k;
  16426. while( z[i]==' ' ) i++;
  16427. }
  16428. }else{
  16429. k = i;
  16430. }
  16431. if( n>=mxWidth && z[i]>=' ' ){
  16432. *pzTail = &z[i];
  16433. }else if( z[i]=='\r' && z[i+1]=='\n' ){
  16434. *pzTail = z[i+2] ? &z[i+2] : 0;
  16435. }else if( z[i]==0 || z[i+1]==0 ){
  16436. *pzTail = 0;
  16437. }else{
  16438. *pzTail = &z[i+1];
  16439. }
  16440. zOut = malloc( j+1 );
  16441. shell_check_oom(zOut);
  16442. i = j = n = 0;
  16443. while( i<k ){
  16444. if( z[i]>=' ' ){
  16445. n++;
  16446. do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
  16447. continue;
  16448. }
  16449. if( z[i]=='\t' ){
  16450. do{
  16451. n++;
  16452. zOut[j++] = ' ';
  16453. }while( (n&7)!=0 && n<mxWidth );
  16454. i++;
  16455. continue;
  16456. }
  16457. break;
  16458. }
  16459. zOut[j] = 0;
  16460. return (char*)zOut;
  16461. }
  16462. /* Extract the value of the i-th current column for pStmt as an SQL literal
  16463. ** value. Memory is obtained from sqlite3_malloc64() and must be freed by
  16464. ** the caller.
  16465. */
  16466. static char *quoted_column(sqlite3_stmt *pStmt, int i){
  16467. switch( sqlite3_column_type(pStmt, i) ){
  16468. case SQLITE_NULL: {
  16469. return sqlite3_mprintf("NULL");
  16470. }
  16471. case SQLITE_INTEGER:
  16472. case SQLITE_FLOAT: {
  16473. return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
  16474. }
  16475. case SQLITE_TEXT: {
  16476. return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
  16477. }
  16478. case SQLITE_BLOB: {
  16479. int j;
  16480. sqlite3_str *pStr = sqlite3_str_new(0);
  16481. const unsigned char *a = sqlite3_column_blob(pStmt,i);
  16482. int n = sqlite3_column_bytes(pStmt,i);
  16483. sqlite3_str_append(pStr, "x'", 2);
  16484. for(j=0; j<n; j++){
  16485. sqlite3_str_appendf(pStr, "%02x", a[j]);
  16486. }
  16487. sqlite3_str_append(pStr, "'", 1);
  16488. return sqlite3_str_finish(pStr);
  16489. }
  16490. }
  16491. return 0; /* Not reached */
  16492. }
  16493. /*
  16494. ** Run a prepared statement and output the result in one of the
  16495. ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
  16496. ** or MODE_Box.
  16497. **
  16498. ** This is different from ordinary exec_prepared_stmt() in that
  16499. ** it has to run the entire query and gather the results into memory
  16500. ** first, in order to determine column widths, before providing
  16501. ** any output.
  16502. */
  16503. static void exec_prepared_stmt_columnar(
  16504. ShellState *p, /* Pointer to ShellState */
  16505. sqlite3_stmt *pStmt /* Statment to run */
  16506. ){
  16507. sqlite3_int64 nRow = 0;
  16508. int nColumn = 0;
  16509. char **azData = 0;
  16510. sqlite3_int64 nAlloc = 0;
  16511. char *abRowDiv = 0;
  16512. const unsigned char *uz;
  16513. const char *z;
  16514. char **azQuoted = 0;
  16515. int rc;
  16516. sqlite3_int64 i, nData;
  16517. int j, nTotal, w, n;
  16518. const char *colSep = 0;
  16519. const char *rowSep = 0;
  16520. const unsigned char **azNextLine = 0;
  16521. int bNextLine = 0;
  16522. int bMultiLineRowExists = 0;
  16523. int bw = p->cmOpts.bWordWrap;
  16524. const char *zEmpty = "";
  16525. const char *zShowNull = p->nullValue;
  16526. rc = sqlite3_step(pStmt);
  16527. if( rc!=SQLITE_ROW ) return;
  16528. nColumn = sqlite3_column_count(pStmt);
  16529. nAlloc = nColumn*4;
  16530. if( nAlloc<=0 ) nAlloc = 1;
  16531. azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
  16532. shell_check_oom(azData);
  16533. azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
  16534. shell_check_oom((void*)azNextLine);
  16535. memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
  16536. if( p->cmOpts.bQuote ){
  16537. azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
  16538. shell_check_oom(azQuoted);
  16539. memset(azQuoted, 0, nColumn*sizeof(char*) );
  16540. }
  16541. abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
  16542. shell_check_oom(abRowDiv);
  16543. if( nColumn>p->nWidth ){
  16544. p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
  16545. shell_check_oom(p->colWidth);
  16546. for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
  16547. p->nWidth = nColumn;
  16548. p->actualWidth = &p->colWidth[nColumn];
  16549. }
  16550. memset(p->actualWidth, 0, nColumn*sizeof(int));
  16551. for(i=0; i<nColumn; i++){
  16552. w = p->colWidth[i];
  16553. if( w<0 ) w = -w;
  16554. p->actualWidth[i] = w;
  16555. }
  16556. for(i=0; i<nColumn; i++){
  16557. const unsigned char *zNotUsed;
  16558. int wx = p->colWidth[i];
  16559. if( wx==0 ){
  16560. wx = p->cmOpts.iWrap;
  16561. }
  16562. if( wx<0 ) wx = -wx;
  16563. uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
  16564. azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
  16565. }
  16566. do{
  16567. int useNextLine = bNextLine;
  16568. bNextLine = 0;
  16569. if( (nRow+2)*nColumn >= nAlloc ){
  16570. nAlloc *= 2;
  16571. azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
  16572. shell_check_oom(azData);
  16573. abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
  16574. shell_check_oom(abRowDiv);
  16575. }
  16576. abRowDiv[nRow] = 1;
  16577. nRow++;
  16578. for(i=0; i<nColumn; i++){
  16579. int wx = p->colWidth[i];
  16580. if( wx==0 ){
  16581. wx = p->cmOpts.iWrap;
  16582. }
  16583. if( wx<0 ) wx = -wx;
  16584. if( useNextLine ){
  16585. uz = azNextLine[i];
  16586. if( uz==0 ) uz = (u8*)zEmpty;
  16587. }else if( p->cmOpts.bQuote ){
  16588. sqlite3_free(azQuoted[i]);
  16589. azQuoted[i] = quoted_column(pStmt,i);
  16590. uz = (const unsigned char*)azQuoted[i];
  16591. }else{
  16592. uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
  16593. if( uz==0 ) uz = (u8*)zShowNull;
  16594. }
  16595. azData[nRow*nColumn + i]
  16596. = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
  16597. if( azNextLine[i] ){
  16598. bNextLine = 1;
  16599. abRowDiv[nRow-1] = 0;
  16600. bMultiLineRowExists = 1;
  16601. }
  16602. }
  16603. }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
  16604. nTotal = nColumn*(nRow+1);
  16605. for(i=0; i<nTotal; i++){
  16606. z = azData[i];
  16607. if( z==0 ) z = (char*)zEmpty;
  16608. n = strlenChar(z);
  16609. j = i%nColumn;
  16610. if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
  16611. }
  16612. if( seenInterrupt ) goto columnar_end;
  16613. if( nColumn==0 ) goto columnar_end;
  16614. switch( p->cMode ){
  16615. case MODE_Column: {
  16616. colSep = " ";
  16617. rowSep = "\n";
  16618. if( p->showHeader ){
  16619. for(i=0; i<nColumn; i++){
  16620. w = p->actualWidth[i];
  16621. if( p->colWidth[i]<0 ) w = -w;
  16622. utf8_width_print(p->out, w, azData[i]);
  16623. fputs(i==nColumn-1?"\n":" ", p->out);
  16624. }
  16625. for(i=0; i<nColumn; i++){
  16626. print_dashes(p->out, p->actualWidth[i]);
  16627. fputs(i==nColumn-1?"\n":" ", p->out);
  16628. }
  16629. }
  16630. break;
  16631. }
  16632. case MODE_Table: {
  16633. colSep = " | ";
  16634. rowSep = " |\n";
  16635. print_row_separator(p, nColumn, "+");
  16636. fputs("| ", p->out);
  16637. for(i=0; i<nColumn; i++){
  16638. w = p->actualWidth[i];
  16639. n = strlenChar(azData[i]);
  16640. utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
  16641. fputs(i==nColumn-1?" |\n":" | ", p->out);
  16642. }
  16643. print_row_separator(p, nColumn, "+");
  16644. break;
  16645. }
  16646. case MODE_Markdown: {
  16647. colSep = " | ";
  16648. rowSep = " |\n";
  16649. fputs("| ", p->out);
  16650. for(i=0; i<nColumn; i++){
  16651. w = p->actualWidth[i];
  16652. n = strlenChar(azData[i]);
  16653. utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
  16654. fputs(i==nColumn-1?" |\n":" | ", p->out);
  16655. }
  16656. print_row_separator(p, nColumn, "|");
  16657. break;
  16658. }
  16659. case MODE_Box: {
  16660. colSep = " " BOX_13 " ";
  16661. rowSep = " " BOX_13 "\n";
  16662. print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
  16663. utf8_printf(p->out, BOX_13 " ");
  16664. for(i=0; i<nColumn; i++){
  16665. w = p->actualWidth[i];
  16666. n = strlenChar(azData[i]);
  16667. utf8_printf(p->out, "%*s%s%*s%s",
  16668. (w-n)/2, "", azData[i], (w-n+1)/2, "",
  16669. i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
  16670. }
  16671. print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
  16672. break;
  16673. }
  16674. }
  16675. for(i=nColumn, j=0; i<nTotal; i++, j++){
  16676. if( j==0 && p->cMode!=MODE_Column ){
  16677. utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
  16678. }
  16679. z = azData[i];
  16680. if( z==0 ) z = p->nullValue;
  16681. w = p->actualWidth[j];
  16682. if( p->colWidth[j]<0 ) w = -w;
  16683. utf8_width_print(p->out, w, z);
  16684. if( j==nColumn-1 ){
  16685. utf8_printf(p->out, "%s", rowSep);
  16686. if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
  16687. if( p->cMode==MODE_Table ){
  16688. print_row_separator(p, nColumn, "+");
  16689. }else if( p->cMode==MODE_Box ){
  16690. print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
  16691. }else if( p->cMode==MODE_Column ){
  16692. raw_printf(p->out, "\n");
  16693. }
  16694. }
  16695. j = -1;
  16696. if( seenInterrupt ) goto columnar_end;
  16697. }else{
  16698. utf8_printf(p->out, "%s", colSep);
  16699. }
  16700. }
  16701. if( p->cMode==MODE_Table ){
  16702. print_row_separator(p, nColumn, "+");
  16703. }else if( p->cMode==MODE_Box ){
  16704. print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
  16705. }
  16706. columnar_end:
  16707. if( seenInterrupt ){
  16708. utf8_printf(p->out, "Interrupt\n");
  16709. }
  16710. nData = (nRow+1)*nColumn;
  16711. for(i=0; i<nData; i++){
  16712. z = azData[i];
  16713. if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
  16714. }
  16715. sqlite3_free(azData);
  16716. sqlite3_free((void*)azNextLine);
  16717. sqlite3_free(abRowDiv);
  16718. if( azQuoted ){
  16719. for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
  16720. sqlite3_free(azQuoted);
  16721. }
  16722. }
  16723. /*
  16724. ** Run a prepared statement
  16725. */
  16726. static void exec_prepared_stmt(
  16727. ShellState *pArg, /* Pointer to ShellState */
  16728. sqlite3_stmt *pStmt /* Statment to run */
  16729. ){
  16730. int rc;
  16731. sqlite3_uint64 nRow = 0;
  16732. if( pArg->cMode==MODE_Column
  16733. || pArg->cMode==MODE_Table
  16734. || pArg->cMode==MODE_Box
  16735. || pArg->cMode==MODE_Markdown
  16736. ){
  16737. exec_prepared_stmt_columnar(pArg, pStmt);
  16738. return;
  16739. }
  16740. /* perform the first step. this will tell us if we
  16741. ** have a result set or not and how wide it is.
  16742. */
  16743. rc = sqlite3_step(pStmt);
  16744. /* if we have a result set... */
  16745. if( SQLITE_ROW == rc ){
  16746. /* allocate space for col name ptr, value ptr, and type */
  16747. int nCol = sqlite3_column_count(pStmt);
  16748. void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
  16749. if( !pData ){
  16750. shell_out_of_memory();
  16751. }else{
  16752. char **azCols = (char **)pData; /* Names of result columns */
  16753. char **azVals = &azCols[nCol]; /* Results */
  16754. int *aiTypes = (int *)&azVals[nCol]; /* Result types */
  16755. int i, x;
  16756. assert(sizeof(int) <= sizeof(char *));
  16757. /* save off ptrs to column names */
  16758. for(i=0; i<nCol; i++){
  16759. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  16760. }
  16761. do{
  16762. nRow++;
  16763. /* extract the data and data types */
  16764. for(i=0; i<nCol; i++){
  16765. aiTypes[i] = x = sqlite3_column_type(pStmt, i);
  16766. if( x==SQLITE_BLOB
  16767. && pArg
  16768. && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
  16769. ){
  16770. azVals[i] = "";
  16771. }else{
  16772. azVals[i] = (char*)sqlite3_column_text(pStmt, i);
  16773. }
  16774. if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
  16775. rc = SQLITE_NOMEM;
  16776. break; /* from for */
  16777. }
  16778. } /* end for */
  16779. /* if data and types extracted successfully... */
  16780. if( SQLITE_ROW == rc ){
  16781. /* call the supplied callback with the result row data */
  16782. if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
  16783. rc = SQLITE_ABORT;
  16784. }else{
  16785. rc = sqlite3_step(pStmt);
  16786. }
  16787. }
  16788. } while( SQLITE_ROW == rc );
  16789. sqlite3_free(pData);
  16790. if( pArg->cMode==MODE_Json ){
  16791. fputs("]\n", pArg->out);
  16792. }else if( pArg->cMode==MODE_Count ){
  16793. char zBuf[200];
  16794. sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
  16795. nRow, nRow!=1 ? "s" : "");
  16796. printf("%s", zBuf);
  16797. }
  16798. }
  16799. }
  16800. }
  16801. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16802. /*
  16803. ** This function is called to process SQL if the previous shell command
  16804. ** was ".expert". It passes the SQL in the second argument directly to
  16805. ** the sqlite3expert object.
  16806. **
  16807. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
  16808. ** code. In this case, (*pzErr) may be set to point to a buffer containing
  16809. ** an English language error message. It is the responsibility of the
  16810. ** caller to eventually free this buffer using sqlite3_free().
  16811. */
  16812. static int expertHandleSQL(
  16813. ShellState *pState,
  16814. const char *zSql,
  16815. char **pzErr
  16816. ){
  16817. assert( pState->expert.pExpert );
  16818. assert( pzErr==0 || *pzErr==0 );
  16819. return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
  16820. }
  16821. /*
  16822. ** This function is called either to silently clean up the object
  16823. ** created by the ".expert" command (if bCancel==1), or to generate a
  16824. ** report from it and then clean it up (if bCancel==0).
  16825. **
  16826. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
  16827. ** code. In this case, (*pzErr) may be set to point to a buffer containing
  16828. ** an English language error message. It is the responsibility of the
  16829. ** caller to eventually free this buffer using sqlite3_free().
  16830. */
  16831. static int expertFinish(
  16832. ShellState *pState,
  16833. int bCancel,
  16834. char **pzErr
  16835. ){
  16836. int rc = SQLITE_OK;
  16837. sqlite3expert *p = pState->expert.pExpert;
  16838. assert( p );
  16839. assert( bCancel || pzErr==0 || *pzErr==0 );
  16840. if( bCancel==0 ){
  16841. FILE *out = pState->out;
  16842. int bVerbose = pState->expert.bVerbose;
  16843. rc = sqlite3_expert_analyze(p, pzErr);
  16844. if( rc==SQLITE_OK ){
  16845. int nQuery = sqlite3_expert_count(p);
  16846. int i;
  16847. if( bVerbose ){
  16848. const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
  16849. raw_printf(out, "-- Candidates -----------------------------\n");
  16850. raw_printf(out, "%s\n", zCand);
  16851. }
  16852. for(i=0; i<nQuery; i++){
  16853. const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
  16854. const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
  16855. const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
  16856. if( zIdx==0 ) zIdx = "(no new indexes)\n";
  16857. if( bVerbose ){
  16858. raw_printf(out, "-- Query %d --------------------------------\n",i+1);
  16859. raw_printf(out, "%s\n\n", zSql);
  16860. }
  16861. raw_printf(out, "%s\n", zIdx);
  16862. raw_printf(out, "%s\n", zEQP);
  16863. }
  16864. }
  16865. }
  16866. sqlite3_expert_destroy(p);
  16867. pState->expert.pExpert = 0;
  16868. return rc;
  16869. }
  16870. /*
  16871. ** Implementation of ".expert" dot command.
  16872. */
  16873. static int expertDotCommand(
  16874. ShellState *pState, /* Current shell tool state */
  16875. char **azArg, /* Array of arguments passed to dot command */
  16876. int nArg /* Number of entries in azArg[] */
  16877. ){
  16878. int rc = SQLITE_OK;
  16879. char *zErr = 0;
  16880. int i;
  16881. int iSample = 0;
  16882. assert( pState->expert.pExpert==0 );
  16883. memset(&pState->expert, 0, sizeof(ExpertInfo));
  16884. for(i=1; rc==SQLITE_OK && i<nArg; i++){
  16885. char *z = azArg[i];
  16886. int n;
  16887. if( z[0]=='-' && z[1]=='-' ) z++;
  16888. n = strlen30(z);
  16889. if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
  16890. pState->expert.bVerbose = 1;
  16891. }
  16892. else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
  16893. if( i==(nArg-1) ){
  16894. raw_printf(stderr, "option requires an argument: %s\n", z);
  16895. rc = SQLITE_ERROR;
  16896. }else{
  16897. iSample = (int)integerValue(azArg[++i]);
  16898. if( iSample<0 || iSample>100 ){
  16899. raw_printf(stderr, "value out of range: %s\n", azArg[i]);
  16900. rc = SQLITE_ERROR;
  16901. }
  16902. }
  16903. }
  16904. else{
  16905. raw_printf(stderr, "unknown option: %s\n", z);
  16906. rc = SQLITE_ERROR;
  16907. }
  16908. }
  16909. if( rc==SQLITE_OK ){
  16910. pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
  16911. if( pState->expert.pExpert==0 ){
  16912. raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
  16913. rc = SQLITE_ERROR;
  16914. }else{
  16915. sqlite3_expert_config(
  16916. pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
  16917. );
  16918. }
  16919. }
  16920. sqlite3_free(zErr);
  16921. return rc;
  16922. }
  16923. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  16924. /*
  16925. ** Execute a statement or set of statements. Print
  16926. ** any result rows/columns depending on the current mode
  16927. ** set via the supplied callback.
  16928. **
  16929. ** This is very similar to SQLite's built-in sqlite3_exec()
  16930. ** function except it takes a slightly different callback
  16931. ** and callback data argument.
  16932. */
  16933. static int shell_exec(
  16934. ShellState *pArg, /* Pointer to ShellState */
  16935. const char *zSql, /* SQL to be evaluated */
  16936. char **pzErrMsg /* Error msg written here */
  16937. ){
  16938. sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
  16939. int rc = SQLITE_OK; /* Return Code */
  16940. int rc2;
  16941. const char *zLeftover; /* Tail of unprocessed SQL */
  16942. sqlite3 *db = pArg->db;
  16943. if( pzErrMsg ){
  16944. *pzErrMsg = NULL;
  16945. }
  16946. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16947. if( pArg->expert.pExpert ){
  16948. rc = expertHandleSQL(pArg, zSql, pzErrMsg);
  16949. return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
  16950. }
  16951. #endif
  16952. while( zSql[0] && (SQLITE_OK == rc) ){
  16953. static const char *zStmtSql;
  16954. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  16955. if( SQLITE_OK != rc ){
  16956. if( pzErrMsg ){
  16957. *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
  16958. }
  16959. }else{
  16960. if( !pStmt ){
  16961. /* this happens for a comment or white-space */
  16962. zSql = zLeftover;
  16963. while( IsSpace(zSql[0]) ) zSql++;
  16964. continue;
  16965. }
  16966. zStmtSql = sqlite3_sql(pStmt);
  16967. if( zStmtSql==0 ) zStmtSql = "";
  16968. while( IsSpace(zStmtSql[0]) ) zStmtSql++;
  16969. /* save off the prepared statment handle and reset row count */
  16970. if( pArg ){
  16971. pArg->pStmt = pStmt;
  16972. pArg->cnt = 0;
  16973. }
  16974. /* Show the EXPLAIN QUERY PLAN if .eqp is on */
  16975. if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
  16976. sqlite3_stmt *pExplain;
  16977. char *zEQP;
  16978. int triggerEQP = 0;
  16979. disable_debug_trace_modes();
  16980. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
  16981. if( pArg->autoEQP>=AUTOEQP_trigger ){
  16982. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
  16983. }
  16984. zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
  16985. shell_check_oom(zEQP);
  16986. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  16987. if( rc==SQLITE_OK ){
  16988. while( sqlite3_step(pExplain)==SQLITE_ROW ){
  16989. const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
  16990. int iEqpId = sqlite3_column_int(pExplain, 0);
  16991. int iParentId = sqlite3_column_int(pExplain, 1);
  16992. if( zEQPLine==0 ) zEQPLine = "";
  16993. if( zEQPLine[0]=='-' ) eqp_render(pArg);
  16994. eqp_append(pArg, iEqpId, iParentId, zEQPLine);
  16995. }
  16996. eqp_render(pArg);
  16997. }
  16998. sqlite3_finalize(pExplain);
  16999. sqlite3_free(zEQP);
  17000. if( pArg->autoEQP>=AUTOEQP_full ){
  17001. /* Also do an EXPLAIN for ".eqp full" mode */
  17002. zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
  17003. shell_check_oom(zEQP);
  17004. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  17005. if( rc==SQLITE_OK ){
  17006. pArg->cMode = MODE_Explain;
  17007. explain_data_prepare(pArg, pExplain);
  17008. exec_prepared_stmt(pArg, pExplain);
  17009. explain_data_delete(pArg);
  17010. }
  17011. sqlite3_finalize(pExplain);
  17012. sqlite3_free(zEQP);
  17013. }
  17014. if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
  17015. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
  17016. /* Reprepare pStmt before reactiving trace modes */
  17017. sqlite3_finalize(pStmt);
  17018. sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  17019. if( pArg ) pArg->pStmt = pStmt;
  17020. }
  17021. restore_debug_trace_modes();
  17022. }
  17023. if( pArg ){
  17024. pArg->cMode = pArg->mode;
  17025. if( pArg->autoExplain ){
  17026. if( sqlite3_stmt_isexplain(pStmt)==1 ){
  17027. pArg->cMode = MODE_Explain;
  17028. }
  17029. if( sqlite3_stmt_isexplain(pStmt)==2 ){
  17030. pArg->cMode = MODE_EQP;
  17031. }
  17032. }
  17033. /* If the shell is currently in ".explain" mode, gather the extra
  17034. ** data required to add indents to the output.*/
  17035. if( pArg->cMode==MODE_Explain ){
  17036. explain_data_prepare(pArg, pStmt);
  17037. }
  17038. }
  17039. bind_prepared_stmt(pArg, pStmt);
  17040. exec_prepared_stmt(pArg, pStmt);
  17041. explain_data_delete(pArg);
  17042. eqp_render(pArg);
  17043. /* print usage stats if stats on */
  17044. if( pArg && pArg->statsOn ){
  17045. display_stats(db, pArg, 0);
  17046. }
  17047. /* print loop-counters if required */
  17048. if( pArg && pArg->scanstatsOn ){
  17049. display_scanstats(db, pArg);
  17050. }
  17051. /* Finalize the statement just executed. If this fails, save a
  17052. ** copy of the error message. Otherwise, set zSql to point to the
  17053. ** next statement to execute. */
  17054. rc2 = sqlite3_finalize(pStmt);
  17055. if( rc!=SQLITE_NOMEM ) rc = rc2;
  17056. if( rc==SQLITE_OK ){
  17057. zSql = zLeftover;
  17058. while( IsSpace(zSql[0]) ) zSql++;
  17059. }else if( pzErrMsg ){
  17060. *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
  17061. }
  17062. /* clear saved stmt handle */
  17063. if( pArg ){
  17064. pArg->pStmt = NULL;
  17065. }
  17066. }
  17067. } /* end while */
  17068. return rc;
  17069. }
  17070. /*
  17071. ** Release memory previously allocated by tableColumnList().
  17072. */
  17073. static void freeColumnList(char **azCol){
  17074. int i;
  17075. for(i=1; azCol[i]; i++){
  17076. sqlite3_free(azCol[i]);
  17077. }
  17078. /* azCol[0] is a static string */
  17079. sqlite3_free(azCol);
  17080. }
  17081. /*
  17082. ** Return a list of pointers to strings which are the names of all
  17083. ** columns in table zTab. The memory to hold the names is dynamically
  17084. ** allocated and must be released by the caller using a subsequent call
  17085. ** to freeColumnList().
  17086. **
  17087. ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
  17088. ** value that needs to be preserved, then azCol[0] is filled in with the
  17089. ** name of the rowid column.
  17090. **
  17091. ** The first regular column in the table is azCol[1]. The list is terminated
  17092. ** by an entry with azCol[i]==0.
  17093. */
  17094. static char **tableColumnList(ShellState *p, const char *zTab){
  17095. char **azCol = 0;
  17096. sqlite3_stmt *pStmt;
  17097. char *zSql;
  17098. int nCol = 0;
  17099. int nAlloc = 0;
  17100. int nPK = 0; /* Number of PRIMARY KEY columns seen */
  17101. int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
  17102. int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
  17103. int rc;
  17104. zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
  17105. shell_check_oom(zSql);
  17106. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  17107. sqlite3_free(zSql);
  17108. if( rc ) return 0;
  17109. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  17110. if( nCol>=nAlloc-2 ){
  17111. nAlloc = nAlloc*2 + nCol + 10;
  17112. azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
  17113. shell_check_oom(azCol);
  17114. }
  17115. azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
  17116. shell_check_oom(azCol[nCol]);
  17117. if( sqlite3_column_int(pStmt, 5) ){
  17118. nPK++;
  17119. if( nPK==1
  17120. && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
  17121. "INTEGER")==0
  17122. ){
  17123. isIPK = 1;
  17124. }else{
  17125. isIPK = 0;
  17126. }
  17127. }
  17128. }
  17129. sqlite3_finalize(pStmt);
  17130. if( azCol==0 ) return 0;
  17131. azCol[0] = 0;
  17132. azCol[nCol+1] = 0;
  17133. /* The decision of whether or not a rowid really needs to be preserved
  17134. ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
  17135. ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
  17136. ** rowids on tables where the rowid is inaccessible because there are other
  17137. ** columns in the table named "rowid", "_rowid_", and "oid".
  17138. */
  17139. if( preserveRowid && isIPK ){
  17140. /* If a single PRIMARY KEY column with type INTEGER was seen, then it
  17141. ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
  17142. ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
  17143. ** ROWID aliases. To distinguish these cases, check to see if
  17144. ** there is a "pk" entry in "PRAGMA index_list". There will be
  17145. ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
  17146. */
  17147. zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
  17148. " WHERE origin='pk'", zTab);
  17149. shell_check_oom(zSql);
  17150. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  17151. sqlite3_free(zSql);
  17152. if( rc ){
  17153. freeColumnList(azCol);
  17154. return 0;
  17155. }
  17156. rc = sqlite3_step(pStmt);
  17157. sqlite3_finalize(pStmt);
  17158. preserveRowid = rc==SQLITE_ROW;
  17159. }
  17160. if( preserveRowid ){
  17161. /* Only preserve the rowid if we can find a name to use for the
  17162. ** rowid */
  17163. static char *azRowid[] = { "rowid", "_rowid_", "oid" };
  17164. int i, j;
  17165. for(j=0; j<3; j++){
  17166. for(i=1; i<=nCol; i++){
  17167. if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
  17168. }
  17169. if( i>nCol ){
  17170. /* At this point, we know that azRowid[j] is not the name of any
  17171. ** ordinary column in the table. Verify that azRowid[j] is a valid
  17172. ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
  17173. ** tables will fail this last check */
  17174. rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
  17175. if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
  17176. break;
  17177. }
  17178. }
  17179. }
  17180. return azCol;
  17181. }
  17182. /*
  17183. ** Toggle the reverse_unordered_selects setting.
  17184. */
  17185. static void toggleSelectOrder(sqlite3 *db){
  17186. sqlite3_stmt *pStmt = 0;
  17187. int iSetting = 0;
  17188. char zStmt[100];
  17189. sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
  17190. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  17191. iSetting = sqlite3_column_int(pStmt, 0);
  17192. }
  17193. sqlite3_finalize(pStmt);
  17194. sqlite3_snprintf(sizeof(zStmt), zStmt,
  17195. "PRAGMA reverse_unordered_selects(%d)", !iSetting);
  17196. sqlite3_exec(db, zStmt, 0, 0, 0);
  17197. }
  17198. /*
  17199. ** This is a different callback routine used for dumping the database.
  17200. ** Each row received by this callback consists of a table name,
  17201. ** the table type ("index" or "table") and SQL to create the table.
  17202. ** This routine should print text sufficient to recreate the table.
  17203. */
  17204. static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
  17205. int rc;
  17206. const char *zTable;
  17207. const char *zType;
  17208. const char *zSql;
  17209. ShellState *p = (ShellState *)pArg;
  17210. int dataOnly;
  17211. int noSys;
  17212. UNUSED_PARAMETER(azNotUsed);
  17213. if( nArg!=3 || azArg==0 ) return 0;
  17214. zTable = azArg[0];
  17215. zType = azArg[1];
  17216. zSql = azArg[2];
  17217. if( zTable==0 ) return 0;
  17218. if( zType==0 ) return 0;
  17219. dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
  17220. noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
  17221. if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
  17222. if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
  17223. }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
  17224. if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
  17225. }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
  17226. return 0;
  17227. }else if( dataOnly ){
  17228. /* no-op */
  17229. }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  17230. char *zIns;
  17231. if( !p->writableSchema ){
  17232. raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
  17233. p->writableSchema = 1;
  17234. }
  17235. zIns = sqlite3_mprintf(
  17236. "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
  17237. "VALUES('table','%q','%q',0,'%q');",
  17238. zTable, zTable, zSql);
  17239. shell_check_oom(zIns);
  17240. utf8_printf(p->out, "%s\n", zIns);
  17241. sqlite3_free(zIns);
  17242. return 0;
  17243. }else{
  17244. printSchemaLine(p->out, zSql, ";\n");
  17245. }
  17246. if( cli_strcmp(zType, "table")==0 ){
  17247. ShellText sSelect;
  17248. ShellText sTable;
  17249. char **azCol;
  17250. int i;
  17251. char *savedDestTable;
  17252. int savedMode;
  17253. azCol = tableColumnList(p, zTable);
  17254. if( azCol==0 ){
  17255. p->nErr++;
  17256. return 0;
  17257. }
  17258. /* Always quote the table name, even if it appears to be pure ascii,
  17259. ** in case it is a keyword. Ex: INSERT INTO "table" ... */
  17260. initText(&sTable);
  17261. appendText(&sTable, zTable, quoteChar(zTable));
  17262. /* If preserving the rowid, add a column list after the table name.
  17263. ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
  17264. ** instead of the usual "INSERT INTO tab VALUES(...)".
  17265. */
  17266. if( azCol[0] ){
  17267. appendText(&sTable, "(", 0);
  17268. appendText(&sTable, azCol[0], 0);
  17269. for(i=1; azCol[i]; i++){
  17270. appendText(&sTable, ",", 0);
  17271. appendText(&sTable, azCol[i], quoteChar(azCol[i]));
  17272. }
  17273. appendText(&sTable, ")", 0);
  17274. }
  17275. /* Build an appropriate SELECT statement */
  17276. initText(&sSelect);
  17277. appendText(&sSelect, "SELECT ", 0);
  17278. if( azCol[0] ){
  17279. appendText(&sSelect, azCol[0], 0);
  17280. appendText(&sSelect, ",", 0);
  17281. }
  17282. for(i=1; azCol[i]; i++){
  17283. appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
  17284. if( azCol[i+1] ){
  17285. appendText(&sSelect, ",", 0);
  17286. }
  17287. }
  17288. freeColumnList(azCol);
  17289. appendText(&sSelect, " FROM ", 0);
  17290. appendText(&sSelect, zTable, quoteChar(zTable));
  17291. savedDestTable = p->zDestTable;
  17292. savedMode = p->mode;
  17293. p->zDestTable = sTable.z;
  17294. p->mode = p->cMode = MODE_Insert;
  17295. rc = shell_exec(p, sSelect.z, 0);
  17296. if( (rc&0xff)==SQLITE_CORRUPT ){
  17297. raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  17298. toggleSelectOrder(p->db);
  17299. shell_exec(p, sSelect.z, 0);
  17300. toggleSelectOrder(p->db);
  17301. }
  17302. p->zDestTable = savedDestTable;
  17303. p->mode = savedMode;
  17304. freeText(&sTable);
  17305. freeText(&sSelect);
  17306. if( rc ) p->nErr++;
  17307. }
  17308. return 0;
  17309. }
  17310. /*
  17311. ** Run zQuery. Use dump_callback() as the callback routine so that
  17312. ** the contents of the query are output as SQL statements.
  17313. **
  17314. ** If we get a SQLITE_CORRUPT error, rerun the query after appending
  17315. ** "ORDER BY rowid DESC" to the end.
  17316. */
  17317. static int run_schema_dump_query(
  17318. ShellState *p,
  17319. const char *zQuery
  17320. ){
  17321. int rc;
  17322. char *zErr = 0;
  17323. rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
  17324. if( rc==SQLITE_CORRUPT ){
  17325. char *zQ2;
  17326. int len = strlen30(zQuery);
  17327. raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  17328. if( zErr ){
  17329. utf8_printf(p->out, "/****** %s ******/\n", zErr);
  17330. sqlite3_free(zErr);
  17331. zErr = 0;
  17332. }
  17333. zQ2 = malloc( len+100 );
  17334. if( zQ2==0 ) return rc;
  17335. sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
  17336. rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
  17337. if( rc ){
  17338. utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
  17339. }else{
  17340. rc = SQLITE_CORRUPT;
  17341. }
  17342. sqlite3_free(zErr);
  17343. free(zQ2);
  17344. }
  17345. return rc;
  17346. }
  17347. /*
  17348. ** Text of help messages.
  17349. **
  17350. ** The help text for each individual command begins with a line that starts
  17351. ** with ".". Subsequent lines are supplemental information.
  17352. **
  17353. ** There must be two or more spaces between the end of the command and the
  17354. ** start of the description of what that command does.
  17355. */
  17356. static const char *(azHelp[]) = {
  17357. #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
  17358. && !defined(SQLITE_SHELL_FIDDLE)
  17359. ".archive ... Manage SQL archives",
  17360. " Each command must have exactly one of the following options:",
  17361. " -c, --create Create a new archive",
  17362. " -u, --update Add or update files with changed mtime",
  17363. " -i, --insert Like -u but always add even if unchanged",
  17364. " -r, --remove Remove files from archive",
  17365. " -t, --list List contents of archive",
  17366. " -x, --extract Extract files from archive",
  17367. " Optional arguments:",
  17368. " -v, --verbose Print each filename as it is processed",
  17369. " -f FILE, --file FILE Use archive FILE (default is current db)",
  17370. " -a FILE, --append FILE Open FILE using the apndvfs VFS",
  17371. " -C DIR, --directory DIR Read/extract files from directory DIR",
  17372. " -g, --glob Use glob matching for names in archive",
  17373. " -n, --dryrun Show the SQL that would have occurred",
  17374. " Examples:",
  17375. " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
  17376. " .ar -tf ARCHIVE # List members of ARCHIVE",
  17377. " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
  17378. " See also:",
  17379. " http://sqlite.org/cli.html#sqlite_archive_support",
  17380. #endif
  17381. #ifndef SQLITE_OMIT_AUTHORIZATION
  17382. ".auth ON|OFF Show authorizer callbacks",
  17383. #endif
  17384. #ifndef SQLITE_SHELL_FIDDLE
  17385. ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
  17386. " Options:",
  17387. " --append Use the appendvfs",
  17388. " --async Write to FILE without journal and fsync()",
  17389. #endif
  17390. ".bail on|off Stop after hitting an error. Default OFF",
  17391. ".binary on|off Turn binary output on or off. Default OFF",
  17392. #ifndef SQLITE_SHELL_FIDDLE
  17393. ".cd DIRECTORY Change the working directory to DIRECTORY",
  17394. #endif
  17395. ".changes on|off Show number of rows changed by SQL",
  17396. #ifndef SQLITE_SHELL_FIDDLE
  17397. ".check GLOB Fail if output since .testcase does not match",
  17398. ".clone NEWDB Clone data into NEWDB from the existing database",
  17399. #endif
  17400. ".connection [close] [#] Open or close an auxiliary database connection",
  17401. ".databases List names and files of attached databases",
  17402. ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
  17403. #if SQLITE_SHELL_HAVE_RECOVER
  17404. ".dbinfo ?DB? Show status information about the database",
  17405. #endif
  17406. ".dump ?OBJECTS? Render database content as SQL",
  17407. " Options:",
  17408. " --data-only Output only INSERT statements",
  17409. " --newlines Allow unescaped newline characters in output",
  17410. " --nosys Omit system tables (ex: \"sqlite_stat1\")",
  17411. " --preserve-rowids Include ROWID values in the output",
  17412. " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
  17413. " Additional LIKE patterns can be given in subsequent arguments",
  17414. ".echo on|off Turn command echo on or off",
  17415. ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
  17416. " Other Modes:",
  17417. #ifdef SQLITE_DEBUG
  17418. " test Show raw EXPLAIN QUERY PLAN output",
  17419. " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
  17420. #endif
  17421. " trigger Like \"full\" but also show trigger bytecode",
  17422. #ifndef SQLITE_SHELL_FIDDLE
  17423. ".excel Display the output of next command in spreadsheet",
  17424. " --bom Put a UTF8 byte-order mark on intermediate file",
  17425. #endif
  17426. #ifndef SQLITE_SHELL_FIDDLE
  17427. ".exit ?CODE? Exit this program with return-code CODE",
  17428. #endif
  17429. ".expert EXPERIMENTAL. Suggest indexes for queries",
  17430. ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
  17431. ".filectrl CMD ... Run various sqlite3_file_control() operations",
  17432. " --schema SCHEMA Use SCHEMA instead of \"main\"",
  17433. " --help Show CMD details",
  17434. ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
  17435. ".headers on|off Turn display of headers on or off",
  17436. ".help ?-all? ?PATTERN? Show help text for PATTERN",
  17437. #ifndef SQLITE_SHELL_FIDDLE
  17438. ".import FILE TABLE Import data from FILE into TABLE",
  17439. " Options:",
  17440. " --ascii Use \\037 and \\036 as column and row separators",
  17441. " --csv Use , and \\n as column and row separators",
  17442. " --skip N Skip the first N rows of input",
  17443. " --schema S Target table to be S.TABLE",
  17444. " -v \"Verbose\" - increase auxiliary output",
  17445. " Notes:",
  17446. " * If TABLE does not exist, it is created. The first row of input",
  17447. " determines the column names.",
  17448. " * If neither --csv or --ascii are used, the input mode is derived",
  17449. " from the \".mode\" output mode",
  17450. " * If FILE begins with \"|\" then it is a command that generates the",
  17451. " input text.",
  17452. #endif
  17453. #ifndef SQLITE_OMIT_TEST_CONTROL
  17454. ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
  17455. #endif
  17456. ".indexes ?TABLE? Show names of indexes",
  17457. " If TABLE is specified, only show indexes for",
  17458. " tables matching TABLE using the LIKE operator.",
  17459. #ifdef SQLITE_ENABLE_IOTRACE
  17460. ".iotrace FILE Enable I/O diagnostic logging to FILE",
  17461. #endif
  17462. ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
  17463. ".lint OPTIONS Report potential schema issues.",
  17464. " Options:",
  17465. " fkey-indexes Find missing foreign key indexes",
  17466. #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
  17467. ".load FILE ?ENTRY? Load an extension library",
  17468. #endif
  17469. #ifndef SQLITE_SHELL_FIDDLE
  17470. ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
  17471. #endif
  17472. ".mode MODE ?OPTIONS? Set output mode",
  17473. " MODE is one of:",
  17474. " ascii Columns/rows delimited by 0x1F and 0x1E",
  17475. " box Tables using unicode box-drawing characters",
  17476. " csv Comma-separated values",
  17477. " column Output in columns. (See .width)",
  17478. " html HTML <table> code",
  17479. " insert SQL insert statements for TABLE",
  17480. " json Results in a JSON array",
  17481. " line One value per line",
  17482. " list Values delimited by \"|\"",
  17483. " markdown Markdown table format",
  17484. " qbox Shorthand for \"box --wrap 60 --quote\"",
  17485. " quote Escape answers as for SQL",
  17486. " table ASCII-art table",
  17487. " tabs Tab-separated values",
  17488. " tcl TCL list elements",
  17489. " OPTIONS: (for columnar modes or insert mode):",
  17490. " --wrap N Wrap output lines to no longer than N characters",
  17491. " --wordwrap B Wrap or not at word boundaries per B (on/off)",
  17492. " --ww Shorthand for \"--wordwrap 1\"",
  17493. " --quote Quote output text as SQL literals",
  17494. " --noquote Do not quote output text",
  17495. " TABLE The name of SQL table used for \"insert\" mode",
  17496. #ifndef SQLITE_SHELL_FIDDLE
  17497. ".nonce STRING Suspend safe mode for one command if nonce matches",
  17498. #endif
  17499. ".nullvalue STRING Use STRING in place of NULL values",
  17500. #ifndef SQLITE_SHELL_FIDDLE
  17501. ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
  17502. " If FILE begins with '|' then open as a pipe",
  17503. " --bom Put a UTF8 byte-order mark at the beginning",
  17504. " -e Send output to the system text editor",
  17505. " -x Send output as CSV to a spreadsheet (same as \".excel\")",
  17506. /* Note that .open is (partially) available in WASM builds but is
  17507. ** currently only intended to be used by the fiddle tool, not
  17508. ** end users, so is "undocumented." */
  17509. ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
  17510. " Options:",
  17511. " --append Use appendvfs to append database to the end of FILE",
  17512. #endif
  17513. #ifndef SQLITE_OMIT_DESERIALIZE
  17514. " --deserialize Load into memory using sqlite3_deserialize()",
  17515. " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
  17516. " --maxsize N Maximum size for --hexdb or --deserialized database",
  17517. #endif
  17518. " --new Initialize FILE to an empty database",
  17519. " --nofollow Do not follow symbolic links",
  17520. " --readonly Open FILE readonly",
  17521. " --zip FILE is a ZIP archive",
  17522. #ifndef SQLITE_SHELL_FIDDLE
  17523. ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
  17524. " If FILE begins with '|' then open it as a pipe.",
  17525. " Options:",
  17526. " --bom Prefix output with a UTF8 byte-order mark",
  17527. " -e Send output to the system text editor",
  17528. " -x Send output as CSV to a spreadsheet",
  17529. #endif
  17530. ".parameter CMD ... Manage SQL parameter bindings",
  17531. " clear Erase all bindings",
  17532. " init Initialize the TEMP table that holds bindings",
  17533. " list List the current parameter bindings",
  17534. " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
  17535. " PARAMETER should start with one of: $ : @ ?",
  17536. " unset PARAMETER Remove PARAMETER from the binding table",
  17537. ".print STRING... Print literal STRING",
  17538. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  17539. ".progress N Invoke progress handler after every N opcodes",
  17540. " --limit N Interrupt after N progress callbacks",
  17541. " --once Do no more than one progress interrupt",
  17542. " --quiet|-q No output except at interrupts",
  17543. " --reset Reset the count for each input and interrupt",
  17544. #endif
  17545. ".prompt MAIN CONTINUE Replace the standard prompts",
  17546. #ifndef SQLITE_SHELL_FIDDLE
  17547. ".quit Exit this program",
  17548. ".read FILE Read input from FILE or command output",
  17549. " If FILE begins with \"|\", it is a command that generates the input.",
  17550. #endif
  17551. #if SQLITE_SHELL_HAVE_RECOVER
  17552. ".recover Recover as much data as possible from corrupt db.",
  17553. " --ignore-freelist Ignore pages that appear to be on db freelist",
  17554. " --lost-and-found TABLE Alternative name for the lost-and-found table",
  17555. " --no-rowids Do not attempt to recover rowid values",
  17556. " that are not also INTEGER PRIMARY KEYs",
  17557. #endif
  17558. #ifndef SQLITE_SHELL_FIDDLE
  17559. ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
  17560. ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)",
  17561. #endif
  17562. ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
  17563. ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
  17564. " Options:",
  17565. " --indent Try to pretty-print the schema",
  17566. " --nosys Omit objects whose names start with \"sqlite_\"",
  17567. ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
  17568. " Options:",
  17569. " --init Create a new SELFTEST table",
  17570. " -v Verbose output",
  17571. ".separator COL ?ROW? Change the column and row separators",
  17572. #if defined(SQLITE_ENABLE_SESSION)
  17573. ".session ?NAME? CMD ... Create or control sessions",
  17574. " Subcommands:",
  17575. " attach TABLE Attach TABLE",
  17576. " changeset FILE Write a changeset into FILE",
  17577. " close Close one session",
  17578. " enable ?BOOLEAN? Set or query the enable bit",
  17579. " filter GLOB... Reject tables matching GLOBs",
  17580. " indirect ?BOOLEAN? Mark or query the indirect status",
  17581. " isempty Query whether the session is empty",
  17582. " list List currently open session names",
  17583. " open DB NAME Open a new session on DB",
  17584. " patchset FILE Write a patchset into FILE",
  17585. " If ?NAME? is omitted, the first defined session is used.",
  17586. #endif
  17587. ".sha3sum ... Compute a SHA3 hash of database content",
  17588. " Options:",
  17589. " --schema Also hash the sqlite_schema table",
  17590. " --sha3-224 Use the sha3-224 algorithm",
  17591. " --sha3-256 Use the sha3-256 algorithm (default)",
  17592. " --sha3-384 Use the sha3-384 algorithm",
  17593. " --sha3-512 Use the sha3-512 algorithm",
  17594. " Any other argument is a LIKE pattern for tables to hash",
  17595. #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
  17596. ".shell CMD ARGS... Run CMD ARGS... in a system shell",
  17597. #endif
  17598. ".show Show the current values for various settings",
  17599. ".stats ?ARG? Show stats or turn stats on or off",
  17600. " off Turn off automatic stat display",
  17601. " on Turn on automatic stat display",
  17602. " stmt Show statement stats",
  17603. " vmstep Show the virtual machine step count only",
  17604. #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
  17605. ".system CMD ARGS... Run CMD ARGS... in a system shell",
  17606. #endif
  17607. ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
  17608. #ifndef SQLITE_SHELL_FIDDLE
  17609. ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
  17610. #endif
  17611. ".testctrl CMD ... Run various sqlite3_test_control() operations",
  17612. " Run \".testctrl\" with no arguments for details",
  17613. ".timeout MS Try opening locked tables for MS milliseconds",
  17614. ".timer on|off Turn SQL timer on or off",
  17615. #ifndef SQLITE_OMIT_TRACE
  17616. ".trace ?OPTIONS? Output each SQL statement as it is run",
  17617. " FILE Send output to FILE",
  17618. " stdout Send output to stdout",
  17619. " stderr Send output to stderr",
  17620. " off Disable tracing",
  17621. " --expanded Expand query parameters",
  17622. #ifdef SQLITE_ENABLE_NORMALIZE
  17623. " --normalized Normal the SQL statements",
  17624. #endif
  17625. " --plain Show SQL as it is input",
  17626. " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
  17627. " --profile Profile statements (SQLITE_TRACE_PROFILE)",
  17628. " --row Trace each row (SQLITE_TRACE_ROW)",
  17629. " --close Trace connection close (SQLITE_TRACE_CLOSE)",
  17630. #endif /* SQLITE_OMIT_TRACE */
  17631. #ifdef SQLITE_DEBUG
  17632. ".unmodule NAME ... Unregister virtual table modules",
  17633. " --allexcept Unregister everything except those named",
  17634. #endif
  17635. ".vfsinfo ?AUX? Information about the top-level VFS",
  17636. ".vfslist List all available VFSes",
  17637. ".vfsname ?AUX? Print the name of the VFS stack",
  17638. ".width NUM1 NUM2 ... Set minimum column widths for columnar output",
  17639. " Negative values right-justify",
  17640. };
  17641. /*
  17642. ** Output help text.
  17643. **
  17644. ** zPattern describes the set of commands for which help text is provided.
  17645. ** If zPattern is NULL, then show all commands, but only give a one-line
  17646. ** description of each.
  17647. **
  17648. ** Return the number of matches.
  17649. */
  17650. static int showHelp(FILE *out, const char *zPattern){
  17651. int i = 0;
  17652. int j = 0;
  17653. int n = 0;
  17654. char *zPat;
  17655. if( zPattern==0
  17656. || zPattern[0]=='0'
  17657. || cli_strcmp(zPattern,"-a")==0
  17658. || cli_strcmp(zPattern,"-all")==0
  17659. || cli_strcmp(zPattern,"--all")==0
  17660. ){
  17661. /* Show all commands, but only one line per command */
  17662. if( zPattern==0 ) zPattern = "";
  17663. for(i=0; i<ArraySize(azHelp); i++){
  17664. if( azHelp[i][0]=='.' || zPattern[0] ){
  17665. utf8_printf(out, "%s\n", azHelp[i]);
  17666. n++;
  17667. }
  17668. }
  17669. }else{
  17670. /* Look for commands that for which zPattern is an exact prefix */
  17671. zPat = sqlite3_mprintf(".%s*", zPattern);
  17672. shell_check_oom(zPat);
  17673. for(i=0; i<ArraySize(azHelp); i++){
  17674. if( sqlite3_strglob(zPat, azHelp[i])==0 ){
  17675. utf8_printf(out, "%s\n", azHelp[i]);
  17676. j = i+1;
  17677. n++;
  17678. }
  17679. }
  17680. sqlite3_free(zPat);
  17681. if( n ){
  17682. if( n==1 ){
  17683. /* when zPattern is a prefix of exactly one command, then include the
  17684. ** details of that command, which should begin at offset j */
  17685. while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
  17686. utf8_printf(out, "%s\n", azHelp[j]);
  17687. j++;
  17688. }
  17689. }
  17690. return n;
  17691. }
  17692. /* Look for commands that contain zPattern anywhere. Show the complete
  17693. ** text of all commands that match. */
  17694. zPat = sqlite3_mprintf("%%%s%%", zPattern);
  17695. shell_check_oom(zPat);
  17696. for(i=0; i<ArraySize(azHelp); i++){
  17697. if( azHelp[i][0]=='.' ) j = i;
  17698. if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
  17699. utf8_printf(out, "%s\n", azHelp[j]);
  17700. while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
  17701. j++;
  17702. utf8_printf(out, "%s\n", azHelp[j]);
  17703. }
  17704. i = j;
  17705. n++;
  17706. }
  17707. }
  17708. sqlite3_free(zPat);
  17709. }
  17710. return n;
  17711. }
  17712. /* Forward reference */
  17713. static int process_input(ShellState *p);
  17714. /*
  17715. ** Read the content of file zName into memory obtained from sqlite3_malloc64()
  17716. ** and return a pointer to the buffer. The caller is responsible for freeing
  17717. ** the memory.
  17718. **
  17719. ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
  17720. ** read.
  17721. **
  17722. ** For convenience, a nul-terminator byte is always appended to the data read
  17723. ** from the file before the buffer is returned. This byte is not included in
  17724. ** the final value of (*pnByte), if applicable.
  17725. **
  17726. ** NULL is returned if any error is encountered. The final value of *pnByte
  17727. ** is undefined in this case.
  17728. */
  17729. static char *readFile(const char *zName, int *pnByte){
  17730. FILE *in = fopen(zName, "rb");
  17731. long nIn;
  17732. size_t nRead;
  17733. char *pBuf;
  17734. if( in==0 ) return 0;
  17735. fseek(in, 0, SEEK_END);
  17736. nIn = ftell(in);
  17737. rewind(in);
  17738. pBuf = sqlite3_malloc64( nIn+1 );
  17739. if( pBuf==0 ){ fclose(in); return 0; }
  17740. nRead = fread(pBuf, nIn, 1, in);
  17741. fclose(in);
  17742. if( nRead!=1 ){
  17743. sqlite3_free(pBuf);
  17744. return 0;
  17745. }
  17746. pBuf[nIn] = 0;
  17747. if( pnByte ) *pnByte = nIn;
  17748. return pBuf;
  17749. }
  17750. #if defined(SQLITE_ENABLE_SESSION)
  17751. /*
  17752. ** Close a single OpenSession object and release all of its associated
  17753. ** resources.
  17754. */
  17755. static void session_close(OpenSession *pSession){
  17756. int i;
  17757. sqlite3session_delete(pSession->p);
  17758. sqlite3_free(pSession->zName);
  17759. for(i=0; i<pSession->nFilter; i++){
  17760. sqlite3_free(pSession->azFilter[i]);
  17761. }
  17762. sqlite3_free(pSession->azFilter);
  17763. memset(pSession, 0, sizeof(OpenSession));
  17764. }
  17765. #endif
  17766. /*
  17767. ** Close all OpenSession objects and release all associated resources.
  17768. */
  17769. #if defined(SQLITE_ENABLE_SESSION)
  17770. static void session_close_all(ShellState *p, int i){
  17771. int j;
  17772. struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
  17773. for(j=0; j<pAuxDb->nSession; j++){
  17774. session_close(&pAuxDb->aSession[j]);
  17775. }
  17776. pAuxDb->nSession = 0;
  17777. }
  17778. #else
  17779. # define session_close_all(X,Y)
  17780. #endif
  17781. /*
  17782. ** Implementation of the xFilter function for an open session. Omit
  17783. ** any tables named by ".session filter" but let all other table through.
  17784. */
  17785. #if defined(SQLITE_ENABLE_SESSION)
  17786. static int session_filter(void *pCtx, const char *zTab){
  17787. OpenSession *pSession = (OpenSession*)pCtx;
  17788. int i;
  17789. for(i=0; i<pSession->nFilter; i++){
  17790. if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
  17791. }
  17792. return 1;
  17793. }
  17794. #endif
  17795. /*
  17796. ** Try to deduce the type of file for zName based on its content. Return
  17797. ** one of the SHELL_OPEN_* constants.
  17798. **
  17799. ** If the file does not exist or is empty but its name looks like a ZIP
  17800. ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
  17801. ** Otherwise, assume an ordinary database regardless of the filename if
  17802. ** the type cannot be determined from content.
  17803. */
  17804. int deduceDatabaseType(const char *zName, int dfltZip){
  17805. FILE *f = fopen(zName, "rb");
  17806. size_t n;
  17807. int rc = SHELL_OPEN_UNSPEC;
  17808. char zBuf[100];
  17809. if( f==0 ){
  17810. if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
  17811. return SHELL_OPEN_ZIPFILE;
  17812. }else{
  17813. return SHELL_OPEN_NORMAL;
  17814. }
  17815. }
  17816. n = fread(zBuf, 16, 1, f);
  17817. if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
  17818. fclose(f);
  17819. return SHELL_OPEN_NORMAL;
  17820. }
  17821. fseek(f, -25, SEEK_END);
  17822. n = fread(zBuf, 25, 1, f);
  17823. if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
  17824. rc = SHELL_OPEN_APPENDVFS;
  17825. }else{
  17826. fseek(f, -22, SEEK_END);
  17827. n = fread(zBuf, 22, 1, f);
  17828. if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
  17829. && zBuf[3]==0x06 ){
  17830. rc = SHELL_OPEN_ZIPFILE;
  17831. }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
  17832. rc = SHELL_OPEN_ZIPFILE;
  17833. }
  17834. }
  17835. fclose(f);
  17836. return rc;
  17837. }
  17838. #ifndef SQLITE_OMIT_DESERIALIZE
  17839. /*
  17840. ** Reconstruct an in-memory database using the output from the "dbtotxt"
  17841. ** program. Read content from the file in p->aAuxDb[].zDbFilename.
  17842. ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
  17843. */
  17844. static unsigned char *readHexDb(ShellState *p, int *pnData){
  17845. unsigned char *a = 0;
  17846. int nLine;
  17847. int n = 0;
  17848. int pgsz = 0;
  17849. int iOffset = 0;
  17850. int j, k;
  17851. int rc;
  17852. FILE *in;
  17853. const char *zDbFilename = p->pAuxDb->zDbFilename;
  17854. unsigned int x[16];
  17855. char zLine[1000];
  17856. if( zDbFilename ){
  17857. in = fopen(zDbFilename, "r");
  17858. if( in==0 ){
  17859. utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
  17860. return 0;
  17861. }
  17862. nLine = 0;
  17863. }else{
  17864. in = p->in;
  17865. nLine = p->lineno;
  17866. if( in==0 ) in = stdin;
  17867. }
  17868. *pnData = 0;
  17869. nLine++;
  17870. if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
  17871. rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
  17872. if( rc!=2 ) goto readHexDb_error;
  17873. if( n<0 ) goto readHexDb_error;
  17874. if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
  17875. n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */
  17876. a = sqlite3_malloc( n ? n : 1 );
  17877. shell_check_oom(a);
  17878. memset(a, 0, n);
  17879. if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
  17880. utf8_printf(stderr, "invalid pagesize\n");
  17881. goto readHexDb_error;
  17882. }
  17883. for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
  17884. rc = sscanf(zLine, "| page %d offset %d", &j, &k);
  17885. if( rc==2 ){
  17886. iOffset = k;
  17887. continue;
  17888. }
  17889. if( cli_strncmp(zLine, "| end ", 6)==0 ){
  17890. break;
  17891. }
  17892. rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
  17893. &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
  17894. &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
  17895. if( rc==17 ){
  17896. k = iOffset+j;
  17897. if( k+16<=n && k>=0 ){
  17898. int ii;
  17899. for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
  17900. }
  17901. }
  17902. }
  17903. *pnData = n;
  17904. if( in!=p->in ){
  17905. fclose(in);
  17906. }else{
  17907. p->lineno = nLine;
  17908. }
  17909. return a;
  17910. readHexDb_error:
  17911. if( in!=p->in ){
  17912. fclose(in);
  17913. }else{
  17914. while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
  17915. nLine++;
  17916. if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
  17917. }
  17918. p->lineno = nLine;
  17919. }
  17920. sqlite3_free(a);
  17921. utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
  17922. return 0;
  17923. }
  17924. #endif /* SQLITE_OMIT_DESERIALIZE */
  17925. /*
  17926. ** Scalar function "shell_int32". The first argument to this function
  17927. ** must be a blob. The second a non-negative integer. This function
  17928. ** reads and returns a 32-bit big-endian integer from byte
  17929. ** offset (4*<arg2>) of the blob.
  17930. */
  17931. static void shellInt32(
  17932. sqlite3_context *context,
  17933. int argc,
  17934. sqlite3_value **argv
  17935. ){
  17936. const unsigned char *pBlob;
  17937. int nBlob;
  17938. int iInt;
  17939. UNUSED_PARAMETER(argc);
  17940. nBlob = sqlite3_value_bytes(argv[0]);
  17941. pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
  17942. iInt = sqlite3_value_int(argv[1]);
  17943. if( iInt>=0 && (iInt+1)*4<=nBlob ){
  17944. const unsigned char *a = &pBlob[iInt*4];
  17945. sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
  17946. + ((sqlite3_int64)a[1]<<16)
  17947. + ((sqlite3_int64)a[2]<< 8)
  17948. + ((sqlite3_int64)a[3]<< 0);
  17949. sqlite3_result_int64(context, iVal);
  17950. }
  17951. }
  17952. /*
  17953. ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
  17954. ** using "..." with internal double-quote characters doubled.
  17955. */
  17956. static void shellIdQuote(
  17957. sqlite3_context *context,
  17958. int argc,
  17959. sqlite3_value **argv
  17960. ){
  17961. const char *zName = (const char*)sqlite3_value_text(argv[0]);
  17962. UNUSED_PARAMETER(argc);
  17963. if( zName ){
  17964. char *z = sqlite3_mprintf("\"%w\"", zName);
  17965. sqlite3_result_text(context, z, -1, sqlite3_free);
  17966. }
  17967. }
  17968. /*
  17969. ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
  17970. */
  17971. static void shellUSleepFunc(
  17972. sqlite3_context *context,
  17973. int argcUnused,
  17974. sqlite3_value **argv
  17975. ){
  17976. int sleep = sqlite3_value_int(argv[0]);
  17977. (void)argcUnused;
  17978. sqlite3_sleep(sleep/1000);
  17979. sqlite3_result_int(context, sleep);
  17980. }
  17981. /*
  17982. ** Scalar function "shell_escape_crnl" used by the .recover command.
  17983. ** The argument passed to this function is the output of built-in
  17984. ** function quote(). If the first character of the input is "'",
  17985. ** indicating that the value passed to quote() was a text value,
  17986. ** then this function searches the input for "\n" and "\r" characters
  17987. ** and adds a wrapper similar to the following:
  17988. **
  17989. ** replace(replace(<input>, '\n', char(10), '\r', char(13));
  17990. **
  17991. ** Or, if the first character of the input is not "'", then a copy
  17992. ** of the input is returned.
  17993. */
  17994. static void shellEscapeCrnl(
  17995. sqlite3_context *context,
  17996. int argc,
  17997. sqlite3_value **argv
  17998. ){
  17999. const char *zText = (const char*)sqlite3_value_text(argv[0]);
  18000. UNUSED_PARAMETER(argc);
  18001. if( zText && zText[0]=='\'' ){
  18002. i64 nText = sqlite3_value_bytes(argv[0]);
  18003. i64 i;
  18004. char zBuf1[20];
  18005. char zBuf2[20];
  18006. const char *zNL = 0;
  18007. const char *zCR = 0;
  18008. i64 nCR = 0;
  18009. i64 nNL = 0;
  18010. for(i=0; zText[i]; i++){
  18011. if( zNL==0 && zText[i]=='\n' ){
  18012. zNL = unused_string(zText, "\\n", "\\012", zBuf1);
  18013. nNL = strlen(zNL);
  18014. }
  18015. if( zCR==0 && zText[i]=='\r' ){
  18016. zCR = unused_string(zText, "\\r", "\\015", zBuf2);
  18017. nCR = strlen(zCR);
  18018. }
  18019. }
  18020. if( zNL || zCR ){
  18021. i64 iOut = 0;
  18022. i64 nMax = (nNL > nCR) ? nNL : nCR;
  18023. i64 nAlloc = nMax * nText + (nMax+64)*2;
  18024. char *zOut = (char*)sqlite3_malloc64(nAlloc);
  18025. if( zOut==0 ){
  18026. sqlite3_result_error_nomem(context);
  18027. return;
  18028. }
  18029. if( zNL && zCR ){
  18030. memcpy(&zOut[iOut], "replace(replace(", 16);
  18031. iOut += 16;
  18032. }else{
  18033. memcpy(&zOut[iOut], "replace(", 8);
  18034. iOut += 8;
  18035. }
  18036. for(i=0; zText[i]; i++){
  18037. if( zText[i]=='\n' ){
  18038. memcpy(&zOut[iOut], zNL, nNL);
  18039. iOut += nNL;
  18040. }else if( zText[i]=='\r' ){
  18041. memcpy(&zOut[iOut], zCR, nCR);
  18042. iOut += nCR;
  18043. }else{
  18044. zOut[iOut] = zText[i];
  18045. iOut++;
  18046. }
  18047. }
  18048. if( zNL ){
  18049. memcpy(&zOut[iOut], ",'", 2); iOut += 2;
  18050. memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
  18051. memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
  18052. }
  18053. if( zCR ){
  18054. memcpy(&zOut[iOut], ",'", 2); iOut += 2;
  18055. memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
  18056. memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
  18057. }
  18058. sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
  18059. sqlite3_free(zOut);
  18060. return;
  18061. }
  18062. }
  18063. sqlite3_result_value(context, argv[0]);
  18064. }
  18065. /* Flags for open_db().
  18066. **
  18067. ** The default behavior of open_db() is to exit(1) if the database fails to
  18068. ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
  18069. ** but still returns without calling exit.
  18070. **
  18071. ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
  18072. ** ZIP archive if the file does not exist or is empty and its name matches
  18073. ** the *.zip pattern.
  18074. */
  18075. #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
  18076. #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
  18077. /*
  18078. ** Make sure the database is open. If it is not, then open it. If
  18079. ** the database fails to open, print an error message and exit.
  18080. */
  18081. static void open_db(ShellState *p, int openFlags){
  18082. if( p->db==0 ){
  18083. const char *zDbFilename = p->pAuxDb->zDbFilename;
  18084. if( p->openMode==SHELL_OPEN_UNSPEC ){
  18085. if( zDbFilename==0 || zDbFilename[0]==0 ){
  18086. p->openMode = SHELL_OPEN_NORMAL;
  18087. }else{
  18088. p->openMode = (u8)deduceDatabaseType(zDbFilename,
  18089. (openFlags & OPEN_DB_ZIPFILE)!=0);
  18090. }
  18091. }
  18092. switch( p->openMode ){
  18093. case SHELL_OPEN_APPENDVFS: {
  18094. sqlite3_open_v2(zDbFilename, &p->db,
  18095. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
  18096. break;
  18097. }
  18098. case SHELL_OPEN_HEXDB:
  18099. case SHELL_OPEN_DESERIALIZE: {
  18100. sqlite3_open(0, &p->db);
  18101. break;
  18102. }
  18103. case SHELL_OPEN_ZIPFILE: {
  18104. sqlite3_open(":memory:", &p->db);
  18105. break;
  18106. }
  18107. case SHELL_OPEN_READONLY: {
  18108. sqlite3_open_v2(zDbFilename, &p->db,
  18109. SQLITE_OPEN_READONLY|p->openFlags, 0);
  18110. break;
  18111. }
  18112. case SHELL_OPEN_UNSPEC:
  18113. case SHELL_OPEN_NORMAL: {
  18114. sqlite3_open_v2(zDbFilename, &p->db,
  18115. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
  18116. break;
  18117. }
  18118. }
  18119. globalDb = p->db;
  18120. if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
  18121. utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
  18122. zDbFilename, sqlite3_errmsg(p->db));
  18123. if( openFlags & OPEN_DB_KEEPALIVE ){
  18124. sqlite3_open(":memory:", &p->db);
  18125. return;
  18126. }
  18127. exit(1);
  18128. }
  18129. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  18130. sqlite3_enable_load_extension(p->db, 1);
  18131. #endif
  18132. sqlite3_shathree_init(p->db, 0, 0);
  18133. sqlite3_uint_init(p->db, 0, 0);
  18134. sqlite3_decimal_init(p->db, 0, 0);
  18135. sqlite3_regexp_init(p->db, 0, 0);
  18136. sqlite3_ieee_init(p->db, 0, 0);
  18137. sqlite3_series_init(p->db, 0, 0);
  18138. #ifndef SQLITE_SHELL_FIDDLE
  18139. sqlite3_fileio_init(p->db, 0, 0);
  18140. sqlite3_completion_init(p->db, 0, 0);
  18141. #endif
  18142. #if SQLITE_SHELL_HAVE_RECOVER
  18143. sqlite3_dbdata_init(p->db, 0, 0);
  18144. #endif
  18145. #ifdef SQLITE_HAVE_ZLIB
  18146. if( !p->bSafeModePersist ){
  18147. sqlite3_zipfile_init(p->db, 0, 0);
  18148. sqlite3_sqlar_init(p->db, 0, 0);
  18149. }
  18150. #endif
  18151. sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
  18152. shellAddSchemaName, 0, 0);
  18153. sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
  18154. shellModuleSchema, 0, 0);
  18155. sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
  18156. shellPutsFunc, 0, 0);
  18157. sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
  18158. shellEscapeCrnl, 0, 0);
  18159. sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
  18160. shellInt32, 0, 0);
  18161. sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
  18162. shellIdQuote, 0, 0);
  18163. sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
  18164. shellUSleepFunc, 0, 0);
  18165. #ifndef SQLITE_NOHAVE_SYSTEM
  18166. sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
  18167. editFunc, 0, 0);
  18168. sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
  18169. editFunc, 0, 0);
  18170. #endif
  18171. if( p->openMode==SHELL_OPEN_ZIPFILE ){
  18172. char *zSql = sqlite3_mprintf(
  18173. "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
  18174. shell_check_oom(zSql);
  18175. sqlite3_exec(p->db, zSql, 0, 0, 0);
  18176. sqlite3_free(zSql);
  18177. }
  18178. #ifndef SQLITE_OMIT_DESERIALIZE
  18179. else
  18180. if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
  18181. int rc;
  18182. int nData = 0;
  18183. unsigned char *aData;
  18184. if( p->openMode==SHELL_OPEN_DESERIALIZE ){
  18185. aData = (unsigned char*)readFile(zDbFilename, &nData);
  18186. }else{
  18187. aData = readHexDb(p, &nData);
  18188. if( aData==0 ){
  18189. return;
  18190. }
  18191. }
  18192. rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
  18193. SQLITE_DESERIALIZE_RESIZEABLE |
  18194. SQLITE_DESERIALIZE_FREEONCLOSE);
  18195. if( rc ){
  18196. utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
  18197. }
  18198. if( p->szMax>0 ){
  18199. sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
  18200. }
  18201. }
  18202. #endif
  18203. }
  18204. if( p->bSafeModePersist && p->db!=0 ){
  18205. sqlite3_set_authorizer(p->db, safeModeAuth, p);
  18206. }
  18207. }
  18208. /*
  18209. ** Attempt to close the databaes connection. Report errors.
  18210. */
  18211. void close_db(sqlite3 *db){
  18212. int rc = sqlite3_close(db);
  18213. if( rc ){
  18214. utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
  18215. rc, sqlite3_errmsg(db));
  18216. }
  18217. }
  18218. #if HAVE_READLINE || HAVE_EDITLINE
  18219. /*
  18220. ** Readline completion callbacks
  18221. */
  18222. static char *readline_completion_generator(const char *text, int state){
  18223. static sqlite3_stmt *pStmt = 0;
  18224. char *zRet;
  18225. if( state==0 ){
  18226. char *zSql;
  18227. sqlite3_finalize(pStmt);
  18228. zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
  18229. " FROM completion(%Q) ORDER BY 1", text);
  18230. shell_check_oom(zSql);
  18231. sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
  18232. sqlite3_free(zSql);
  18233. }
  18234. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  18235. const char *z = (const char*)sqlite3_column_text(pStmt,0);
  18236. zRet = z ? strdup(z) : 0;
  18237. }else{
  18238. sqlite3_finalize(pStmt);
  18239. pStmt = 0;
  18240. zRet = 0;
  18241. }
  18242. return zRet;
  18243. }
  18244. static char **readline_completion(const char *zText, int iStart, int iEnd){
  18245. rl_attempted_completion_over = 1;
  18246. return rl_completion_matches(zText, readline_completion_generator);
  18247. }
  18248. #elif HAVE_LINENOISE
  18249. /*
  18250. ** Linenoise completion callback
  18251. */
  18252. static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
  18253. i64 nLine = strlen(zLine);
  18254. i64 i, iStart;
  18255. sqlite3_stmt *pStmt = 0;
  18256. char *zSql;
  18257. char zBuf[1000];
  18258. if( nLine>sizeof(zBuf)-30 ) return;
  18259. if( zLine[0]=='.' || zLine[0]=='#') return;
  18260. for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
  18261. if( i==nLine-1 ) return;
  18262. iStart = i+1;
  18263. memcpy(zBuf, zLine, iStart);
  18264. zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
  18265. " FROM completion(%Q,%Q) ORDER BY 1",
  18266. &zLine[iStart], zLine);
  18267. shell_check_oom(zSql);
  18268. sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
  18269. sqlite3_free(zSql);
  18270. sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
  18271. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  18272. const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
  18273. int nCompletion = sqlite3_column_bytes(pStmt, 0);
  18274. if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
  18275. memcpy(zBuf+iStart, zCompletion, nCompletion+1);
  18276. linenoiseAddCompletion(lc, zBuf);
  18277. }
  18278. }
  18279. sqlite3_finalize(pStmt);
  18280. }
  18281. #endif
  18282. /*
  18283. ** Do C-language style dequoting.
  18284. **
  18285. ** \a -> alarm
  18286. ** \b -> backspace
  18287. ** \t -> tab
  18288. ** \n -> newline
  18289. ** \v -> vertical tab
  18290. ** \f -> form feed
  18291. ** \r -> carriage return
  18292. ** \s -> space
  18293. ** \" -> "
  18294. ** \' -> '
  18295. ** \\ -> backslash
  18296. ** \NNN -> ascii character NNN in octal
  18297. */
  18298. static void resolve_backslashes(char *z){
  18299. int i, j;
  18300. char c;
  18301. while( *z && *z!='\\' ) z++;
  18302. for(i=j=0; (c = z[i])!=0; i++, j++){
  18303. if( c=='\\' && z[i+1]!=0 ){
  18304. c = z[++i];
  18305. if( c=='a' ){
  18306. c = '\a';
  18307. }else if( c=='b' ){
  18308. c = '\b';
  18309. }else if( c=='t' ){
  18310. c = '\t';
  18311. }else if( c=='n' ){
  18312. c = '\n';
  18313. }else if( c=='v' ){
  18314. c = '\v';
  18315. }else if( c=='f' ){
  18316. c = '\f';
  18317. }else if( c=='r' ){
  18318. c = '\r';
  18319. }else if( c=='"' ){
  18320. c = '"';
  18321. }else if( c=='\'' ){
  18322. c = '\'';
  18323. }else if( c=='\\' ){
  18324. c = '\\';
  18325. }else if( c>='0' && c<='7' ){
  18326. c -= '0';
  18327. if( z[i+1]>='0' && z[i+1]<='7' ){
  18328. i++;
  18329. c = (c<<3) + z[i] - '0';
  18330. if( z[i+1]>='0' && z[i+1]<='7' ){
  18331. i++;
  18332. c = (c<<3) + z[i] - '0';
  18333. }
  18334. }
  18335. }
  18336. }
  18337. z[j] = c;
  18338. }
  18339. if( j<i ) z[j] = 0;
  18340. }
  18341. /*
  18342. ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
  18343. ** for TRUE and FALSE. Return the integer value if appropriate.
  18344. */
  18345. static int booleanValue(const char *zArg){
  18346. int i;
  18347. if( zArg[0]=='0' && zArg[1]=='x' ){
  18348. for(i=2; hexDigitValue(zArg[i])>=0; i++){}
  18349. }else{
  18350. for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
  18351. }
  18352. if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
  18353. if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
  18354. return 1;
  18355. }
  18356. if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
  18357. return 0;
  18358. }
  18359. utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
  18360. zArg);
  18361. return 0;
  18362. }
  18363. /*
  18364. ** Set or clear a shell flag according to a boolean value.
  18365. */
  18366. static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
  18367. if( booleanValue(zArg) ){
  18368. ShellSetFlag(p, mFlag);
  18369. }else{
  18370. ShellClearFlag(p, mFlag);
  18371. }
  18372. }
  18373. /*
  18374. ** Close an output file, assuming it is not stderr or stdout
  18375. */
  18376. static void output_file_close(FILE *f){
  18377. if( f && f!=stdout && f!=stderr ) fclose(f);
  18378. }
  18379. /*
  18380. ** Try to open an output file. The names "stdout" and "stderr" are
  18381. ** recognized and do the right thing. NULL is returned if the output
  18382. ** filename is "off".
  18383. */
  18384. static FILE *output_file_open(const char *zFile, int bTextMode){
  18385. FILE *f;
  18386. if( cli_strcmp(zFile,"stdout")==0 ){
  18387. f = stdout;
  18388. }else if( cli_strcmp(zFile, "stderr")==0 ){
  18389. f = stderr;
  18390. }else if( cli_strcmp(zFile, "off")==0 ){
  18391. f = 0;
  18392. }else{
  18393. f = fopen(zFile, bTextMode ? "w" : "wb");
  18394. if( f==0 ){
  18395. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  18396. }
  18397. }
  18398. return f;
  18399. }
  18400. #ifndef SQLITE_OMIT_TRACE
  18401. /*
  18402. ** A routine for handling output from sqlite3_trace().
  18403. */
  18404. static int sql_trace_callback(
  18405. unsigned mType, /* The trace type */
  18406. void *pArg, /* The ShellState pointer */
  18407. void *pP, /* Usually a pointer to sqlite_stmt */
  18408. void *pX /* Auxiliary output */
  18409. ){
  18410. ShellState *p = (ShellState*)pArg;
  18411. sqlite3_stmt *pStmt;
  18412. const char *zSql;
  18413. i64 nSql;
  18414. if( p->traceOut==0 ) return 0;
  18415. if( mType==SQLITE_TRACE_CLOSE ){
  18416. utf8_printf(p->traceOut, "-- closing database connection\n");
  18417. return 0;
  18418. }
  18419. if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
  18420. zSql = (const char*)pX;
  18421. }else{
  18422. pStmt = (sqlite3_stmt*)pP;
  18423. switch( p->eTraceType ){
  18424. case SHELL_TRACE_EXPANDED: {
  18425. zSql = sqlite3_expanded_sql(pStmt);
  18426. break;
  18427. }
  18428. #ifdef SQLITE_ENABLE_NORMALIZE
  18429. case SHELL_TRACE_NORMALIZED: {
  18430. zSql = sqlite3_normalized_sql(pStmt);
  18431. break;
  18432. }
  18433. #endif
  18434. default: {
  18435. zSql = sqlite3_sql(pStmt);
  18436. break;
  18437. }
  18438. }
  18439. }
  18440. if( zSql==0 ) return 0;
  18441. nSql = strlen(zSql);
  18442. if( nSql>1000000000 ) nSql = 1000000000;
  18443. while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
  18444. switch( mType ){
  18445. case SQLITE_TRACE_ROW:
  18446. case SQLITE_TRACE_STMT: {
  18447. utf8_printf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
  18448. break;
  18449. }
  18450. case SQLITE_TRACE_PROFILE: {
  18451. sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
  18452. utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
  18453. break;
  18454. }
  18455. }
  18456. return 0;
  18457. }
  18458. #endif
  18459. /*
  18460. ** A no-op routine that runs with the ".breakpoint" doc-command. This is
  18461. ** a useful spot to set a debugger breakpoint.
  18462. */
  18463. static void test_breakpoint(void){
  18464. static int nCall = 0;
  18465. nCall++;
  18466. }
  18467. /*
  18468. ** An object used to read a CSV and other files for import.
  18469. */
  18470. typedef struct ImportCtx ImportCtx;
  18471. struct ImportCtx {
  18472. const char *zFile; /* Name of the input file */
  18473. FILE *in; /* Read the CSV text from this input stream */
  18474. int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */
  18475. char *z; /* Accumulated text for a field */
  18476. int n; /* Number of bytes in z */
  18477. int nAlloc; /* Space allocated for z[] */
  18478. int nLine; /* Current line number */
  18479. int nRow; /* Number of rows imported */
  18480. int nErr; /* Number of errors encountered */
  18481. int bNotFirst; /* True if one or more bytes already read */
  18482. int cTerm; /* Character that terminated the most recent field */
  18483. int cColSep; /* The column separator character. (Usually ",") */
  18484. int cRowSep; /* The row separator character. (Usually "\n") */
  18485. };
  18486. /* Clean up resourced used by an ImportCtx */
  18487. static void import_cleanup(ImportCtx *p){
  18488. if( p->in!=0 && p->xCloser!=0 ){
  18489. p->xCloser(p->in);
  18490. p->in = 0;
  18491. }
  18492. sqlite3_free(p->z);
  18493. p->z = 0;
  18494. }
  18495. /* Append a single byte to z[] */
  18496. static void import_append_char(ImportCtx *p, int c){
  18497. if( p->n+1>=p->nAlloc ){
  18498. p->nAlloc += p->nAlloc + 100;
  18499. p->z = sqlite3_realloc64(p->z, p->nAlloc);
  18500. shell_check_oom(p->z);
  18501. }
  18502. p->z[p->n++] = (char)c;
  18503. }
  18504. /* Read a single field of CSV text. Compatible with rfc4180 and extended
  18505. ** with the option of having a separator other than ",".
  18506. **
  18507. ** + Input comes from p->in.
  18508. ** + Store results in p->z of length p->n. Space to hold p->z comes
  18509. ** from sqlite3_malloc64().
  18510. ** + Use p->cSep as the column separator. The default is ",".
  18511. ** + Use p->rSep as the row separator. The default is "\n".
  18512. ** + Keep track of the line number in p->nLine.
  18513. ** + Store the character that terminates the field in p->cTerm. Store
  18514. ** EOF on end-of-file.
  18515. ** + Report syntax errors on stderr
  18516. */
  18517. static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
  18518. int c;
  18519. int cSep = p->cColSep;
  18520. int rSep = p->cRowSep;
  18521. p->n = 0;
  18522. c = fgetc(p->in);
  18523. if( c==EOF || seenInterrupt ){
  18524. p->cTerm = EOF;
  18525. return 0;
  18526. }
  18527. if( c=='"' ){
  18528. int pc, ppc;
  18529. int startLine = p->nLine;
  18530. int cQuote = c;
  18531. pc = ppc = 0;
  18532. while( 1 ){
  18533. c = fgetc(p->in);
  18534. if( c==rSep ) p->nLine++;
  18535. if( c==cQuote ){
  18536. if( pc==cQuote ){
  18537. pc = 0;
  18538. continue;
  18539. }
  18540. }
  18541. if( (c==cSep && pc==cQuote)
  18542. || (c==rSep && pc==cQuote)
  18543. || (c==rSep && pc=='\r' && ppc==cQuote)
  18544. || (c==EOF && pc==cQuote)
  18545. ){
  18546. do{ p->n--; }while( p->z[p->n]!=cQuote );
  18547. p->cTerm = c;
  18548. break;
  18549. }
  18550. if( pc==cQuote && c!='\r' ){
  18551. utf8_printf(stderr, "%s:%d: unescaped %c character\n",
  18552. p->zFile, p->nLine, cQuote);
  18553. }
  18554. if( c==EOF ){
  18555. utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
  18556. p->zFile, startLine, cQuote);
  18557. p->cTerm = c;
  18558. break;
  18559. }
  18560. import_append_char(p, c);
  18561. ppc = pc;
  18562. pc = c;
  18563. }
  18564. }else{
  18565. /* If this is the first field being parsed and it begins with the
  18566. ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
  18567. if( (c&0xff)==0xef && p->bNotFirst==0 ){
  18568. import_append_char(p, c);
  18569. c = fgetc(p->in);
  18570. if( (c&0xff)==0xbb ){
  18571. import_append_char(p, c);
  18572. c = fgetc(p->in);
  18573. if( (c&0xff)==0xbf ){
  18574. p->bNotFirst = 1;
  18575. p->n = 0;
  18576. return csv_read_one_field(p);
  18577. }
  18578. }
  18579. }
  18580. while( c!=EOF && c!=cSep && c!=rSep ){
  18581. import_append_char(p, c);
  18582. c = fgetc(p->in);
  18583. }
  18584. if( c==rSep ){
  18585. p->nLine++;
  18586. if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
  18587. }
  18588. p->cTerm = c;
  18589. }
  18590. if( p->z ) p->z[p->n] = 0;
  18591. p->bNotFirst = 1;
  18592. return p->z;
  18593. }
  18594. /* Read a single field of ASCII delimited text.
  18595. **
  18596. ** + Input comes from p->in.
  18597. ** + Store results in p->z of length p->n. Space to hold p->z comes
  18598. ** from sqlite3_malloc64().
  18599. ** + Use p->cSep as the column separator. The default is "\x1F".
  18600. ** + Use p->rSep as the row separator. The default is "\x1E".
  18601. ** + Keep track of the row number in p->nLine.
  18602. ** + Store the character that terminates the field in p->cTerm. Store
  18603. ** EOF on end-of-file.
  18604. ** + Report syntax errors on stderr
  18605. */
  18606. static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
  18607. int c;
  18608. int cSep = p->cColSep;
  18609. int rSep = p->cRowSep;
  18610. p->n = 0;
  18611. c = fgetc(p->in);
  18612. if( c==EOF || seenInterrupt ){
  18613. p->cTerm = EOF;
  18614. return 0;
  18615. }
  18616. while( c!=EOF && c!=cSep && c!=rSep ){
  18617. import_append_char(p, c);
  18618. c = fgetc(p->in);
  18619. }
  18620. if( c==rSep ){
  18621. p->nLine++;
  18622. }
  18623. p->cTerm = c;
  18624. if( p->z ) p->z[p->n] = 0;
  18625. return p->z;
  18626. }
  18627. /*
  18628. ** Try to transfer data for table zTable. If an error is seen while
  18629. ** moving forward, try to go backwards. The backwards movement won't
  18630. ** work for WITHOUT ROWID tables.
  18631. */
  18632. static void tryToCloneData(
  18633. ShellState *p,
  18634. sqlite3 *newDb,
  18635. const char *zTable
  18636. ){
  18637. sqlite3_stmt *pQuery = 0;
  18638. sqlite3_stmt *pInsert = 0;
  18639. char *zQuery = 0;
  18640. char *zInsert = 0;
  18641. int rc;
  18642. int i, j, n;
  18643. int nTable = strlen30(zTable);
  18644. int k = 0;
  18645. int cnt = 0;
  18646. const int spinRate = 10000;
  18647. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
  18648. shell_check_oom(zQuery);
  18649. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  18650. if( rc ){
  18651. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  18652. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  18653. zQuery);
  18654. goto end_data_xfer;
  18655. }
  18656. n = sqlite3_column_count(pQuery);
  18657. zInsert = sqlite3_malloc64(200 + nTable + n*3);
  18658. shell_check_oom(zInsert);
  18659. sqlite3_snprintf(200+nTable,zInsert,
  18660. "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
  18661. i = strlen30(zInsert);
  18662. for(j=1; j<n; j++){
  18663. memcpy(zInsert+i, ",?", 2);
  18664. i += 2;
  18665. }
  18666. memcpy(zInsert+i, ");", 3);
  18667. rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
  18668. if( rc ){
  18669. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  18670. sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
  18671. zQuery);
  18672. goto end_data_xfer;
  18673. }
  18674. for(k=0; k<2; k++){
  18675. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  18676. for(i=0; i<n; i++){
  18677. switch( sqlite3_column_type(pQuery, i) ){
  18678. case SQLITE_NULL: {
  18679. sqlite3_bind_null(pInsert, i+1);
  18680. break;
  18681. }
  18682. case SQLITE_INTEGER: {
  18683. sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
  18684. break;
  18685. }
  18686. case SQLITE_FLOAT: {
  18687. sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
  18688. break;
  18689. }
  18690. case SQLITE_TEXT: {
  18691. sqlite3_bind_text(pInsert, i+1,
  18692. (const char*)sqlite3_column_text(pQuery,i),
  18693. -1, SQLITE_STATIC);
  18694. break;
  18695. }
  18696. case SQLITE_BLOB: {
  18697. sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
  18698. sqlite3_column_bytes(pQuery,i),
  18699. SQLITE_STATIC);
  18700. break;
  18701. }
  18702. }
  18703. } /* End for */
  18704. rc = sqlite3_step(pInsert);
  18705. if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  18706. utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
  18707. sqlite3_errmsg(newDb));
  18708. }
  18709. sqlite3_reset(pInsert);
  18710. cnt++;
  18711. if( (cnt%spinRate)==0 ){
  18712. printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
  18713. fflush(stdout);
  18714. }
  18715. } /* End while */
  18716. if( rc==SQLITE_DONE ) break;
  18717. sqlite3_finalize(pQuery);
  18718. sqlite3_free(zQuery);
  18719. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
  18720. zTable);
  18721. shell_check_oom(zQuery);
  18722. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  18723. if( rc ){
  18724. utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
  18725. break;
  18726. }
  18727. } /* End for(k=0...) */
  18728. end_data_xfer:
  18729. sqlite3_finalize(pQuery);
  18730. sqlite3_finalize(pInsert);
  18731. sqlite3_free(zQuery);
  18732. sqlite3_free(zInsert);
  18733. }
  18734. /*
  18735. ** Try to transfer all rows of the schema that match zWhere. For
  18736. ** each row, invoke xForEach() on the object defined by that row.
  18737. ** If an error is encountered while moving forward through the
  18738. ** sqlite_schema table, try again moving backwards.
  18739. */
  18740. static void tryToCloneSchema(
  18741. ShellState *p,
  18742. sqlite3 *newDb,
  18743. const char *zWhere,
  18744. void (*xForEach)(ShellState*,sqlite3*,const char*)
  18745. ){
  18746. sqlite3_stmt *pQuery = 0;
  18747. char *zQuery = 0;
  18748. int rc;
  18749. const unsigned char *zName;
  18750. const unsigned char *zSql;
  18751. char *zErrMsg = 0;
  18752. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
  18753. " WHERE %s", zWhere);
  18754. shell_check_oom(zQuery);
  18755. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  18756. if( rc ){
  18757. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  18758. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  18759. zQuery);
  18760. goto end_schema_xfer;
  18761. }
  18762. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  18763. zName = sqlite3_column_text(pQuery, 0);
  18764. zSql = sqlite3_column_text(pQuery, 1);
  18765. if( zName==0 || zSql==0 ) continue;
  18766. printf("%s... ", zName); fflush(stdout);
  18767. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  18768. if( zErrMsg ){
  18769. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  18770. sqlite3_free(zErrMsg);
  18771. zErrMsg = 0;
  18772. }
  18773. if( xForEach ){
  18774. xForEach(p, newDb, (const char*)zName);
  18775. }
  18776. printf("done\n");
  18777. }
  18778. if( rc!=SQLITE_DONE ){
  18779. sqlite3_finalize(pQuery);
  18780. sqlite3_free(zQuery);
  18781. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
  18782. " WHERE %s ORDER BY rowid DESC", zWhere);
  18783. shell_check_oom(zQuery);
  18784. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  18785. if( rc ){
  18786. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  18787. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  18788. zQuery);
  18789. goto end_schema_xfer;
  18790. }
  18791. while( sqlite3_step(pQuery)==SQLITE_ROW ){
  18792. zName = sqlite3_column_text(pQuery, 0);
  18793. zSql = sqlite3_column_text(pQuery, 1);
  18794. if( zName==0 || zSql==0 ) continue;
  18795. printf("%s... ", zName); fflush(stdout);
  18796. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  18797. if( zErrMsg ){
  18798. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  18799. sqlite3_free(zErrMsg);
  18800. zErrMsg = 0;
  18801. }
  18802. if( xForEach ){
  18803. xForEach(p, newDb, (const char*)zName);
  18804. }
  18805. printf("done\n");
  18806. }
  18807. }
  18808. end_schema_xfer:
  18809. sqlite3_finalize(pQuery);
  18810. sqlite3_free(zQuery);
  18811. }
  18812. /*
  18813. ** Open a new database file named "zNewDb". Try to recover as much information
  18814. ** as possible out of the main database (which might be corrupt) and write it
  18815. ** into zNewDb.
  18816. */
  18817. static void tryToClone(ShellState *p, const char *zNewDb){
  18818. int rc;
  18819. sqlite3 *newDb = 0;
  18820. if( access(zNewDb,0)==0 ){
  18821. utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
  18822. return;
  18823. }
  18824. rc = sqlite3_open(zNewDb, &newDb);
  18825. if( rc ){
  18826. utf8_printf(stderr, "Cannot create output database: %s\n",
  18827. sqlite3_errmsg(newDb));
  18828. }else{
  18829. sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
  18830. sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
  18831. tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
  18832. tryToCloneSchema(p, newDb, "type!='table'", 0);
  18833. sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
  18834. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  18835. }
  18836. close_db(newDb);
  18837. }
  18838. /*
  18839. ** Change the output file back to stdout.
  18840. **
  18841. ** If the p->doXdgOpen flag is set, that means the output was being
  18842. ** redirected to a temporary file named by p->zTempFile. In that case,
  18843. ** launch start/open/xdg-open on that temporary file.
  18844. */
  18845. static void output_reset(ShellState *p){
  18846. if( p->outfile[0]=='|' ){
  18847. #ifndef SQLITE_OMIT_POPEN
  18848. pclose(p->out);
  18849. #endif
  18850. }else{
  18851. output_file_close(p->out);
  18852. #ifndef SQLITE_NOHAVE_SYSTEM
  18853. if( p->doXdgOpen ){
  18854. const char *zXdgOpenCmd =
  18855. #if defined(_WIN32)
  18856. "start";
  18857. #elif defined(__APPLE__)
  18858. "open";
  18859. #else
  18860. "xdg-open";
  18861. #endif
  18862. char *zCmd;
  18863. zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
  18864. if( system(zCmd) ){
  18865. utf8_printf(stderr, "Failed: [%s]\n", zCmd);
  18866. }else{
  18867. /* Give the start/open/xdg-open command some time to get
  18868. ** going before we continue, and potential delete the
  18869. ** p->zTempFile data file out from under it */
  18870. sqlite3_sleep(2000);
  18871. }
  18872. sqlite3_free(zCmd);
  18873. outputModePop(p);
  18874. p->doXdgOpen = 0;
  18875. }
  18876. #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
  18877. }
  18878. p->outfile[0] = 0;
  18879. p->out = stdout;
  18880. }
  18881. /*
  18882. ** Run an SQL command and return the single integer result.
  18883. */
  18884. static int db_int(sqlite3 *db, const char *zSql){
  18885. sqlite3_stmt *pStmt;
  18886. int res = 0;
  18887. sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  18888. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  18889. res = sqlite3_column_int(pStmt,0);
  18890. }
  18891. sqlite3_finalize(pStmt);
  18892. return res;
  18893. }
  18894. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
  18895. /*
  18896. ** Convert a 2-byte or 4-byte big-endian integer into a native integer
  18897. */
  18898. static unsigned int get2byteInt(unsigned char *a){
  18899. return (a[0]<<8) + a[1];
  18900. }
  18901. static unsigned int get4byteInt(unsigned char *a){
  18902. return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
  18903. }
  18904. /*
  18905. ** Implementation of the ".dbinfo" command.
  18906. **
  18907. ** Return 1 on error, 2 to exit, and 0 otherwise.
  18908. */
  18909. static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
  18910. static const struct { const char *zName; int ofst; } aField[] = {
  18911. { "file change counter:", 24 },
  18912. { "database page count:", 28 },
  18913. { "freelist page count:", 36 },
  18914. { "schema cookie:", 40 },
  18915. { "schema format:", 44 },
  18916. { "default cache size:", 48 },
  18917. { "autovacuum top root:", 52 },
  18918. { "incremental vacuum:", 64 },
  18919. { "text encoding:", 56 },
  18920. { "user version:", 60 },
  18921. { "application id:", 68 },
  18922. { "software version:", 96 },
  18923. };
  18924. static const struct { const char *zName; const char *zSql; } aQuery[] = {
  18925. { "number of tables:",
  18926. "SELECT count(*) FROM %s WHERE type='table'" },
  18927. { "number of indexes:",
  18928. "SELECT count(*) FROM %s WHERE type='index'" },
  18929. { "number of triggers:",
  18930. "SELECT count(*) FROM %s WHERE type='trigger'" },
  18931. { "number of views:",
  18932. "SELECT count(*) FROM %s WHERE type='view'" },
  18933. { "schema size:",
  18934. "SELECT total(length(sql)) FROM %s" },
  18935. };
  18936. int i, rc;
  18937. unsigned iDataVersion;
  18938. char *zSchemaTab;
  18939. char *zDb = nArg>=2 ? azArg[1] : "main";
  18940. sqlite3_stmt *pStmt = 0;
  18941. unsigned char aHdr[100];
  18942. open_db(p, 0);
  18943. if( p->db==0 ) return 1;
  18944. rc = sqlite3_prepare_v2(p->db,
  18945. "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
  18946. -1, &pStmt, 0);
  18947. if( rc ){
  18948. utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
  18949. sqlite3_finalize(pStmt);
  18950. return 1;
  18951. }
  18952. sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
  18953. if( sqlite3_step(pStmt)==SQLITE_ROW
  18954. && sqlite3_column_bytes(pStmt,0)>100
  18955. ){
  18956. memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
  18957. sqlite3_finalize(pStmt);
  18958. }else{
  18959. raw_printf(stderr, "unable to read database header\n");
  18960. sqlite3_finalize(pStmt);
  18961. return 1;
  18962. }
  18963. i = get2byteInt(aHdr+16);
  18964. if( i==1 ) i = 65536;
  18965. utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
  18966. utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
  18967. utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
  18968. utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
  18969. for(i=0; i<ArraySize(aField); i++){
  18970. int ofst = aField[i].ofst;
  18971. unsigned int val = get4byteInt(aHdr + ofst);
  18972. utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
  18973. switch( ofst ){
  18974. case 56: {
  18975. if( val==1 ) raw_printf(p->out, " (utf8)");
  18976. if( val==2 ) raw_printf(p->out, " (utf16le)");
  18977. if( val==3 ) raw_printf(p->out, " (utf16be)");
  18978. }
  18979. }
  18980. raw_printf(p->out, "\n");
  18981. }
  18982. if( zDb==0 ){
  18983. zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
  18984. }else if( cli_strcmp(zDb,"temp")==0 ){
  18985. zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
  18986. }else{
  18987. zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
  18988. }
  18989. for(i=0; i<ArraySize(aQuery); i++){
  18990. char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
  18991. int val = db_int(p->db, zSql);
  18992. sqlite3_free(zSql);
  18993. utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
  18994. }
  18995. sqlite3_free(zSchemaTab);
  18996. sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
  18997. utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
  18998. return 0;
  18999. }
  19000. #endif /* SQLITE_SHELL_HAVE_RECOVER */
  19001. /*
  19002. ** Print the current sqlite3_errmsg() value to stderr and return 1.
  19003. */
  19004. static int shellDatabaseError(sqlite3 *db){
  19005. const char *zErr = sqlite3_errmsg(db);
  19006. utf8_printf(stderr, "Error: %s\n", zErr);
  19007. return 1;
  19008. }
  19009. /*
  19010. ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
  19011. ** if they match and FALSE (0) if they do not match.
  19012. **
  19013. ** Globbing rules:
  19014. **
  19015. ** '*' Matches any sequence of zero or more characters.
  19016. **
  19017. ** '?' Matches exactly one character.
  19018. **
  19019. ** [...] Matches one character from the enclosed list of
  19020. ** characters.
  19021. **
  19022. ** [^...] Matches one character not in the enclosed list.
  19023. **
  19024. ** '#' Matches any sequence of one or more digits with an
  19025. ** optional + or - sign in front
  19026. **
  19027. ** ' ' Any span of whitespace matches any other span of
  19028. ** whitespace.
  19029. **
  19030. ** Extra whitespace at the end of z[] is ignored.
  19031. */
  19032. static int testcase_glob(const char *zGlob, const char *z){
  19033. int c, c2;
  19034. int invert;
  19035. int seen;
  19036. while( (c = (*(zGlob++)))!=0 ){
  19037. if( IsSpace(c) ){
  19038. if( !IsSpace(*z) ) return 0;
  19039. while( IsSpace(*zGlob) ) zGlob++;
  19040. while( IsSpace(*z) ) z++;
  19041. }else if( c=='*' ){
  19042. while( (c=(*(zGlob++))) == '*' || c=='?' ){
  19043. if( c=='?' && (*(z++))==0 ) return 0;
  19044. }
  19045. if( c==0 ){
  19046. return 1;
  19047. }else if( c=='[' ){
  19048. while( *z && testcase_glob(zGlob-1,z)==0 ){
  19049. z++;
  19050. }
  19051. return (*z)!=0;
  19052. }
  19053. while( (c2 = (*(z++)))!=0 ){
  19054. while( c2!=c ){
  19055. c2 = *(z++);
  19056. if( c2==0 ) return 0;
  19057. }
  19058. if( testcase_glob(zGlob,z) ) return 1;
  19059. }
  19060. return 0;
  19061. }else if( c=='?' ){
  19062. if( (*(z++))==0 ) return 0;
  19063. }else if( c=='[' ){
  19064. int prior_c = 0;
  19065. seen = 0;
  19066. invert = 0;
  19067. c = *(z++);
  19068. if( c==0 ) return 0;
  19069. c2 = *(zGlob++);
  19070. if( c2=='^' ){
  19071. invert = 1;
  19072. c2 = *(zGlob++);
  19073. }
  19074. if( c2==']' ){
  19075. if( c==']' ) seen = 1;
  19076. c2 = *(zGlob++);
  19077. }
  19078. while( c2 && c2!=']' ){
  19079. if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
  19080. c2 = *(zGlob++);
  19081. if( c>=prior_c && c<=c2 ) seen = 1;
  19082. prior_c = 0;
  19083. }else{
  19084. if( c==c2 ){
  19085. seen = 1;
  19086. }
  19087. prior_c = c2;
  19088. }
  19089. c2 = *(zGlob++);
  19090. }
  19091. if( c2==0 || (seen ^ invert)==0 ) return 0;
  19092. }else if( c=='#' ){
  19093. if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
  19094. if( !IsDigit(z[0]) ) return 0;
  19095. z++;
  19096. while( IsDigit(z[0]) ){ z++; }
  19097. }else{
  19098. if( c!=(*(z++)) ) return 0;
  19099. }
  19100. }
  19101. while( IsSpace(*z) ){ z++; }
  19102. return *z==0;
  19103. }
  19104. /*
  19105. ** Compare the string as a command-line option with either one or two
  19106. ** initial "-" characters.
  19107. */
  19108. static int optionMatch(const char *zStr, const char *zOpt){
  19109. if( zStr[0]!='-' ) return 0;
  19110. zStr++;
  19111. if( zStr[0]=='-' ) zStr++;
  19112. return cli_strcmp(zStr, zOpt)==0;
  19113. }
  19114. /*
  19115. ** Delete a file.
  19116. */
  19117. int shellDeleteFile(const char *zFilename){
  19118. int rc;
  19119. #ifdef _WIN32
  19120. wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
  19121. rc = _wunlink(z);
  19122. sqlite3_free(z);
  19123. #else
  19124. rc = unlink(zFilename);
  19125. #endif
  19126. return rc;
  19127. }
  19128. /*
  19129. ** Try to delete the temporary file (if there is one) and free the
  19130. ** memory used to hold the name of the temp file.
  19131. */
  19132. static void clearTempFile(ShellState *p){
  19133. if( p->zTempFile==0 ) return;
  19134. if( p->doXdgOpen ) return;
  19135. if( shellDeleteFile(p->zTempFile) ) return;
  19136. sqlite3_free(p->zTempFile);
  19137. p->zTempFile = 0;
  19138. }
  19139. /*
  19140. ** Create a new temp file name with the given suffix.
  19141. */
  19142. static void newTempFile(ShellState *p, const char *zSuffix){
  19143. clearTempFile(p);
  19144. sqlite3_free(p->zTempFile);
  19145. p->zTempFile = 0;
  19146. if( p->db ){
  19147. sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
  19148. }
  19149. if( p->zTempFile==0 ){
  19150. /* If p->db is an in-memory database then the TEMPFILENAME file-control
  19151. ** will not work and we will need to fallback to guessing */
  19152. char *zTemp;
  19153. sqlite3_uint64 r;
  19154. sqlite3_randomness(sizeof(r), &r);
  19155. zTemp = getenv("TEMP");
  19156. if( zTemp==0 ) zTemp = getenv("TMP");
  19157. if( zTemp==0 ){
  19158. #ifdef _WIN32
  19159. zTemp = "\\tmp";
  19160. #else
  19161. zTemp = "/tmp";
  19162. #endif
  19163. }
  19164. p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
  19165. }else{
  19166. p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
  19167. }
  19168. shell_check_oom(p->zTempFile);
  19169. }
  19170. /*
  19171. ** The implementation of SQL scalar function fkey_collate_clause(), used
  19172. ** by the ".lint fkey-indexes" command. This scalar function is always
  19173. ** called with four arguments - the parent table name, the parent column name,
  19174. ** the child table name and the child column name.
  19175. **
  19176. ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
  19177. **
  19178. ** If either of the named tables or columns do not exist, this function
  19179. ** returns an empty string. An empty string is also returned if both tables
  19180. ** and columns exist but have the same default collation sequence. Or,
  19181. ** if both exist but the default collation sequences are different, this
  19182. ** function returns the string " COLLATE <parent-collation>", where
  19183. ** <parent-collation> is the default collation sequence of the parent column.
  19184. */
  19185. static void shellFkeyCollateClause(
  19186. sqlite3_context *pCtx,
  19187. int nVal,
  19188. sqlite3_value **apVal
  19189. ){
  19190. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  19191. const char *zParent;
  19192. const char *zParentCol;
  19193. const char *zParentSeq;
  19194. const char *zChild;
  19195. const char *zChildCol;
  19196. const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
  19197. int rc;
  19198. assert( nVal==4 );
  19199. zParent = (const char*)sqlite3_value_text(apVal[0]);
  19200. zParentCol = (const char*)sqlite3_value_text(apVal[1]);
  19201. zChild = (const char*)sqlite3_value_text(apVal[2]);
  19202. zChildCol = (const char*)sqlite3_value_text(apVal[3]);
  19203. sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
  19204. rc = sqlite3_table_column_metadata(
  19205. db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
  19206. );
  19207. if( rc==SQLITE_OK ){
  19208. rc = sqlite3_table_column_metadata(
  19209. db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
  19210. );
  19211. }
  19212. if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
  19213. char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
  19214. sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
  19215. sqlite3_free(z);
  19216. }
  19217. }
  19218. /*
  19219. ** The implementation of dot-command ".lint fkey-indexes".
  19220. */
  19221. static int lintFkeyIndexes(
  19222. ShellState *pState, /* Current shell tool state */
  19223. char **azArg, /* Array of arguments passed to dot command */
  19224. int nArg /* Number of entries in azArg[] */
  19225. ){
  19226. sqlite3 *db = pState->db; /* Database handle to query "main" db of */
  19227. FILE *out = pState->out; /* Stream to write non-error output to */
  19228. int bVerbose = 0; /* If -verbose is present */
  19229. int bGroupByParent = 0; /* If -groupbyparent is present */
  19230. int i; /* To iterate through azArg[] */
  19231. const char *zIndent = ""; /* How much to indent CREATE INDEX by */
  19232. int rc; /* Return code */
  19233. sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
  19234. /*
  19235. ** This SELECT statement returns one row for each foreign key constraint
  19236. ** in the schema of the main database. The column values are:
  19237. **
  19238. ** 0. The text of an SQL statement similar to:
  19239. **
  19240. ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
  19241. **
  19242. ** This SELECT is similar to the one that the foreign keys implementation
  19243. ** needs to run internally on child tables. If there is an index that can
  19244. ** be used to optimize this query, then it can also be used by the FK
  19245. ** implementation to optimize DELETE or UPDATE statements on the parent
  19246. ** table.
  19247. **
  19248. ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
  19249. ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
  19250. ** contains an index that can be used to optimize the query.
  19251. **
  19252. ** 2. Human readable text that describes the child table and columns. e.g.
  19253. **
  19254. ** "child_table(child_key1, child_key2)"
  19255. **
  19256. ** 3. Human readable text that describes the parent table and columns. e.g.
  19257. **
  19258. ** "parent_table(parent_key1, parent_key2)"
  19259. **
  19260. ** 4. A full CREATE INDEX statement for an index that could be used to
  19261. ** optimize DELETE or UPDATE statements on the parent table. e.g.
  19262. **
  19263. ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
  19264. **
  19265. ** 5. The name of the parent table.
  19266. **
  19267. ** These six values are used by the C logic below to generate the report.
  19268. */
  19269. const char *zSql =
  19270. "SELECT "
  19271. " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
  19272. " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
  19273. " || fkey_collate_clause("
  19274. " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
  19275. ", "
  19276. " 'SEARCH ' || s.name || ' USING COVERING INDEX*('"
  19277. " || group_concat('*=?', ' AND ') || ')'"
  19278. ", "
  19279. " s.name || '(' || group_concat(f.[from], ', ') || ')'"
  19280. ", "
  19281. " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
  19282. ", "
  19283. " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
  19284. " || ' ON ' || quote(s.name) || '('"
  19285. " || group_concat(quote(f.[from]) ||"
  19286. " fkey_collate_clause("
  19287. " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
  19288. " || ');'"
  19289. ", "
  19290. " f.[table] "
  19291. "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
  19292. "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
  19293. "GROUP BY s.name, f.id "
  19294. "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
  19295. ;
  19296. const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
  19297. for(i=2; i<nArg; i++){
  19298. int n = strlen30(azArg[i]);
  19299. if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
  19300. bVerbose = 1;
  19301. }
  19302. else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
  19303. bGroupByParent = 1;
  19304. zIndent = " ";
  19305. }
  19306. else{
  19307. raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
  19308. azArg[0], azArg[1]
  19309. );
  19310. return SQLITE_ERROR;
  19311. }
  19312. }
  19313. /* Register the fkey_collate_clause() SQL function */
  19314. rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
  19315. 0, shellFkeyCollateClause, 0, 0
  19316. );
  19317. if( rc==SQLITE_OK ){
  19318. rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
  19319. }
  19320. if( rc==SQLITE_OK ){
  19321. sqlite3_bind_int(pSql, 1, bGroupByParent);
  19322. }
  19323. if( rc==SQLITE_OK ){
  19324. int rc2;
  19325. char *zPrev = 0;
  19326. while( SQLITE_ROW==sqlite3_step(pSql) ){
  19327. int res = -1;
  19328. sqlite3_stmt *pExplain = 0;
  19329. const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
  19330. const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
  19331. const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
  19332. const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
  19333. const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
  19334. const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
  19335. if( zEQP==0 ) continue;
  19336. if( zGlob==0 ) continue;
  19337. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  19338. if( rc!=SQLITE_OK ) break;
  19339. if( SQLITE_ROW==sqlite3_step(pExplain) ){
  19340. const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
  19341. res = zPlan!=0 && ( 0==sqlite3_strglob(zGlob, zPlan)
  19342. || 0==sqlite3_strglob(zGlobIPK, zPlan));
  19343. }
  19344. rc = sqlite3_finalize(pExplain);
  19345. if( rc!=SQLITE_OK ) break;
  19346. if( res<0 ){
  19347. raw_printf(stderr, "Error: internal error");
  19348. break;
  19349. }else{
  19350. if( bGroupByParent
  19351. && (bVerbose || res==0)
  19352. && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
  19353. ){
  19354. raw_printf(out, "-- Parent table %s\n", zParent);
  19355. sqlite3_free(zPrev);
  19356. zPrev = sqlite3_mprintf("%s", zParent);
  19357. }
  19358. if( res==0 ){
  19359. raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
  19360. }else if( bVerbose ){
  19361. raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
  19362. zIndent, zFrom, zTarget
  19363. );
  19364. }
  19365. }
  19366. }
  19367. sqlite3_free(zPrev);
  19368. if( rc!=SQLITE_OK ){
  19369. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  19370. }
  19371. rc2 = sqlite3_finalize(pSql);
  19372. if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
  19373. rc = rc2;
  19374. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  19375. }
  19376. }else{
  19377. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  19378. }
  19379. return rc;
  19380. }
  19381. /*
  19382. ** Implementation of ".lint" dot command.
  19383. */
  19384. static int lintDotCommand(
  19385. ShellState *pState, /* Current shell tool state */
  19386. char **azArg, /* Array of arguments passed to dot command */
  19387. int nArg /* Number of entries in azArg[] */
  19388. ){
  19389. int n;
  19390. n = (nArg>=2 ? strlen30(azArg[1]) : 0);
  19391. if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
  19392. return lintFkeyIndexes(pState, azArg, nArg);
  19393. usage:
  19394. raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
  19395. raw_printf(stderr, "Where sub-commands are:\n");
  19396. raw_printf(stderr, " fkey-indexes\n");
  19397. return SQLITE_ERROR;
  19398. }
  19399. #if !defined SQLITE_OMIT_VIRTUALTABLE
  19400. static void shellPrepare(
  19401. sqlite3 *db,
  19402. int *pRc,
  19403. const char *zSql,
  19404. sqlite3_stmt **ppStmt
  19405. ){
  19406. *ppStmt = 0;
  19407. if( *pRc==SQLITE_OK ){
  19408. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  19409. if( rc!=SQLITE_OK ){
  19410. raw_printf(stderr, "sql error: %s (%d)\n",
  19411. sqlite3_errmsg(db), sqlite3_errcode(db)
  19412. );
  19413. *pRc = rc;
  19414. }
  19415. }
  19416. }
  19417. /*
  19418. ** Create a prepared statement using printf-style arguments for the SQL.
  19419. **
  19420. ** This routine is could be marked "static". But it is not always used,
  19421. ** depending on compile-time options. By omitting the "static", we avoid
  19422. ** nuisance compiler warnings about "defined but not used".
  19423. */
  19424. void shellPreparePrintf(
  19425. sqlite3 *db,
  19426. int *pRc,
  19427. sqlite3_stmt **ppStmt,
  19428. const char *zFmt,
  19429. ...
  19430. ){
  19431. *ppStmt = 0;
  19432. if( *pRc==SQLITE_OK ){
  19433. va_list ap;
  19434. char *z;
  19435. va_start(ap, zFmt);
  19436. z = sqlite3_vmprintf(zFmt, ap);
  19437. va_end(ap);
  19438. if( z==0 ){
  19439. *pRc = SQLITE_NOMEM;
  19440. }else{
  19441. shellPrepare(db, pRc, z, ppStmt);
  19442. sqlite3_free(z);
  19443. }
  19444. }
  19445. }
  19446. /* Finalize the prepared statement created using shellPreparePrintf().
  19447. **
  19448. ** This routine is could be marked "static". But it is not always used,
  19449. ** depending on compile-time options. By omitting the "static", we avoid
  19450. ** nuisance compiler warnings about "defined but not used".
  19451. */
  19452. void shellFinalize(
  19453. int *pRc,
  19454. sqlite3_stmt *pStmt
  19455. ){
  19456. if( pStmt ){
  19457. sqlite3 *db = sqlite3_db_handle(pStmt);
  19458. int rc = sqlite3_finalize(pStmt);
  19459. if( *pRc==SQLITE_OK ){
  19460. if( rc!=SQLITE_OK ){
  19461. raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
  19462. }
  19463. *pRc = rc;
  19464. }
  19465. }
  19466. }
  19467. /* Reset the prepared statement created using shellPreparePrintf().
  19468. **
  19469. ** This routine is could be marked "static". But it is not always used,
  19470. ** depending on compile-time options. By omitting the "static", we avoid
  19471. ** nuisance compiler warnings about "defined but not used".
  19472. */
  19473. void shellReset(
  19474. int *pRc,
  19475. sqlite3_stmt *pStmt
  19476. ){
  19477. int rc = sqlite3_reset(pStmt);
  19478. if( *pRc==SQLITE_OK ){
  19479. if( rc!=SQLITE_OK ){
  19480. sqlite3 *db = sqlite3_db_handle(pStmt);
  19481. raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
  19482. }
  19483. *pRc = rc;
  19484. }
  19485. }
  19486. #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
  19487. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  19488. /******************************************************************************
  19489. ** The ".archive" or ".ar" command.
  19490. */
  19491. /*
  19492. ** Structure representing a single ".ar" command.
  19493. */
  19494. typedef struct ArCommand ArCommand;
  19495. struct ArCommand {
  19496. u8 eCmd; /* An AR_CMD_* value */
  19497. u8 bVerbose; /* True if --verbose */
  19498. u8 bZip; /* True if the archive is a ZIP */
  19499. u8 bDryRun; /* True if --dry-run */
  19500. u8 bAppend; /* True if --append */
  19501. u8 bGlob; /* True if --glob */
  19502. u8 fromCmdLine; /* Run from -A instead of .archive */
  19503. int nArg; /* Number of command arguments */
  19504. char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
  19505. const char *zFile; /* --file argument, or NULL */
  19506. const char *zDir; /* --directory argument, or NULL */
  19507. char **azArg; /* Array of command arguments */
  19508. ShellState *p; /* Shell state */
  19509. sqlite3 *db; /* Database containing the archive */
  19510. };
  19511. /*
  19512. ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
  19513. */
  19514. static int arUsage(FILE *f){
  19515. showHelp(f,"archive");
  19516. return SQLITE_ERROR;
  19517. }
  19518. /*
  19519. ** Print an error message for the .ar command to stderr and return
  19520. ** SQLITE_ERROR.
  19521. */
  19522. static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
  19523. va_list ap;
  19524. char *z;
  19525. va_start(ap, zFmt);
  19526. z = sqlite3_vmprintf(zFmt, ap);
  19527. va_end(ap);
  19528. utf8_printf(stderr, "Error: %s\n", z);
  19529. if( pAr->fromCmdLine ){
  19530. utf8_printf(stderr, "Use \"-A\" for more help\n");
  19531. }else{
  19532. utf8_printf(stderr, "Use \".archive --help\" for more help\n");
  19533. }
  19534. sqlite3_free(z);
  19535. return SQLITE_ERROR;
  19536. }
  19537. /*
  19538. ** Values for ArCommand.eCmd.
  19539. */
  19540. #define AR_CMD_CREATE 1
  19541. #define AR_CMD_UPDATE 2
  19542. #define AR_CMD_INSERT 3
  19543. #define AR_CMD_EXTRACT 4
  19544. #define AR_CMD_LIST 5
  19545. #define AR_CMD_HELP 6
  19546. #define AR_CMD_REMOVE 7
  19547. /*
  19548. ** Other (non-command) switches.
  19549. */
  19550. #define AR_SWITCH_VERBOSE 8
  19551. #define AR_SWITCH_FILE 9
  19552. #define AR_SWITCH_DIRECTORY 10
  19553. #define AR_SWITCH_APPEND 11
  19554. #define AR_SWITCH_DRYRUN 12
  19555. #define AR_SWITCH_GLOB 13
  19556. static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
  19557. switch( eSwitch ){
  19558. case AR_CMD_CREATE:
  19559. case AR_CMD_EXTRACT:
  19560. case AR_CMD_LIST:
  19561. case AR_CMD_REMOVE:
  19562. case AR_CMD_UPDATE:
  19563. case AR_CMD_INSERT:
  19564. case AR_CMD_HELP:
  19565. if( pAr->eCmd ){
  19566. return arErrorMsg(pAr, "multiple command options");
  19567. }
  19568. pAr->eCmd = eSwitch;
  19569. break;
  19570. case AR_SWITCH_DRYRUN:
  19571. pAr->bDryRun = 1;
  19572. break;
  19573. case AR_SWITCH_GLOB:
  19574. pAr->bGlob = 1;
  19575. break;
  19576. case AR_SWITCH_VERBOSE:
  19577. pAr->bVerbose = 1;
  19578. break;
  19579. case AR_SWITCH_APPEND:
  19580. pAr->bAppend = 1;
  19581. /* Fall thru into --file */
  19582. case AR_SWITCH_FILE:
  19583. pAr->zFile = zArg;
  19584. break;
  19585. case AR_SWITCH_DIRECTORY:
  19586. pAr->zDir = zArg;
  19587. break;
  19588. }
  19589. return SQLITE_OK;
  19590. }
  19591. /*
  19592. ** Parse the command line for an ".ar" command. The results are written into
  19593. ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
  19594. ** successfully, otherwise an error message is written to stderr and
  19595. ** SQLITE_ERROR returned.
  19596. */
  19597. static int arParseCommand(
  19598. char **azArg, /* Array of arguments passed to dot command */
  19599. int nArg, /* Number of entries in azArg[] */
  19600. ArCommand *pAr /* Populate this object */
  19601. ){
  19602. struct ArSwitch {
  19603. const char *zLong;
  19604. char cShort;
  19605. u8 eSwitch;
  19606. u8 bArg;
  19607. } aSwitch[] = {
  19608. { "create", 'c', AR_CMD_CREATE, 0 },
  19609. { "extract", 'x', AR_CMD_EXTRACT, 0 },
  19610. { "insert", 'i', AR_CMD_INSERT, 0 },
  19611. { "list", 't', AR_CMD_LIST, 0 },
  19612. { "remove", 'r', AR_CMD_REMOVE, 0 },
  19613. { "update", 'u', AR_CMD_UPDATE, 0 },
  19614. { "help", 'h', AR_CMD_HELP, 0 },
  19615. { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
  19616. { "file", 'f', AR_SWITCH_FILE, 1 },
  19617. { "append", 'a', AR_SWITCH_APPEND, 1 },
  19618. { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
  19619. { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
  19620. { "glob", 'g', AR_SWITCH_GLOB, 0 },
  19621. };
  19622. int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
  19623. struct ArSwitch *pEnd = &aSwitch[nSwitch];
  19624. if( nArg<=1 ){
  19625. utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
  19626. return arUsage(stderr);
  19627. }else{
  19628. char *z = azArg[1];
  19629. if( z[0]!='-' ){
  19630. /* Traditional style [tar] invocation */
  19631. int i;
  19632. int iArg = 2;
  19633. for(i=0; z[i]; i++){
  19634. const char *zArg = 0;
  19635. struct ArSwitch *pOpt;
  19636. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  19637. if( z[i]==pOpt->cShort ) break;
  19638. }
  19639. if( pOpt==pEnd ){
  19640. return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
  19641. }
  19642. if( pOpt->bArg ){
  19643. if( iArg>=nArg ){
  19644. return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
  19645. }
  19646. zArg = azArg[iArg++];
  19647. }
  19648. if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
  19649. }
  19650. pAr->nArg = nArg-iArg;
  19651. if( pAr->nArg>0 ){
  19652. pAr->azArg = &azArg[iArg];
  19653. }
  19654. }else{
  19655. /* Non-traditional invocation */
  19656. int iArg;
  19657. for(iArg=1; iArg<nArg; iArg++){
  19658. int n;
  19659. z = azArg[iArg];
  19660. if( z[0]!='-' ){
  19661. /* All remaining command line words are command arguments. */
  19662. pAr->azArg = &azArg[iArg];
  19663. pAr->nArg = nArg-iArg;
  19664. break;
  19665. }
  19666. n = strlen30(z);
  19667. if( z[1]!='-' ){
  19668. int i;
  19669. /* One or more short options */
  19670. for(i=1; i<n; i++){
  19671. const char *zArg = 0;
  19672. struct ArSwitch *pOpt;
  19673. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  19674. if( z[i]==pOpt->cShort ) break;
  19675. }
  19676. if( pOpt==pEnd ){
  19677. return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
  19678. }
  19679. if( pOpt->bArg ){
  19680. if( i<(n-1) ){
  19681. zArg = &z[i+1];
  19682. i = n;
  19683. }else{
  19684. if( iArg>=(nArg-1) ){
  19685. return arErrorMsg(pAr, "option requires an argument: %c",
  19686. z[i]);
  19687. }
  19688. zArg = azArg[++iArg];
  19689. }
  19690. }
  19691. if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
  19692. }
  19693. }else if( z[2]=='\0' ){
  19694. /* A -- option, indicating that all remaining command line words
  19695. ** are command arguments. */
  19696. pAr->azArg = &azArg[iArg+1];
  19697. pAr->nArg = nArg-iArg-1;
  19698. break;
  19699. }else{
  19700. /* A long option */
  19701. const char *zArg = 0; /* Argument for option, if any */
  19702. struct ArSwitch *pMatch = 0; /* Matching option */
  19703. struct ArSwitch *pOpt; /* Iterator */
  19704. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  19705. const char *zLong = pOpt->zLong;
  19706. if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
  19707. if( pMatch ){
  19708. return arErrorMsg(pAr, "ambiguous option: %s",z);
  19709. }else{
  19710. pMatch = pOpt;
  19711. }
  19712. }
  19713. }
  19714. if( pMatch==0 ){
  19715. return arErrorMsg(pAr, "unrecognized option: %s", z);
  19716. }
  19717. if( pMatch->bArg ){
  19718. if( iArg>=(nArg-1) ){
  19719. return arErrorMsg(pAr, "option requires an argument: %s", z);
  19720. }
  19721. zArg = azArg[++iArg];
  19722. }
  19723. if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
  19724. }
  19725. }
  19726. }
  19727. }
  19728. return SQLITE_OK;
  19729. }
  19730. /*
  19731. ** This function assumes that all arguments within the ArCommand.azArg[]
  19732. ** array refer to archive members, as for the --extract, --list or --remove
  19733. ** commands. It checks that each of them are "present". If any specified
  19734. ** file is not present in the archive, an error is printed to stderr and an
  19735. ** error code returned. Otherwise, if all specified arguments are present
  19736. ** in the archive, SQLITE_OK is returned. Here, "present" means either an
  19737. ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
  19738. ** when pAr->bGlob is true.
  19739. **
  19740. ** This function strips any trailing '/' characters from each argument.
  19741. ** This is consistent with the way the [tar] command seems to work on
  19742. ** Linux.
  19743. */
  19744. static int arCheckEntries(ArCommand *pAr){
  19745. int rc = SQLITE_OK;
  19746. if( pAr->nArg ){
  19747. int i, j;
  19748. sqlite3_stmt *pTest = 0;
  19749. const char *zSel = (pAr->bGlob)
  19750. ? "SELECT name FROM %s WHERE glob($name,name)"
  19751. : "SELECT name FROM %s WHERE name=$name";
  19752. shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
  19753. j = sqlite3_bind_parameter_index(pTest, "$name");
  19754. for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
  19755. char *z = pAr->azArg[i];
  19756. int n = strlen30(z);
  19757. int bOk = 0;
  19758. while( n>0 && z[n-1]=='/' ) n--;
  19759. z[n] = '\0';
  19760. sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
  19761. if( SQLITE_ROW==sqlite3_step(pTest) ){
  19762. bOk = 1;
  19763. }
  19764. shellReset(&rc, pTest);
  19765. if( rc==SQLITE_OK && bOk==0 ){
  19766. utf8_printf(stderr, "not found in archive: %s\n", z);
  19767. rc = SQLITE_ERROR;
  19768. }
  19769. }
  19770. shellFinalize(&rc, pTest);
  19771. }
  19772. return rc;
  19773. }
  19774. /*
  19775. ** Format a WHERE clause that can be used against the "sqlar" table to
  19776. ** identify all archive members that match the command arguments held
  19777. ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
  19778. ** The caller is responsible for eventually calling sqlite3_free() on
  19779. ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
  19780. ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
  19781. */
  19782. static void arWhereClause(
  19783. int *pRc,
  19784. ArCommand *pAr,
  19785. char **pzWhere /* OUT: New WHERE clause */
  19786. ){
  19787. char *zWhere = 0;
  19788. const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
  19789. if( *pRc==SQLITE_OK ){
  19790. if( pAr->nArg==0 ){
  19791. zWhere = sqlite3_mprintf("1");
  19792. }else{
  19793. int i;
  19794. const char *zSep = "";
  19795. for(i=0; i<pAr->nArg; i++){
  19796. const char *z = pAr->azArg[i];
  19797. zWhere = sqlite3_mprintf(
  19798. "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
  19799. zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
  19800. );
  19801. if( zWhere==0 ){
  19802. *pRc = SQLITE_NOMEM;
  19803. break;
  19804. }
  19805. zSep = " OR ";
  19806. }
  19807. }
  19808. }
  19809. *pzWhere = zWhere;
  19810. }
  19811. /*
  19812. ** Implementation of .ar "lisT" command.
  19813. */
  19814. static int arListCommand(ArCommand *pAr){
  19815. const char *zSql = "SELECT %s FROM %s WHERE %s";
  19816. const char *azCols[] = {
  19817. "name",
  19818. "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
  19819. };
  19820. char *zWhere = 0;
  19821. sqlite3_stmt *pSql = 0;
  19822. int rc;
  19823. rc = arCheckEntries(pAr);
  19824. arWhereClause(&rc, pAr, &zWhere);
  19825. shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
  19826. pAr->zSrcTable, zWhere);
  19827. if( pAr->bDryRun ){
  19828. utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
  19829. }else{
  19830. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  19831. if( pAr->bVerbose ){
  19832. utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
  19833. sqlite3_column_text(pSql, 0),
  19834. sqlite3_column_int(pSql, 1),
  19835. sqlite3_column_text(pSql, 2),
  19836. sqlite3_column_text(pSql, 3)
  19837. );
  19838. }else{
  19839. utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
  19840. }
  19841. }
  19842. }
  19843. shellFinalize(&rc, pSql);
  19844. sqlite3_free(zWhere);
  19845. return rc;
  19846. }
  19847. /*
  19848. ** Implementation of .ar "Remove" command.
  19849. */
  19850. static int arRemoveCommand(ArCommand *pAr){
  19851. int rc = 0;
  19852. char *zSql = 0;
  19853. char *zWhere = 0;
  19854. if( pAr->nArg ){
  19855. /* Verify that args actually exist within the archive before proceeding.
  19856. ** And formulate a WHERE clause to match them. */
  19857. rc = arCheckEntries(pAr);
  19858. arWhereClause(&rc, pAr, &zWhere);
  19859. }
  19860. if( rc==SQLITE_OK ){
  19861. zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
  19862. pAr->zSrcTable, zWhere);
  19863. if( pAr->bDryRun ){
  19864. utf8_printf(pAr->p->out, "%s\n", zSql);
  19865. }else{
  19866. char *zErr = 0;
  19867. rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
  19868. if( rc==SQLITE_OK ){
  19869. rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
  19870. if( rc!=SQLITE_OK ){
  19871. sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
  19872. }else{
  19873. rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
  19874. }
  19875. }
  19876. if( zErr ){
  19877. utf8_printf(stdout, "ERROR: %s\n", zErr);
  19878. sqlite3_free(zErr);
  19879. }
  19880. }
  19881. }
  19882. sqlite3_free(zWhere);
  19883. sqlite3_free(zSql);
  19884. return rc;
  19885. }
  19886. /*
  19887. ** Implementation of .ar "eXtract" command.
  19888. */
  19889. static int arExtractCommand(ArCommand *pAr){
  19890. const char *zSql1 =
  19891. "SELECT "
  19892. " ($dir || name),"
  19893. " writefile(($dir || name), %s, mode, mtime) "
  19894. "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
  19895. " AND name NOT GLOB '*..[/\\]*'";
  19896. const char *azExtraArg[] = {
  19897. "sqlar_uncompress(data, sz)",
  19898. "data"
  19899. };
  19900. sqlite3_stmt *pSql = 0;
  19901. int rc = SQLITE_OK;
  19902. char *zDir = 0;
  19903. char *zWhere = 0;
  19904. int i, j;
  19905. /* If arguments are specified, check that they actually exist within
  19906. ** the archive before proceeding. And formulate a WHERE clause to
  19907. ** match them. */
  19908. rc = arCheckEntries(pAr);
  19909. arWhereClause(&rc, pAr, &zWhere);
  19910. if( rc==SQLITE_OK ){
  19911. if( pAr->zDir ){
  19912. zDir = sqlite3_mprintf("%s/", pAr->zDir);
  19913. }else{
  19914. zDir = sqlite3_mprintf("");
  19915. }
  19916. if( zDir==0 ) rc = SQLITE_NOMEM;
  19917. }
  19918. shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
  19919. azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
  19920. );
  19921. if( rc==SQLITE_OK ){
  19922. j = sqlite3_bind_parameter_index(pSql, "$dir");
  19923. sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
  19924. /* Run the SELECT statement twice. The first time, writefile() is called
  19925. ** for all archive members that should be extracted. The second time,
  19926. ** only for the directories. This is because the timestamps for
  19927. ** extracted directories must be reset after they are populated (as
  19928. ** populating them changes the timestamp). */
  19929. for(i=0; i<2; i++){
  19930. j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
  19931. sqlite3_bind_int(pSql, j, i);
  19932. if( pAr->bDryRun ){
  19933. utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
  19934. }else{
  19935. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  19936. if( i==0 && pAr->bVerbose ){
  19937. utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
  19938. }
  19939. }
  19940. }
  19941. shellReset(&rc, pSql);
  19942. }
  19943. shellFinalize(&rc, pSql);
  19944. }
  19945. sqlite3_free(zDir);
  19946. sqlite3_free(zWhere);
  19947. return rc;
  19948. }
  19949. /*
  19950. ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
  19951. */
  19952. static int arExecSql(ArCommand *pAr, const char *zSql){
  19953. int rc;
  19954. if( pAr->bDryRun ){
  19955. utf8_printf(pAr->p->out, "%s\n", zSql);
  19956. rc = SQLITE_OK;
  19957. }else{
  19958. char *zErr = 0;
  19959. rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
  19960. if( zErr ){
  19961. utf8_printf(stdout, "ERROR: %s\n", zErr);
  19962. sqlite3_free(zErr);
  19963. }
  19964. }
  19965. return rc;
  19966. }
  19967. /*
  19968. ** Implementation of .ar "create", "insert", and "update" commands.
  19969. **
  19970. ** create -> Create a new SQL archive
  19971. ** insert -> Insert or reinsert all files listed
  19972. ** update -> Insert files that have changed or that were not
  19973. ** previously in the archive
  19974. **
  19975. ** Create the "sqlar" table in the database if it does not already exist.
  19976. ** Then add each file in the azFile[] array to the archive. Directories
  19977. ** are added recursively. If argument bVerbose is non-zero, a message is
  19978. ** printed on stdout for each file archived.
  19979. **
  19980. ** The create command is the same as update, except that it drops
  19981. ** any existing "sqlar" table before beginning. The "insert" command
  19982. ** always overwrites every file named on the command-line, where as
  19983. ** "update" only overwrites if the size or mtime or mode has changed.
  19984. */
  19985. static int arCreateOrUpdateCommand(
  19986. ArCommand *pAr, /* Command arguments and options */
  19987. int bUpdate, /* true for a --create. */
  19988. int bOnlyIfChanged /* Only update if file has changed */
  19989. ){
  19990. const char *zCreate =
  19991. "CREATE TABLE IF NOT EXISTS sqlar(\n"
  19992. " name TEXT PRIMARY KEY, -- name of the file\n"
  19993. " mode INT, -- access permissions\n"
  19994. " mtime INT, -- last modification time\n"
  19995. " sz INT, -- original file size\n"
  19996. " data BLOB -- compressed content\n"
  19997. ")";
  19998. const char *zDrop = "DROP TABLE IF EXISTS sqlar";
  19999. const char *zInsertFmt[2] = {
  20000. "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
  20001. " SELECT\n"
  20002. " %s,\n"
  20003. " mode,\n"
  20004. " mtime,\n"
  20005. " CASE substr(lsmode(mode),1,1)\n"
  20006. " WHEN '-' THEN length(data)\n"
  20007. " WHEN 'd' THEN 0\n"
  20008. " ELSE -1 END,\n"
  20009. " sqlar_compress(data)\n"
  20010. " FROM fsdir(%Q,%Q) AS disk\n"
  20011. " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
  20012. ,
  20013. "REPLACE INTO %s(name,mode,mtime,data)\n"
  20014. " SELECT\n"
  20015. " %s,\n"
  20016. " mode,\n"
  20017. " mtime,\n"
  20018. " data\n"
  20019. " FROM fsdir(%Q,%Q) AS disk\n"
  20020. " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
  20021. };
  20022. int i; /* For iterating through azFile[] */
  20023. int rc; /* Return code */
  20024. const char *zTab = 0; /* SQL table into which to insert */
  20025. char *zSql;
  20026. char zTemp[50];
  20027. char *zExists = 0;
  20028. arExecSql(pAr, "PRAGMA page_size=512");
  20029. rc = arExecSql(pAr, "SAVEPOINT ar;");
  20030. if( rc!=SQLITE_OK ) return rc;
  20031. zTemp[0] = 0;
  20032. if( pAr->bZip ){
  20033. /* Initialize the zipfile virtual table, if necessary */
  20034. if( pAr->zFile ){
  20035. sqlite3_uint64 r;
  20036. sqlite3_randomness(sizeof(r),&r);
  20037. sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
  20038. zTab = zTemp;
  20039. zSql = sqlite3_mprintf(
  20040. "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
  20041. zTab, pAr->zFile
  20042. );
  20043. rc = arExecSql(pAr, zSql);
  20044. sqlite3_free(zSql);
  20045. }else{
  20046. zTab = "zip";
  20047. }
  20048. }else{
  20049. /* Initialize the table for an SQLAR */
  20050. zTab = "sqlar";
  20051. if( bUpdate==0 ){
  20052. rc = arExecSql(pAr, zDrop);
  20053. if( rc!=SQLITE_OK ) goto end_ar_transaction;
  20054. }
  20055. rc = arExecSql(pAr, zCreate);
  20056. }
  20057. if( bOnlyIfChanged ){
  20058. zExists = sqlite3_mprintf(
  20059. " AND NOT EXISTS("
  20060. "SELECT 1 FROM %s AS mem"
  20061. " WHERE mem.name=disk.name"
  20062. " AND mem.mtime=disk.mtime"
  20063. " AND mem.mode=disk.mode)", zTab);
  20064. }else{
  20065. zExists = sqlite3_mprintf("");
  20066. }
  20067. if( zExists==0 ) rc = SQLITE_NOMEM;
  20068. for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
  20069. char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
  20070. pAr->bVerbose ? "shell_putsnl(name)" : "name",
  20071. pAr->azArg[i], pAr->zDir, zExists);
  20072. rc = arExecSql(pAr, zSql2);
  20073. sqlite3_free(zSql2);
  20074. }
  20075. end_ar_transaction:
  20076. if( rc!=SQLITE_OK ){
  20077. sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
  20078. }else{
  20079. rc = arExecSql(pAr, "RELEASE ar;");
  20080. if( pAr->bZip && pAr->zFile ){
  20081. zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
  20082. arExecSql(pAr, zSql);
  20083. sqlite3_free(zSql);
  20084. }
  20085. }
  20086. sqlite3_free(zExists);
  20087. return rc;
  20088. }
  20089. /*
  20090. ** Implementation of ".ar" dot command.
  20091. */
  20092. static int arDotCommand(
  20093. ShellState *pState, /* Current shell tool state */
  20094. int fromCmdLine, /* True if -A command-line option, not .ar cmd */
  20095. char **azArg, /* Array of arguments passed to dot command */
  20096. int nArg /* Number of entries in azArg[] */
  20097. ){
  20098. ArCommand cmd;
  20099. int rc;
  20100. memset(&cmd, 0, sizeof(cmd));
  20101. cmd.fromCmdLine = fromCmdLine;
  20102. rc = arParseCommand(azArg, nArg, &cmd);
  20103. if( rc==SQLITE_OK ){
  20104. int eDbType = SHELL_OPEN_UNSPEC;
  20105. cmd.p = pState;
  20106. cmd.db = pState->db;
  20107. if( cmd.zFile ){
  20108. eDbType = deduceDatabaseType(cmd.zFile, 1);
  20109. }else{
  20110. eDbType = pState->openMode;
  20111. }
  20112. if( eDbType==SHELL_OPEN_ZIPFILE ){
  20113. if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
  20114. if( cmd.zFile==0 ){
  20115. cmd.zSrcTable = sqlite3_mprintf("zip");
  20116. }else{
  20117. cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
  20118. }
  20119. }
  20120. cmd.bZip = 1;
  20121. }else if( cmd.zFile ){
  20122. int flags;
  20123. if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
  20124. if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
  20125. || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
  20126. flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
  20127. }else{
  20128. flags = SQLITE_OPEN_READONLY;
  20129. }
  20130. cmd.db = 0;
  20131. if( cmd.bDryRun ){
  20132. utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
  20133. eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
  20134. }
  20135. rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
  20136. eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
  20137. if( rc!=SQLITE_OK ){
  20138. utf8_printf(stderr, "cannot open file: %s (%s)\n",
  20139. cmd.zFile, sqlite3_errmsg(cmd.db)
  20140. );
  20141. goto end_ar_command;
  20142. }
  20143. sqlite3_fileio_init(cmd.db, 0, 0);
  20144. sqlite3_sqlar_init(cmd.db, 0, 0);
  20145. sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
  20146. shellPutsFunc, 0, 0);
  20147. }
  20148. if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
  20149. if( cmd.eCmd!=AR_CMD_CREATE
  20150. && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
  20151. ){
  20152. utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
  20153. rc = SQLITE_ERROR;
  20154. goto end_ar_command;
  20155. }
  20156. cmd.zSrcTable = sqlite3_mprintf("sqlar");
  20157. }
  20158. switch( cmd.eCmd ){
  20159. case AR_CMD_CREATE:
  20160. rc = arCreateOrUpdateCommand(&cmd, 0, 0);
  20161. break;
  20162. case AR_CMD_EXTRACT:
  20163. rc = arExtractCommand(&cmd);
  20164. break;
  20165. case AR_CMD_LIST:
  20166. rc = arListCommand(&cmd);
  20167. break;
  20168. case AR_CMD_HELP:
  20169. arUsage(pState->out);
  20170. break;
  20171. case AR_CMD_INSERT:
  20172. rc = arCreateOrUpdateCommand(&cmd, 1, 0);
  20173. break;
  20174. case AR_CMD_REMOVE:
  20175. rc = arRemoveCommand(&cmd);
  20176. break;
  20177. default:
  20178. assert( cmd.eCmd==AR_CMD_UPDATE );
  20179. rc = arCreateOrUpdateCommand(&cmd, 1, 1);
  20180. break;
  20181. }
  20182. }
  20183. end_ar_command:
  20184. if( cmd.db!=pState->db ){
  20185. close_db(cmd.db);
  20186. }
  20187. sqlite3_free(cmd.zSrcTable);
  20188. return rc;
  20189. }
  20190. /* End of the ".archive" or ".ar" command logic
  20191. *******************************************************************************/
  20192. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
  20193. #if SQLITE_SHELL_HAVE_RECOVER
  20194. /*
  20195. ** This function is used as a callback by the recover extension. Simply
  20196. ** print the supplied SQL statement to stdout.
  20197. */
  20198. static int recoverSqlCb(void *pCtx, const char *zSql){
  20199. ShellState *pState = (ShellState*)pCtx;
  20200. utf8_printf(pState->out, "%s;\n", zSql);
  20201. return SQLITE_OK;
  20202. }
  20203. /*
  20204. ** This function is called to recover data from the database. A script
  20205. ** to construct a new database containing all recovered data is output
  20206. ** on stream pState->out.
  20207. */
  20208. static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
  20209. int rc = SQLITE_OK;
  20210. const char *zRecoveryDb = ""; /* Name of "recovery" database. Debug only */
  20211. const char *zLAF = "lost_and_found";
  20212. int bFreelist = 1; /* 0 if --ignore-freelist is specified */
  20213. int bRowids = 1; /* 0 if --no-rowids */
  20214. sqlite3_recover *p = 0;
  20215. int i = 0;
  20216. for(i=1; i<nArg; i++){
  20217. char *z = azArg[i];
  20218. int n;
  20219. if( z[0]=='-' && z[1]=='-' ) z++;
  20220. n = strlen30(z);
  20221. if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
  20222. bFreelist = 0;
  20223. }else
  20224. if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
  20225. /* This option determines the name of the ATTACH-ed database used
  20226. ** internally by the recovery extension. The default is "" which
  20227. ** means to use a temporary database that is automatically deleted
  20228. ** when closed. This option is undocumented and might disappear at
  20229. ** any moment. */
  20230. i++;
  20231. zRecoveryDb = azArg[i];
  20232. }else
  20233. if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
  20234. i++;
  20235. zLAF = azArg[i];
  20236. }else
  20237. if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
  20238. bRowids = 0;
  20239. }
  20240. else{
  20241. utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
  20242. showHelp(pState->out, azArg[0]);
  20243. return 1;
  20244. }
  20245. }
  20246. p = sqlite3_recover_init_sql(
  20247. pState->db, "main", recoverSqlCb, (void*)pState
  20248. );
  20249. sqlite3_recover_config(p, 789, (void*)zRecoveryDb); /* Debug use only */
  20250. sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
  20251. sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
  20252. sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
  20253. sqlite3_recover_run(p);
  20254. if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
  20255. const char *zErr = sqlite3_recover_errmsg(p);
  20256. int errCode = sqlite3_recover_errcode(p);
  20257. raw_printf(stderr, "sql error: %s (%d)\n", zErr, errCode);
  20258. }
  20259. rc = sqlite3_recover_finish(p);
  20260. return rc;
  20261. }
  20262. #endif /* SQLITE_SHELL_HAVE_RECOVER */
  20263. /*
  20264. * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
  20265. * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
  20266. * close db and set it to 0, and return the columns spec, to later
  20267. * be sqlite3_free()'ed by the caller.
  20268. * The return is 0 when either:
  20269. * (a) The db was not initialized and zCol==0 (There are no columns.)
  20270. * (b) zCol!=0 (Column was added, db initialized as needed.)
  20271. * The 3rd argument, pRenamed, references an out parameter. If the
  20272. * pointer is non-zero, its referent will be set to a summary of renames
  20273. * done if renaming was necessary, or set to 0 if none was done. The out
  20274. * string (if any) must be sqlite3_free()'ed by the caller.
  20275. */
  20276. #ifdef SHELL_DEBUG
  20277. #define rc_err_oom_die(rc) \
  20278. if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
  20279. else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
  20280. fprintf(stderr,"E:%d\n",rc), assert(0)
  20281. #else
  20282. static void rc_err_oom_die(int rc){
  20283. if( rc==SQLITE_NOMEM ) shell_check_oom(0);
  20284. assert(rc==SQLITE_OK||rc==SQLITE_DONE);
  20285. }
  20286. #endif
  20287. #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
  20288. static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
  20289. #else /* Otherwise, memory is faster/better for the transient DB. */
  20290. static const char *zCOL_DB = ":memory:";
  20291. #endif
  20292. /* Define character (as C string) to separate generated column ordinal
  20293. * from protected part of incoming column names. This defaults to "_"
  20294. * so that incoming column identifiers that did not need not be quoted
  20295. * remain usable without being quoted. It must be one character.
  20296. */
  20297. #ifndef SHELL_AUTOCOLUMN_SEP
  20298. # define AUTOCOLUMN_SEP "_"
  20299. #else
  20300. # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
  20301. #endif
  20302. static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
  20303. /* Queries and D{D,M}L used here */
  20304. static const char * const zTabMake = "\
  20305. CREATE TABLE ColNames(\
  20306. cpos INTEGER PRIMARY KEY,\
  20307. name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
  20308. CREATE VIEW RepeatedNames AS \
  20309. SELECT DISTINCT t.name FROM ColNames t \
  20310. WHERE t.name COLLATE NOCASE IN (\
  20311. SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
  20312. );\
  20313. ";
  20314. static const char * const zTabFill = "\
  20315. INSERT INTO ColNames(name,nlen,chop,reps,suff)\
  20316. VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
  20317. ";
  20318. static const char * const zHasDupes = "\
  20319. SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
  20320. <count(name) FROM ColNames\
  20321. ";
  20322. #ifdef SHELL_COLUMN_RENAME_CLEAN
  20323. static const char * const zDedoctor = "\
  20324. UPDATE ColNames SET chop=iif(\
  20325. (substring(name,nlen,1) BETWEEN '0' AND '9')\
  20326. AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
  20327. nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
  20328. 0\
  20329. )\
  20330. ";
  20331. #endif
  20332. static const char * const zSetReps = "\
  20333. UPDATE ColNames AS t SET reps=\
  20334. (SELECT count(*) FROM ColNames d \
  20335. WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
  20336. COLLATE NOCASE\
  20337. )\
  20338. ";
  20339. #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
  20340. static const char * const zColDigits = "\
  20341. SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
  20342. ";
  20343. #else
  20344. /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
  20345. static const char * const zColDigits = "\
  20346. SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
  20347. WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
  20348. ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
  20349. ";
  20350. #endif
  20351. static const char * const zRenameRank =
  20352. #ifdef SHELL_COLUMN_RENAME_CLEAN
  20353. "UPDATE ColNames AS t SET suff="
  20354. "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
  20355. #else /* ...RENAME_MINIMAL_ONE_PASS */
  20356. "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
  20357. " SELECT 0 AS nlz"
  20358. " UNION"
  20359. " SELECT nlz+1 AS nlz FROM Lzn"
  20360. " WHERE EXISTS("
  20361. " SELECT 1"
  20362. " FROM ColNames t, ColNames o"
  20363. " WHERE"
  20364. " iif(t.name IN (SELECT * FROM RepeatedNames),"
  20365. " printf('%s"AUTOCOLUMN_SEP"%s',"
  20366. " t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
  20367. " t.name"
  20368. " )"
  20369. " ="
  20370. " iif(o.name IN (SELECT * FROM RepeatedNames),"
  20371. " printf('%s"AUTOCOLUMN_SEP"%s',"
  20372. " o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
  20373. " o.name"
  20374. " )"
  20375. " COLLATE NOCASE"
  20376. " AND o.cpos<>t.cpos"
  20377. " GROUP BY t.cpos"
  20378. " )"
  20379. ") UPDATE Colnames AS t SET"
  20380. " chop = 0," /* No chopping, never touch incoming names. */
  20381. " suff = iif(name IN (SELECT * FROM RepeatedNames),"
  20382. " printf('"AUTOCOLUMN_SEP"%s', substring("
  20383. " printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
  20384. " ''"
  20385. " )"
  20386. #endif
  20387. ;
  20388. static const char * const zCollectVar = "\
  20389. SELECT\
  20390. '('||x'0a'\
  20391. || group_concat(\
  20392. cname||' TEXT',\
  20393. ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
  20394. ||')' AS ColsSpec \
  20395. FROM (\
  20396. SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
  20397. FROM ColNames ORDER BY cpos\
  20398. )";
  20399. static const char * const zRenamesDone =
  20400. "SELECT group_concat("
  20401. " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
  20402. " ','||x'0a')"
  20403. "FROM ColNames WHERE suff<>'' OR chop!=0"
  20404. ;
  20405. int rc;
  20406. sqlite3_stmt *pStmt = 0;
  20407. assert(pDb!=0);
  20408. if( zColNew ){
  20409. /* Add initial or additional column. Init db if necessary. */
  20410. if( *pDb==0 ){
  20411. if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
  20412. #ifdef SHELL_COLFIX_DB
  20413. if(*zCOL_DB!=':')
  20414. sqlite3_exec(*pDb,"drop table if exists ColNames;"
  20415. "drop view if exists RepeatedNames;",0,0,0);
  20416. #endif
  20417. rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
  20418. rc_err_oom_die(rc);
  20419. }
  20420. assert(*pDb!=0);
  20421. rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
  20422. rc_err_oom_die(rc);
  20423. rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
  20424. rc_err_oom_die(rc);
  20425. rc = sqlite3_step(pStmt);
  20426. rc_err_oom_die(rc);
  20427. sqlite3_finalize(pStmt);
  20428. return 0;
  20429. }else if( *pDb==0 ){
  20430. return 0;
  20431. }else{
  20432. /* Formulate the columns spec, close the DB, zero *pDb. */
  20433. char *zColsSpec = 0;
  20434. int hasDupes = db_int(*pDb, zHasDupes);
  20435. int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
  20436. if( hasDupes ){
  20437. #ifdef SHELL_COLUMN_RENAME_CLEAN
  20438. rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
  20439. rc_err_oom_die(rc);
  20440. #endif
  20441. rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
  20442. rc_err_oom_die(rc);
  20443. rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
  20444. rc_err_oom_die(rc);
  20445. sqlite3_bind_int(pStmt, 1, nDigits);
  20446. rc = sqlite3_step(pStmt);
  20447. sqlite3_finalize(pStmt);
  20448. assert(rc==SQLITE_DONE);
  20449. }
  20450. assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
  20451. rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
  20452. rc_err_oom_die(rc);
  20453. rc = sqlite3_step(pStmt);
  20454. if( rc==SQLITE_ROW ){
  20455. zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  20456. }else{
  20457. zColsSpec = 0;
  20458. }
  20459. if( pzRenamed!=0 ){
  20460. if( !hasDupes ) *pzRenamed = 0;
  20461. else{
  20462. sqlite3_finalize(pStmt);
  20463. if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
  20464. && SQLITE_ROW==sqlite3_step(pStmt) ){
  20465. *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  20466. }else
  20467. *pzRenamed = 0;
  20468. }
  20469. }
  20470. sqlite3_finalize(pStmt);
  20471. sqlite3_close(*pDb);
  20472. *pDb = 0;
  20473. return zColsSpec;
  20474. }
  20475. }
  20476. /*
  20477. ** If an input line begins with "." then invoke this routine to
  20478. ** process that line.
  20479. **
  20480. ** Return 1 on error, 2 to exit, and 0 otherwise.
  20481. */
  20482. static int do_meta_command(char *zLine, ShellState *p){
  20483. int h = 1;
  20484. int nArg = 0;
  20485. int n, c;
  20486. int rc = 0;
  20487. char *azArg[52];
  20488. #ifndef SQLITE_OMIT_VIRTUALTABLE
  20489. if( p->expert.pExpert ){
  20490. expertFinish(p, 1, 0);
  20491. }
  20492. #endif
  20493. /* Parse the input line into tokens.
  20494. */
  20495. while( zLine[h] && nArg<ArraySize(azArg)-1 ){
  20496. while( IsSpace(zLine[h]) ){ h++; }
  20497. if( zLine[h]==0 ) break;
  20498. if( zLine[h]=='\'' || zLine[h]=='"' ){
  20499. int delim = zLine[h++];
  20500. azArg[nArg++] = &zLine[h];
  20501. while( zLine[h] && zLine[h]!=delim ){
  20502. if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
  20503. h++;
  20504. }
  20505. if( zLine[h]==delim ){
  20506. zLine[h++] = 0;
  20507. }
  20508. if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  20509. }else{
  20510. azArg[nArg++] = &zLine[h];
  20511. while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
  20512. if( zLine[h] ) zLine[h++] = 0;
  20513. resolve_backslashes(azArg[nArg-1]);
  20514. }
  20515. }
  20516. azArg[nArg] = 0;
  20517. /* Process the input line.
  20518. */
  20519. if( nArg==0 ) return 0; /* no tokens, no error */
  20520. n = strlen30(azArg[0]);
  20521. c = azArg[0][0];
  20522. clearTempFile(p);
  20523. #ifndef SQLITE_OMIT_AUTHORIZATION
  20524. if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
  20525. if( nArg!=2 ){
  20526. raw_printf(stderr, "Usage: .auth ON|OFF\n");
  20527. rc = 1;
  20528. goto meta_command_exit;
  20529. }
  20530. open_db(p, 0);
  20531. if( booleanValue(azArg[1]) ){
  20532. sqlite3_set_authorizer(p->db, shellAuth, p);
  20533. }else if( p->bSafeModePersist ){
  20534. sqlite3_set_authorizer(p->db, safeModeAuth, p);
  20535. }else{
  20536. sqlite3_set_authorizer(p->db, 0, 0);
  20537. }
  20538. }else
  20539. #endif
  20540. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
  20541. && !defined(SQLITE_SHELL_FIDDLE)
  20542. if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
  20543. open_db(p, 0);
  20544. failIfSafeMode(p, "cannot run .archive in safe mode");
  20545. rc = arDotCommand(p, 0, azArg, nArg);
  20546. }else
  20547. #endif
  20548. #ifndef SQLITE_SHELL_FIDDLE
  20549. if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
  20550. || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
  20551. ){
  20552. const char *zDestFile = 0;
  20553. const char *zDb = 0;
  20554. sqlite3 *pDest;
  20555. sqlite3_backup *pBackup;
  20556. int j;
  20557. int bAsync = 0;
  20558. const char *zVfs = 0;
  20559. failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
  20560. for(j=1; j<nArg; j++){
  20561. const char *z = azArg[j];
  20562. if( z[0]=='-' ){
  20563. if( z[1]=='-' ) z++;
  20564. if( cli_strcmp(z, "-append")==0 ){
  20565. zVfs = "apndvfs";
  20566. }else
  20567. if( cli_strcmp(z, "-async")==0 ){
  20568. bAsync = 1;
  20569. }else
  20570. {
  20571. utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
  20572. return 1;
  20573. }
  20574. }else if( zDestFile==0 ){
  20575. zDestFile = azArg[j];
  20576. }else if( zDb==0 ){
  20577. zDb = zDestFile;
  20578. zDestFile = azArg[j];
  20579. }else{
  20580. raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
  20581. return 1;
  20582. }
  20583. }
  20584. if( zDestFile==0 ){
  20585. raw_printf(stderr, "missing FILENAME argument on .backup\n");
  20586. return 1;
  20587. }
  20588. if( zDb==0 ) zDb = "main";
  20589. rc = sqlite3_open_v2(zDestFile, &pDest,
  20590. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
  20591. if( rc!=SQLITE_OK ){
  20592. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  20593. close_db(pDest);
  20594. return 1;
  20595. }
  20596. if( bAsync ){
  20597. sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
  20598. 0, 0, 0);
  20599. }
  20600. open_db(p, 0);
  20601. pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  20602. if( pBackup==0 ){
  20603. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  20604. close_db(pDest);
  20605. return 1;
  20606. }
  20607. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  20608. sqlite3_backup_finish(pBackup);
  20609. if( rc==SQLITE_DONE ){
  20610. rc = 0;
  20611. }else{
  20612. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  20613. rc = 1;
  20614. }
  20615. close_db(pDest);
  20616. }else
  20617. #endif /* !defined(SQLITE_SHELL_FIDDLE) */
  20618. if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
  20619. if( nArg==2 ){
  20620. bail_on_error = booleanValue(azArg[1]);
  20621. }else{
  20622. raw_printf(stderr, "Usage: .bail on|off\n");
  20623. rc = 1;
  20624. }
  20625. }else
  20626. if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
  20627. if( nArg==2 ){
  20628. if( booleanValue(azArg[1]) ){
  20629. setBinaryMode(p->out, 1);
  20630. }else{
  20631. setTextMode(p->out, 1);
  20632. }
  20633. }else{
  20634. raw_printf(stderr, "Usage: .binary on|off\n");
  20635. rc = 1;
  20636. }
  20637. }else
  20638. /* The undocumented ".breakpoint" command causes a call to the no-op
  20639. ** routine named test_breakpoint().
  20640. */
  20641. if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
  20642. test_breakpoint();
  20643. }else
  20644. #ifndef SQLITE_SHELL_FIDDLE
  20645. if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
  20646. failIfSafeMode(p, "cannot run .cd in safe mode");
  20647. if( nArg==2 ){
  20648. #if defined(_WIN32) || defined(WIN32)
  20649. wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
  20650. rc = !SetCurrentDirectoryW(z);
  20651. sqlite3_free(z);
  20652. #else
  20653. rc = chdir(azArg[1]);
  20654. #endif
  20655. if( rc ){
  20656. utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
  20657. rc = 1;
  20658. }
  20659. }else{
  20660. raw_printf(stderr, "Usage: .cd DIRECTORY\n");
  20661. rc = 1;
  20662. }
  20663. }else
  20664. #endif /* !defined(SQLITE_SHELL_FIDDLE) */
  20665. if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
  20666. if( nArg==2 ){
  20667. setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
  20668. }else{
  20669. raw_printf(stderr, "Usage: .changes on|off\n");
  20670. rc = 1;
  20671. }
  20672. }else
  20673. #ifndef SQLITE_SHELL_FIDDLE
  20674. /* Cancel output redirection, if it is currently set (by .testcase)
  20675. ** Then read the content of the testcase-out.txt file and compare against
  20676. ** azArg[1]. If there are differences, report an error and exit.
  20677. */
  20678. if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
  20679. char *zRes = 0;
  20680. output_reset(p);
  20681. if( nArg!=2 ){
  20682. raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
  20683. rc = 2;
  20684. }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
  20685. raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
  20686. rc = 2;
  20687. }else if( testcase_glob(azArg[1],zRes)==0 ){
  20688. utf8_printf(stderr,
  20689. "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
  20690. p->zTestcase, azArg[1], zRes);
  20691. rc = 1;
  20692. }else{
  20693. utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
  20694. p->nCheck++;
  20695. }
  20696. sqlite3_free(zRes);
  20697. }else
  20698. #endif /* !defined(SQLITE_SHELL_FIDDLE) */
  20699. #ifndef SQLITE_SHELL_FIDDLE
  20700. if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
  20701. failIfSafeMode(p, "cannot run .clone in safe mode");
  20702. if( nArg==2 ){
  20703. tryToClone(p, azArg[1]);
  20704. }else{
  20705. raw_printf(stderr, "Usage: .clone FILENAME\n");
  20706. rc = 1;
  20707. }
  20708. }else
  20709. #endif /* !defined(SQLITE_SHELL_FIDDLE) */
  20710. if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
  20711. if( nArg==1 ){
  20712. /* List available connections */
  20713. int i;
  20714. for(i=0; i<ArraySize(p->aAuxDb); i++){
  20715. const char *zFile = p->aAuxDb[i].zDbFilename;
  20716. if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
  20717. zFile = "(not open)";
  20718. }else if( zFile==0 ){
  20719. zFile = "(memory)";
  20720. }else if( zFile[0]==0 ){
  20721. zFile = "(temporary-file)";
  20722. }
  20723. if( p->pAuxDb == &p->aAuxDb[i] ){
  20724. utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
  20725. }else if( p->aAuxDb[i].db!=0 ){
  20726. utf8_printf(stdout, " %d: %s\n", i, zFile);
  20727. }
  20728. }
  20729. }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
  20730. int i = azArg[1][0] - '0';
  20731. if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
  20732. p->pAuxDb->db = p->db;
  20733. p->pAuxDb = &p->aAuxDb[i];
  20734. globalDb = p->db = p->pAuxDb->db;
  20735. p->pAuxDb->db = 0;
  20736. }
  20737. }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
  20738. && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
  20739. int i = azArg[2][0] - '0';
  20740. if( i<0 || i>=ArraySize(p->aAuxDb) ){
  20741. /* No-op */
  20742. }else if( p->pAuxDb == &p->aAuxDb[i] ){
  20743. raw_printf(stderr, "cannot close the active database connection\n");
  20744. rc = 1;
  20745. }else if( p->aAuxDb[i].db ){
  20746. session_close_all(p, i);
  20747. close_db(p->aAuxDb[i].db);
  20748. p->aAuxDb[i].db = 0;
  20749. }
  20750. }else{
  20751. raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
  20752. rc = 1;
  20753. }
  20754. }else
  20755. if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
  20756. char **azName = 0;
  20757. int nName = 0;
  20758. sqlite3_stmt *pStmt;
  20759. int i;
  20760. open_db(p, 0);
  20761. rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
  20762. if( rc ){
  20763. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  20764. rc = 1;
  20765. }else{
  20766. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  20767. const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
  20768. const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
  20769. if( zSchema==0 || zFile==0 ) continue;
  20770. azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
  20771. shell_check_oom(azName);
  20772. azName[nName*2] = strdup(zSchema);
  20773. azName[nName*2+1] = strdup(zFile);
  20774. nName++;
  20775. }
  20776. }
  20777. sqlite3_finalize(pStmt);
  20778. for(i=0; i<nName; i++){
  20779. int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
  20780. int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
  20781. const char *z = azName[i*2+1];
  20782. utf8_printf(p->out, "%s: %s %s%s\n",
  20783. azName[i*2],
  20784. z && z[0] ? z : "\"\"",
  20785. bRdonly ? "r/o" : "r/w",
  20786. eTxn==SQLITE_TXN_NONE ? "" :
  20787. eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
  20788. free(azName[i*2]);
  20789. free(azName[i*2+1]);
  20790. }
  20791. sqlite3_free(azName);
  20792. }else
  20793. if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
  20794. static const struct DbConfigChoices {
  20795. const char *zName;
  20796. int op;
  20797. } aDbConfig[] = {
  20798. { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
  20799. { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL },
  20800. { "dqs_dml", SQLITE_DBCONFIG_DQS_DML },
  20801. { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
  20802. { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
  20803. { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
  20804. { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW },
  20805. { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
  20806. { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE },
  20807. { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT },
  20808. { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
  20809. { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
  20810. { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
  20811. { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
  20812. { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
  20813. { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
  20814. };
  20815. int ii, v;
  20816. open_db(p, 0);
  20817. for(ii=0; ii<ArraySize(aDbConfig); ii++){
  20818. if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
  20819. if( nArg>=3 ){
  20820. sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
  20821. }
  20822. sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
  20823. utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
  20824. if( nArg>1 ) break;
  20825. }
  20826. if( nArg>1 && ii==ArraySize(aDbConfig) ){
  20827. utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
  20828. utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
  20829. }
  20830. }else
  20831. #if SQLITE_SHELL_HAVE_RECOVER
  20832. if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
  20833. rc = shell_dbinfo_command(p, nArg, azArg);
  20834. }else
  20835. if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
  20836. open_db(p, 0);
  20837. rc = recoverDatabaseCmd(p, nArg, azArg);
  20838. }else
  20839. #endif /* SQLITE_SHELL_HAVE_RECOVER */
  20840. if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
  20841. char *zLike = 0;
  20842. char *zSql;
  20843. int i;
  20844. int savedShowHeader = p->showHeader;
  20845. int savedShellFlags = p->shellFlgs;
  20846. ShellClearFlag(p,
  20847. SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
  20848. |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
  20849. for(i=1; i<nArg; i++){
  20850. if( azArg[i][0]=='-' ){
  20851. const char *z = azArg[i]+1;
  20852. if( z[0]=='-' ) z++;
  20853. if( cli_strcmp(z,"preserve-rowids")==0 ){
  20854. #ifdef SQLITE_OMIT_VIRTUALTABLE
  20855. raw_printf(stderr, "The --preserve-rowids option is not compatible"
  20856. " with SQLITE_OMIT_VIRTUALTABLE\n");
  20857. rc = 1;
  20858. sqlite3_free(zLike);
  20859. goto meta_command_exit;
  20860. #else
  20861. ShellSetFlag(p, SHFLG_PreserveRowid);
  20862. #endif
  20863. }else
  20864. if( cli_strcmp(z,"newlines")==0 ){
  20865. ShellSetFlag(p, SHFLG_Newlines);
  20866. }else
  20867. if( cli_strcmp(z,"data-only")==0 ){
  20868. ShellSetFlag(p, SHFLG_DumpDataOnly);
  20869. }else
  20870. if( cli_strcmp(z,"nosys")==0 ){
  20871. ShellSetFlag(p, SHFLG_DumpNoSys);
  20872. }else
  20873. {
  20874. raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
  20875. rc = 1;
  20876. sqlite3_free(zLike);
  20877. goto meta_command_exit;
  20878. }
  20879. }else{
  20880. /* azArg[i] contains a LIKE pattern. This ".dump" request should
  20881. ** only dump data for tables for which either the table name matches
  20882. ** the LIKE pattern, or the table appears to be a shadow table of
  20883. ** a virtual table for which the name matches the LIKE pattern.
  20884. */
  20885. char *zExpr = sqlite3_mprintf(
  20886. "name LIKE %Q ESCAPE '\\' OR EXISTS ("
  20887. " SELECT 1 FROM sqlite_schema WHERE "
  20888. " name LIKE %Q ESCAPE '\\' AND"
  20889. " sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
  20890. " substr(o.name, 1, length(name)+1) == (name||'_')"
  20891. ")", azArg[i], azArg[i]
  20892. );
  20893. if( zLike ){
  20894. zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
  20895. }else{
  20896. zLike = zExpr;
  20897. }
  20898. }
  20899. }
  20900. open_db(p, 0);
  20901. if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
  20902. /* When playing back a "dump", the content might appear in an order
  20903. ** which causes immediate foreign key constraints to be violated.
  20904. ** So disable foreign-key constraint enforcement to prevent problems. */
  20905. raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
  20906. raw_printf(p->out, "BEGIN TRANSACTION;\n");
  20907. }
  20908. p->writableSchema = 0;
  20909. p->showHeader = 0;
  20910. /* Set writable_schema=ON since doing so forces SQLite to initialize
  20911. ** as much of the schema as it can even if the sqlite_schema table is
  20912. ** corrupt. */
  20913. sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
  20914. p->nErr = 0;
  20915. if( zLike==0 ) zLike = sqlite3_mprintf("true");
  20916. zSql = sqlite3_mprintf(
  20917. "SELECT name, type, sql FROM sqlite_schema AS o "
  20918. "WHERE (%s) AND type=='table'"
  20919. " AND sql NOT NULL"
  20920. " ORDER BY tbl_name='sqlite_sequence', rowid",
  20921. zLike
  20922. );
  20923. run_schema_dump_query(p,zSql);
  20924. sqlite3_free(zSql);
  20925. if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
  20926. zSql = sqlite3_mprintf(
  20927. "SELECT sql FROM sqlite_schema AS o "
  20928. "WHERE (%s) AND sql NOT NULL"
  20929. " AND type IN ('index','trigger','view')",
  20930. zLike
  20931. );
  20932. run_table_dump_query(p, zSql);
  20933. sqlite3_free(zSql);
  20934. }
  20935. sqlite3_free(zLike);
  20936. if( p->writableSchema ){
  20937. raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
  20938. p->writableSchema = 0;
  20939. }
  20940. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  20941. sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
  20942. if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
  20943. raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
  20944. }
  20945. p->showHeader = savedShowHeader;
  20946. p->shellFlgs = savedShellFlags;
  20947. }else
  20948. if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
  20949. if( nArg==2 ){
  20950. setOrClearFlag(p, SHFLG_Echo, azArg[1]);
  20951. }else{
  20952. raw_printf(stderr, "Usage: .echo on|off\n");
  20953. rc = 1;
  20954. }
  20955. }else
  20956. if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
  20957. if( nArg==2 ){
  20958. p->autoEQPtest = 0;
  20959. if( p->autoEQPtrace ){
  20960. if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
  20961. p->autoEQPtrace = 0;
  20962. }
  20963. if( cli_strcmp(azArg[1],"full")==0 ){
  20964. p->autoEQP = AUTOEQP_full;
  20965. }else if( cli_strcmp(azArg[1],"trigger")==0 ){
  20966. p->autoEQP = AUTOEQP_trigger;
  20967. #ifdef SQLITE_DEBUG
  20968. }else if( cli_strcmp(azArg[1],"test")==0 ){
  20969. p->autoEQP = AUTOEQP_on;
  20970. p->autoEQPtest = 1;
  20971. }else if( cli_strcmp(azArg[1],"trace")==0 ){
  20972. p->autoEQP = AUTOEQP_full;
  20973. p->autoEQPtrace = 1;
  20974. open_db(p, 0);
  20975. sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
  20976. sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
  20977. #endif
  20978. }else{
  20979. p->autoEQP = (u8)booleanValue(azArg[1]);
  20980. }
  20981. }else{
  20982. raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
  20983. rc = 1;
  20984. }
  20985. }else
  20986. #ifndef SQLITE_SHELL_FIDDLE
  20987. if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
  20988. if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
  20989. rc = 2;
  20990. }else
  20991. #endif
  20992. /* The ".explain" command is automatic now. It is largely pointless. It
  20993. ** retained purely for backwards compatibility */
  20994. if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
  20995. int val = 1;
  20996. if( nArg>=2 ){
  20997. if( cli_strcmp(azArg[1],"auto")==0 ){
  20998. val = 99;
  20999. }else{
  21000. val = booleanValue(azArg[1]);
  21001. }
  21002. }
  21003. if( val==1 && p->mode!=MODE_Explain ){
  21004. p->normalMode = p->mode;
  21005. p->mode = MODE_Explain;
  21006. p->autoExplain = 0;
  21007. }else if( val==0 ){
  21008. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  21009. p->autoExplain = 0;
  21010. }else if( val==99 ){
  21011. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  21012. p->autoExplain = 1;
  21013. }
  21014. }else
  21015. #ifndef SQLITE_OMIT_VIRTUALTABLE
  21016. if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
  21017. if( p->bSafeMode ){
  21018. raw_printf(stderr,
  21019. "Cannot run experimental commands such as \"%s\" in safe mode\n",
  21020. azArg[0]);
  21021. rc = 1;
  21022. }else{
  21023. open_db(p, 0);
  21024. expertDotCommand(p, azArg, nArg);
  21025. }
  21026. }else
  21027. #endif
  21028. if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
  21029. static const struct {
  21030. const char *zCtrlName; /* Name of a test-control option */
  21031. int ctrlCode; /* Integer code for that option */
  21032. const char *zUsage; /* Usage notes */
  21033. } aCtrl[] = {
  21034. { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" },
  21035. { "data_version", SQLITE_FCNTL_DATA_VERSION, "" },
  21036. { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" },
  21037. { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" },
  21038. { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" },
  21039. /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
  21040. { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" },
  21041. { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" },
  21042. { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" },
  21043. { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" },
  21044. /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
  21045. };
  21046. int filectrl = -1;
  21047. int iCtrl = -1;
  21048. sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */
  21049. int isOk = 0; /* 0: usage 1: %lld 2: no-result */
  21050. int n2, i;
  21051. const char *zCmd = 0;
  21052. const char *zSchema = 0;
  21053. open_db(p, 0);
  21054. zCmd = nArg>=2 ? azArg[1] : "help";
  21055. if( zCmd[0]=='-'
  21056. && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
  21057. && nArg>=4
  21058. ){
  21059. zSchema = azArg[2];
  21060. for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
  21061. nArg -= 2;
  21062. zCmd = azArg[1];
  21063. }
  21064. /* The argument can optionally begin with "-" or "--" */
  21065. if( zCmd[0]=='-' && zCmd[1] ){
  21066. zCmd++;
  21067. if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
  21068. }
  21069. /* --help lists all file-controls */
  21070. if( cli_strcmp(zCmd,"help")==0 ){
  21071. utf8_printf(p->out, "Available file-controls:\n");
  21072. for(i=0; i<ArraySize(aCtrl); i++){
  21073. utf8_printf(p->out, " .filectrl %s %s\n",
  21074. aCtrl[i].zCtrlName, aCtrl[i].zUsage);
  21075. }
  21076. rc = 1;
  21077. goto meta_command_exit;
  21078. }
  21079. /* convert filectrl text option to value. allow any unique prefix
  21080. ** of the option name, or a numerical value. */
  21081. n2 = strlen30(zCmd);
  21082. for(i=0; i<ArraySize(aCtrl); i++){
  21083. if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
  21084. if( filectrl<0 ){
  21085. filectrl = aCtrl[i].ctrlCode;
  21086. iCtrl = i;
  21087. }else{
  21088. utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
  21089. "Use \".filectrl --help\" for help\n", zCmd);
  21090. rc = 1;
  21091. goto meta_command_exit;
  21092. }
  21093. }
  21094. }
  21095. if( filectrl<0 ){
  21096. utf8_printf(stderr,"Error: unknown file-control: %s\n"
  21097. "Use \".filectrl --help\" for help\n", zCmd);
  21098. }else{
  21099. switch(filectrl){
  21100. case SQLITE_FCNTL_SIZE_LIMIT: {
  21101. if( nArg!=2 && nArg!=3 ) break;
  21102. iRes = nArg==3 ? integerValue(azArg[2]) : -1;
  21103. sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
  21104. isOk = 1;
  21105. break;
  21106. }
  21107. case SQLITE_FCNTL_LOCK_TIMEOUT:
  21108. case SQLITE_FCNTL_CHUNK_SIZE: {
  21109. int x;
  21110. if( nArg!=3 ) break;
  21111. x = (int)integerValue(azArg[2]);
  21112. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  21113. isOk = 2;
  21114. break;
  21115. }
  21116. case SQLITE_FCNTL_PERSIST_WAL:
  21117. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  21118. int x;
  21119. if( nArg!=2 && nArg!=3 ) break;
  21120. x = nArg==3 ? booleanValue(azArg[2]) : -1;
  21121. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  21122. iRes = x;
  21123. isOk = 1;
  21124. break;
  21125. }
  21126. case SQLITE_FCNTL_DATA_VERSION:
  21127. case SQLITE_FCNTL_HAS_MOVED: {
  21128. int x;
  21129. if( nArg!=2 ) break;
  21130. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  21131. iRes = x;
  21132. isOk = 1;
  21133. break;
  21134. }
  21135. case SQLITE_FCNTL_TEMPFILENAME: {
  21136. char *z = 0;
  21137. if( nArg!=2 ) break;
  21138. sqlite3_file_control(p->db, zSchema, filectrl, &z);
  21139. if( z ){
  21140. utf8_printf(p->out, "%s\n", z);
  21141. sqlite3_free(z);
  21142. }
  21143. isOk = 2;
  21144. break;
  21145. }
  21146. case SQLITE_FCNTL_RESERVE_BYTES: {
  21147. int x;
  21148. if( nArg>=3 ){
  21149. x = atoi(azArg[2]);
  21150. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  21151. }
  21152. x = -1;
  21153. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  21154. utf8_printf(p->out,"%d\n", x);
  21155. isOk = 2;
  21156. break;
  21157. }
  21158. }
  21159. }
  21160. if( isOk==0 && iCtrl>=0 ){
  21161. utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
  21162. rc = 1;
  21163. }else if( isOk==1 ){
  21164. char zBuf[100];
  21165. sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
  21166. raw_printf(p->out, "%s\n", zBuf);
  21167. }
  21168. }else
  21169. if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
  21170. ShellState data;
  21171. int doStats = 0;
  21172. memcpy(&data, p, sizeof(data));
  21173. data.showHeader = 0;
  21174. data.cMode = data.mode = MODE_Semi;
  21175. if( nArg==2 && optionMatch(azArg[1], "indent") ){
  21176. data.cMode = data.mode = MODE_Pretty;
  21177. nArg = 1;
  21178. }
  21179. if( nArg!=1 ){
  21180. raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
  21181. rc = 1;
  21182. goto meta_command_exit;
  21183. }
  21184. open_db(p, 0);
  21185. rc = sqlite3_exec(p->db,
  21186. "SELECT sql FROM"
  21187. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  21188. " FROM sqlite_schema UNION ALL"
  21189. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
  21190. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  21191. "ORDER BY x",
  21192. callback, &data, 0
  21193. );
  21194. if( rc==SQLITE_OK ){
  21195. sqlite3_stmt *pStmt;
  21196. rc = sqlite3_prepare_v2(p->db,
  21197. "SELECT rowid FROM sqlite_schema"
  21198. " WHERE name GLOB 'sqlite_stat[134]'",
  21199. -1, &pStmt, 0);
  21200. doStats = sqlite3_step(pStmt)==SQLITE_ROW;
  21201. sqlite3_finalize(pStmt);
  21202. }
  21203. if( doStats==0 ){
  21204. raw_printf(p->out, "/* No STAT tables available */\n");
  21205. }else{
  21206. raw_printf(p->out, "ANALYZE sqlite_schema;\n");
  21207. data.cMode = data.mode = MODE_Insert;
  21208. data.zDestTable = "sqlite_stat1";
  21209. shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
  21210. data.zDestTable = "sqlite_stat4";
  21211. shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
  21212. raw_printf(p->out, "ANALYZE sqlite_schema;\n");
  21213. }
  21214. }else
  21215. if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
  21216. if( nArg==2 ){
  21217. p->showHeader = booleanValue(azArg[1]);
  21218. p->shellFlgs |= SHFLG_HeaderSet;
  21219. }else{
  21220. raw_printf(stderr, "Usage: .headers on|off\n");
  21221. rc = 1;
  21222. }
  21223. }else
  21224. if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
  21225. if( nArg>=2 ){
  21226. n = showHelp(p->out, azArg[1]);
  21227. if( n==0 ){
  21228. utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
  21229. }
  21230. }else{
  21231. showHelp(p->out, 0);
  21232. }
  21233. }else
  21234. #ifndef SQLITE_SHELL_FIDDLE
  21235. if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
  21236. char *zTable = 0; /* Insert data into this table */
  21237. char *zSchema = 0; /* within this schema (may default to "main") */
  21238. char *zFile = 0; /* Name of file to extra content from */
  21239. sqlite3_stmt *pStmt = NULL; /* A statement */
  21240. int nCol; /* Number of columns in the table */
  21241. int nByte; /* Number of bytes in an SQL string */
  21242. int i, j; /* Loop counters */
  21243. int needCommit; /* True to COMMIT or ROLLBACK at end */
  21244. int nSep; /* Number of bytes in p->colSeparator[] */
  21245. char *zSql; /* An SQL statement */
  21246. char *zFullTabName; /* Table name with schema if applicable */
  21247. ImportCtx sCtx; /* Reader context */
  21248. char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
  21249. int eVerbose = 0; /* Larger for more console output */
  21250. int nSkip = 0; /* Initial lines to skip */
  21251. int useOutputMode = 1; /* Use output mode to determine separators */
  21252. char *zCreate = 0; /* CREATE TABLE statement text */
  21253. failIfSafeMode(p, "cannot run .import in safe mode");
  21254. memset(&sCtx, 0, sizeof(sCtx));
  21255. if( p->mode==MODE_Ascii ){
  21256. xRead = ascii_read_one_field;
  21257. }else{
  21258. xRead = csv_read_one_field;
  21259. }
  21260. rc = 1;
  21261. for(i=1; i<nArg; i++){
  21262. char *z = azArg[i];
  21263. if( z[0]=='-' && z[1]=='-' ) z++;
  21264. if( z[0]!='-' ){
  21265. if( zFile==0 ){
  21266. zFile = z;
  21267. }else if( zTable==0 ){
  21268. zTable = z;
  21269. }else{
  21270. utf8_printf(p->out, "ERROR: extra argument: \"%s\". Usage:\n", z);
  21271. showHelp(p->out, "import");
  21272. goto meta_command_exit;
  21273. }
  21274. }else if( cli_strcmp(z,"-v")==0 ){
  21275. eVerbose++;
  21276. }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
  21277. zSchema = azArg[++i];
  21278. }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
  21279. nSkip = integerValue(azArg[++i]);
  21280. }else if( cli_strcmp(z,"-ascii")==0 ){
  21281. sCtx.cColSep = SEP_Unit[0];
  21282. sCtx.cRowSep = SEP_Record[0];
  21283. xRead = ascii_read_one_field;
  21284. useOutputMode = 0;
  21285. }else if( cli_strcmp(z,"-csv")==0 ){
  21286. sCtx.cColSep = ',';
  21287. sCtx.cRowSep = '\n';
  21288. xRead = csv_read_one_field;
  21289. useOutputMode = 0;
  21290. }else{
  21291. utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", z);
  21292. showHelp(p->out, "import");
  21293. goto meta_command_exit;
  21294. }
  21295. }
  21296. if( zTable==0 ){
  21297. utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
  21298. zFile==0 ? "FILE" : "TABLE");
  21299. showHelp(p->out, "import");
  21300. goto meta_command_exit;
  21301. }
  21302. seenInterrupt = 0;
  21303. open_db(p, 0);
  21304. if( useOutputMode ){
  21305. /* If neither the --csv or --ascii options are specified, then set
  21306. ** the column and row separator characters from the output mode. */
  21307. nSep = strlen30(p->colSeparator);
  21308. if( nSep==0 ){
  21309. raw_printf(stderr,
  21310. "Error: non-null column separator required for import\n");
  21311. goto meta_command_exit;
  21312. }
  21313. if( nSep>1 ){
  21314. raw_printf(stderr,
  21315. "Error: multi-character column separators not allowed"
  21316. " for import\n");
  21317. goto meta_command_exit;
  21318. }
  21319. nSep = strlen30(p->rowSeparator);
  21320. if( nSep==0 ){
  21321. raw_printf(stderr,
  21322. "Error: non-null row separator required for import\n");
  21323. goto meta_command_exit;
  21324. }
  21325. if( nSep==2 && p->mode==MODE_Csv
  21326. && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
  21327. ){
  21328. /* When importing CSV (only), if the row separator is set to the
  21329. ** default output row separator, change it to the default input
  21330. ** row separator. This avoids having to maintain different input
  21331. ** and output row separators. */
  21332. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  21333. nSep = strlen30(p->rowSeparator);
  21334. }
  21335. if( nSep>1 ){
  21336. raw_printf(stderr, "Error: multi-character row separators not allowed"
  21337. " for import\n");
  21338. goto meta_command_exit;
  21339. }
  21340. sCtx.cColSep = p->colSeparator[0];
  21341. sCtx.cRowSep = p->rowSeparator[0];
  21342. }
  21343. sCtx.zFile = zFile;
  21344. sCtx.nLine = 1;
  21345. if( sCtx.zFile[0]=='|' ){
  21346. #ifdef SQLITE_OMIT_POPEN
  21347. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  21348. goto meta_command_exit;
  21349. #else
  21350. sCtx.in = popen(sCtx.zFile+1, "r");
  21351. sCtx.zFile = "<pipe>";
  21352. sCtx.xCloser = pclose;
  21353. #endif
  21354. }else{
  21355. sCtx.in = fopen(sCtx.zFile, "rb");
  21356. sCtx.xCloser = fclose;
  21357. }
  21358. if( sCtx.in==0 ){
  21359. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  21360. goto meta_command_exit;
  21361. }
  21362. if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
  21363. char zSep[2];
  21364. zSep[1] = 0;
  21365. zSep[0] = sCtx.cColSep;
  21366. utf8_printf(p->out, "Column separator ");
  21367. output_c_string(p->out, zSep);
  21368. utf8_printf(p->out, ", row separator ");
  21369. zSep[0] = sCtx.cRowSep;
  21370. output_c_string(p->out, zSep);
  21371. utf8_printf(p->out, "\n");
  21372. }
  21373. sCtx.z = sqlite3_malloc64(120);
  21374. if( sCtx.z==0 ){
  21375. import_cleanup(&sCtx);
  21376. shell_out_of_memory();
  21377. }
  21378. /* Below, resources must be freed before exit. */
  21379. while( (nSkip--)>0 ){
  21380. while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
  21381. }
  21382. if( zSchema!=0 ){
  21383. zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
  21384. }else{
  21385. zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
  21386. }
  21387. zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
  21388. if( zSql==0 || zFullTabName==0 ){
  21389. import_cleanup(&sCtx);
  21390. shell_out_of_memory();
  21391. }
  21392. nByte = strlen30(zSql);
  21393. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  21394. import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
  21395. if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
  21396. sqlite3 *dbCols = 0;
  21397. char *zRenames = 0;
  21398. char *zColDefs;
  21399. zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
  21400. while( xRead(&sCtx) ){
  21401. zAutoColumn(sCtx.z, &dbCols, 0);
  21402. if( sCtx.cTerm!=sCtx.cColSep ) break;
  21403. }
  21404. zColDefs = zAutoColumn(0, &dbCols, &zRenames);
  21405. if( zRenames!=0 ){
  21406. utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
  21407. "Columns renamed during .import %s due to duplicates:\n"
  21408. "%s\n", sCtx.zFile, zRenames);
  21409. sqlite3_free(zRenames);
  21410. }
  21411. assert(dbCols==0);
  21412. if( zColDefs==0 ){
  21413. utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
  21414. import_fail:
  21415. sqlite3_free(zCreate);
  21416. sqlite3_free(zSql);
  21417. sqlite3_free(zFullTabName);
  21418. import_cleanup(&sCtx);
  21419. rc = 1;
  21420. goto meta_command_exit;
  21421. }
  21422. zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
  21423. if( eVerbose>=1 ){
  21424. utf8_printf(p->out, "%s\n", zCreate);
  21425. }
  21426. rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
  21427. if( rc ){
  21428. utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
  21429. goto import_fail;
  21430. }
  21431. sqlite3_free(zCreate);
  21432. zCreate = 0;
  21433. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  21434. }
  21435. if( rc ){
  21436. if (pStmt) sqlite3_finalize(pStmt);
  21437. utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
  21438. goto import_fail;
  21439. }
  21440. sqlite3_free(zSql);
  21441. nCol = sqlite3_column_count(pStmt);
  21442. sqlite3_finalize(pStmt);
  21443. pStmt = 0;
  21444. if( nCol==0 ) return 0; /* no columns, no error */
  21445. zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
  21446. if( zSql==0 ){
  21447. import_cleanup(&sCtx);
  21448. shell_out_of_memory();
  21449. }
  21450. sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
  21451. j = strlen30(zSql);
  21452. for(i=1; i<nCol; i++){
  21453. zSql[j++] = ',';
  21454. zSql[j++] = '?';
  21455. }
  21456. zSql[j++] = ')';
  21457. zSql[j] = 0;
  21458. if( eVerbose>=2 ){
  21459. utf8_printf(p->out, "Insert using: %s\n", zSql);
  21460. }
  21461. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  21462. if( rc ){
  21463. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  21464. if (pStmt) sqlite3_finalize(pStmt);
  21465. goto import_fail;
  21466. }
  21467. sqlite3_free(zSql);
  21468. sqlite3_free(zFullTabName);
  21469. needCommit = sqlite3_get_autocommit(p->db);
  21470. if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
  21471. do{
  21472. int startLine = sCtx.nLine;
  21473. for(i=0; i<nCol; i++){
  21474. char *z = xRead(&sCtx);
  21475. /*
  21476. ** Did we reach end-of-file before finding any columns?
  21477. ** If so, stop instead of NULL filling the remaining columns.
  21478. */
  21479. if( z==0 && i==0 ) break;
  21480. /*
  21481. ** Did we reach end-of-file OR end-of-line before finding any
  21482. ** columns in ASCII mode? If so, stop instead of NULL filling
  21483. ** the remaining columns.
  21484. */
  21485. if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
  21486. sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
  21487. if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
  21488. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  21489. "filling the rest with NULL\n",
  21490. sCtx.zFile, startLine, nCol, i+1);
  21491. i += 2;
  21492. while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
  21493. }
  21494. }
  21495. if( sCtx.cTerm==sCtx.cColSep ){
  21496. do{
  21497. xRead(&sCtx);
  21498. i++;
  21499. }while( sCtx.cTerm==sCtx.cColSep );
  21500. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  21501. "extras ignored\n",
  21502. sCtx.zFile, startLine, nCol, i);
  21503. }
  21504. if( i>=nCol ){
  21505. sqlite3_step(pStmt);
  21506. rc = sqlite3_reset(pStmt);
  21507. if( rc!=SQLITE_OK ){
  21508. utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
  21509. startLine, sqlite3_errmsg(p->db));
  21510. sCtx.nErr++;
  21511. }else{
  21512. sCtx.nRow++;
  21513. }
  21514. }
  21515. }while( sCtx.cTerm!=EOF );
  21516. import_cleanup(&sCtx);
  21517. sqlite3_finalize(pStmt);
  21518. if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
  21519. if( eVerbose>0 ){
  21520. utf8_printf(p->out,
  21521. "Added %d rows with %d errors using %d lines of input\n",
  21522. sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
  21523. }
  21524. }else
  21525. #endif /* !defined(SQLITE_SHELL_FIDDLE) */
  21526. #ifndef SQLITE_UNTESTABLE
  21527. if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
  21528. char *zSql;
  21529. char *zCollist = 0;
  21530. sqlite3_stmt *pStmt;
  21531. int tnum = 0;
  21532. int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */
  21533. int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
  21534. int i;
  21535. if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
  21536. utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
  21537. " .imposter off\n");
  21538. /* Also allowed, but not documented:
  21539. **
  21540. ** .imposter TABLE IMPOSTER
  21541. **
  21542. ** where TABLE is a WITHOUT ROWID table. In that case, the
  21543. ** imposter is another WITHOUT ROWID table with the columns in
  21544. ** storage order. */
  21545. rc = 1;
  21546. goto meta_command_exit;
  21547. }
  21548. open_db(p, 0);
  21549. if( nArg==2 ){
  21550. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
  21551. goto meta_command_exit;
  21552. }
  21553. zSql = sqlite3_mprintf(
  21554. "SELECT rootpage, 0 FROM sqlite_schema"
  21555. " WHERE name='%q' AND type='index'"
  21556. "UNION ALL "
  21557. "SELECT rootpage, 1 FROM sqlite_schema"
  21558. " WHERE name='%q' AND type='table'"
  21559. " AND sql LIKE '%%without%%rowid%%'",
  21560. azArg[1], azArg[1]
  21561. );
  21562. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  21563. sqlite3_free(zSql);
  21564. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  21565. tnum = sqlite3_column_int(pStmt, 0);
  21566. isWO = sqlite3_column_int(pStmt, 1);
  21567. }
  21568. sqlite3_finalize(pStmt);
  21569. zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
  21570. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  21571. sqlite3_free(zSql);
  21572. i = 0;
  21573. while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
  21574. char zLabel[20];
  21575. const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
  21576. i++;
  21577. if( zCol==0 ){
  21578. if( sqlite3_column_int(pStmt,1)==-1 ){
  21579. zCol = "_ROWID_";
  21580. }else{
  21581. sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
  21582. zCol = zLabel;
  21583. }
  21584. }
  21585. if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
  21586. lenPK = (int)strlen(zCollist);
  21587. }
  21588. if( zCollist==0 ){
  21589. zCollist = sqlite3_mprintf("\"%w\"", zCol);
  21590. }else{
  21591. zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
  21592. }
  21593. }
  21594. sqlite3_finalize(pStmt);
  21595. if( i==0 || tnum==0 ){
  21596. utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
  21597. rc = 1;
  21598. sqlite3_free(zCollist);
  21599. goto meta_command_exit;
  21600. }
  21601. if( lenPK==0 ) lenPK = 100000;
  21602. zSql = sqlite3_mprintf(
  21603. "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
  21604. azArg[2], zCollist, lenPK, zCollist);
  21605. sqlite3_free(zCollist);
  21606. rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
  21607. if( rc==SQLITE_OK ){
  21608. rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
  21609. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
  21610. if( rc ){
  21611. utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
  21612. }else{
  21613. utf8_printf(stdout, "%s;\n", zSql);
  21614. raw_printf(stdout,
  21615. "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
  21616. azArg[1], isWO ? "table" : "index"
  21617. );
  21618. }
  21619. }else{
  21620. raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
  21621. rc = 1;
  21622. }
  21623. sqlite3_free(zSql);
  21624. }else
  21625. #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
  21626. #ifdef SQLITE_ENABLE_IOTRACE
  21627. if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
  21628. SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
  21629. if( iotrace && iotrace!=stdout ) fclose(iotrace);
  21630. iotrace = 0;
  21631. if( nArg<2 ){
  21632. sqlite3IoTrace = 0;
  21633. }else if( cli_strcmp(azArg[1], "-")==0 ){
  21634. sqlite3IoTrace = iotracePrintf;
  21635. iotrace = stdout;
  21636. }else{
  21637. iotrace = fopen(azArg[1], "w");
  21638. if( iotrace==0 ){
  21639. utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  21640. sqlite3IoTrace = 0;
  21641. rc = 1;
  21642. }else{
  21643. sqlite3IoTrace = iotracePrintf;
  21644. }
  21645. }
  21646. }else
  21647. #endif
  21648. if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
  21649. static const struct {
  21650. const char *zLimitName; /* Name of a limit */
  21651. int limitCode; /* Integer code for that limit */
  21652. } aLimit[] = {
  21653. { "length", SQLITE_LIMIT_LENGTH },
  21654. { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
  21655. { "column", SQLITE_LIMIT_COLUMN },
  21656. { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
  21657. { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
  21658. { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
  21659. { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
  21660. { "attached", SQLITE_LIMIT_ATTACHED },
  21661. { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
  21662. { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
  21663. { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
  21664. { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
  21665. };
  21666. int i, n2;
  21667. open_db(p, 0);
  21668. if( nArg==1 ){
  21669. for(i=0; i<ArraySize(aLimit); i++){
  21670. printf("%20s %d\n", aLimit[i].zLimitName,
  21671. sqlite3_limit(p->db, aLimit[i].limitCode, -1));
  21672. }
  21673. }else if( nArg>3 ){
  21674. raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
  21675. rc = 1;
  21676. goto meta_command_exit;
  21677. }else{
  21678. int iLimit = -1;
  21679. n2 = strlen30(azArg[1]);
  21680. for(i=0; i<ArraySize(aLimit); i++){
  21681. if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
  21682. if( iLimit<0 ){
  21683. iLimit = i;
  21684. }else{
  21685. utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
  21686. rc = 1;
  21687. goto meta_command_exit;
  21688. }
  21689. }
  21690. }
  21691. if( iLimit<0 ){
  21692. utf8_printf(stderr, "unknown limit: \"%s\"\n"
  21693. "enter \".limits\" with no arguments for a list.\n",
  21694. azArg[1]);
  21695. rc = 1;
  21696. goto meta_command_exit;
  21697. }
  21698. if( nArg==3 ){
  21699. sqlite3_limit(p->db, aLimit[iLimit].limitCode,
  21700. (int)integerValue(azArg[2]));
  21701. }
  21702. printf("%20s %d\n", aLimit[iLimit].zLimitName,
  21703. sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
  21704. }
  21705. }else
  21706. if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
  21707. open_db(p, 0);
  21708. lintDotCommand(p, azArg, nArg);
  21709. }else
  21710. #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
  21711. if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
  21712. const char *zFile, *zProc;
  21713. char *zErrMsg = 0;
  21714. failIfSafeMode(p, "cannot run .load in safe mode");
  21715. if( nArg<2 ){
  21716. raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
  21717. rc = 1;
  21718. goto meta_command_exit;
  21719. }
  21720. zFile = azArg[1];
  21721. zProc = nArg>=3 ? azArg[2] : 0;
  21722. open_db(p, 0);
  21723. rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  21724. if( rc!=SQLITE_OK ){
  21725. utf8_printf(stderr, "Error: %s\n", zErrMsg);
  21726. sqlite3_free(zErrMsg);
  21727. rc = 1;
  21728. }
  21729. }else
  21730. #endif
  21731. #ifndef SQLITE_SHELL_FIDDLE
  21732. if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
  21733. failIfSafeMode(p, "cannot run .log in safe mode");
  21734. if( nArg!=2 ){
  21735. raw_printf(stderr, "Usage: .log FILENAME\n");
  21736. rc = 1;
  21737. }else{
  21738. const char *zFile = azArg[1];
  21739. output_file_close(p->pLog);
  21740. p->pLog = output_file_open(zFile, 0);
  21741. }
  21742. }else
  21743. #endif
  21744. if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
  21745. const char *zMode = 0;
  21746. const char *zTabname = 0;
  21747. int i, n2;
  21748. ColModeOpts cmOpts = ColModeOpts_default;
  21749. for(i=1; i<nArg; i++){
  21750. const char *z = azArg[i];
  21751. if( optionMatch(z,"wrap") && i+1<nArg ){
  21752. cmOpts.iWrap = integerValue(azArg[++i]);
  21753. }else if( optionMatch(z,"ww") ){
  21754. cmOpts.bWordWrap = 1;
  21755. }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
  21756. cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
  21757. }else if( optionMatch(z,"quote") ){
  21758. cmOpts.bQuote = 1;
  21759. }else if( optionMatch(z,"noquote") ){
  21760. cmOpts.bQuote = 0;
  21761. }else if( zMode==0 ){
  21762. zMode = z;
  21763. /* Apply defaults for qbox pseudo-mode. If that
  21764. * overwrites already-set values, user was informed of this.
  21765. */
  21766. if( cli_strcmp(z, "qbox")==0 ){
  21767. ColModeOpts cmo = ColModeOpts_default_qbox;
  21768. zMode = "box";
  21769. cmOpts = cmo;
  21770. }
  21771. }else if( zTabname==0 ){
  21772. zTabname = z;
  21773. }else if( z[0]=='-' ){
  21774. utf8_printf(stderr, "unknown option: %s\n", z);
  21775. utf8_printf(stderr, "options:\n"
  21776. " --noquote\n"
  21777. " --quote\n"
  21778. " --wordwrap on/off\n"
  21779. " --wrap N\n"
  21780. " --ww\n");
  21781. rc = 1;
  21782. goto meta_command_exit;
  21783. }else{
  21784. utf8_printf(stderr, "extra argument: \"%s\"\n", z);
  21785. rc = 1;
  21786. goto meta_command_exit;
  21787. }
  21788. }
  21789. if( zMode==0 ){
  21790. if( p->mode==MODE_Column
  21791. || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
  21792. ){
  21793. raw_printf
  21794. (p->out,
  21795. "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
  21796. modeDescr[p->mode], p->cmOpts.iWrap,
  21797. p->cmOpts.bWordWrap ? "on" : "off",
  21798. p->cmOpts.bQuote ? "" : "no");
  21799. }else{
  21800. raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
  21801. }
  21802. zMode = modeDescr[p->mode];
  21803. }
  21804. n2 = strlen30(zMode);
  21805. if( cli_strncmp(zMode,"lines",n2)==0 ){
  21806. p->mode = MODE_Line;
  21807. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  21808. }else if( cli_strncmp(zMode,"columns",n2)==0 ){
  21809. p->mode = MODE_Column;
  21810. if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
  21811. p->showHeader = 1;
  21812. }
  21813. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  21814. p->cmOpts = cmOpts;
  21815. }else if( cli_strncmp(zMode,"list",n2)==0 ){
  21816. p->mode = MODE_List;
  21817. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
  21818. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  21819. }else if( cli_strncmp(zMode,"html",n2)==0 ){
  21820. p->mode = MODE_Html;
  21821. }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
  21822. p->mode = MODE_Tcl;
  21823. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
  21824. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  21825. }else if( cli_strncmp(zMode,"csv",n2)==0 ){
  21826. p->mode = MODE_Csv;
  21827. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  21828. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  21829. }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
  21830. p->mode = MODE_List;
  21831. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
  21832. }else if( cli_strncmp(zMode,"insert",n2)==0 ){
  21833. p->mode = MODE_Insert;
  21834. set_table_name(p, zTabname ? zTabname : "table");
  21835. }else if( cli_strncmp(zMode,"quote",n2)==0 ){
  21836. p->mode = MODE_Quote;
  21837. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  21838. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  21839. }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
  21840. p->mode = MODE_Ascii;
  21841. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
  21842. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
  21843. }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
  21844. p->mode = MODE_Markdown;
  21845. p->cmOpts = cmOpts;
  21846. }else if( cli_strncmp(zMode,"table",n2)==0 ){
  21847. p->mode = MODE_Table;
  21848. p->cmOpts = cmOpts;
  21849. }else if( cli_strncmp(zMode,"box",n2)==0 ){
  21850. p->mode = MODE_Box;
  21851. p->cmOpts = cmOpts;
  21852. }else if( cli_strncmp(zMode,"count",n2)==0 ){
  21853. p->mode = MODE_Count;
  21854. }else if( cli_strncmp(zMode,"off",n2)==0 ){
  21855. p->mode = MODE_Off;
  21856. }else if( cli_strncmp(zMode,"json",n2)==0 ){
  21857. p->mode = MODE_Json;
  21858. }else{
  21859. raw_printf(stderr, "Error: mode should be one of: "
  21860. "ascii box column csv html insert json line list markdown "
  21861. "qbox quote table tabs tcl\n");
  21862. rc = 1;
  21863. }
  21864. p->cMode = p->mode;
  21865. }else
  21866. #ifndef SQLITE_SHELL_FIDDLE
  21867. if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
  21868. if( nArg!=2 ){
  21869. raw_printf(stderr, "Usage: .nonce NONCE\n");
  21870. rc = 1;
  21871. }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
  21872. raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
  21873. p->lineno, azArg[1]);
  21874. exit(1);
  21875. }else{
  21876. p->bSafeMode = 0;
  21877. return 0; /* Return immediately to bypass the safe mode reset
  21878. ** at the end of this procedure */
  21879. }
  21880. }else
  21881. #endif /* !defined(SQLITE_SHELL_FIDDLE) */
  21882. if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
  21883. if( nArg==2 ){
  21884. sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
  21885. "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
  21886. }else{
  21887. raw_printf(stderr, "Usage: .nullvalue STRING\n");
  21888. rc = 1;
  21889. }
  21890. }else
  21891. if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
  21892. const char *zFN = 0; /* Pointer to constant filename */
  21893. char *zNewFilename = 0; /* Name of the database file to open */
  21894. int iName = 1; /* Index in azArg[] of the filename */
  21895. int newFlag = 0; /* True to delete file before opening */
  21896. int openMode = SHELL_OPEN_UNSPEC;
  21897. /* Check for command-line arguments */
  21898. for(iName=1; iName<nArg; iName++){
  21899. const char *z = azArg[iName];
  21900. #ifndef SQLITE_SHELL_FIDDLE
  21901. if( optionMatch(z,"new") ){
  21902. newFlag = 1;
  21903. #ifdef SQLITE_HAVE_ZLIB
  21904. }else if( optionMatch(z, "zip") ){
  21905. openMode = SHELL_OPEN_ZIPFILE;
  21906. #endif
  21907. }else if( optionMatch(z, "append") ){
  21908. openMode = SHELL_OPEN_APPENDVFS;
  21909. }else if( optionMatch(z, "readonly") ){
  21910. openMode = SHELL_OPEN_READONLY;
  21911. }else if( optionMatch(z, "nofollow") ){
  21912. p->openFlags |= SQLITE_OPEN_NOFOLLOW;
  21913. #ifndef SQLITE_OMIT_DESERIALIZE
  21914. }else if( optionMatch(z, "deserialize") ){
  21915. openMode = SHELL_OPEN_DESERIALIZE;
  21916. }else if( optionMatch(z, "hexdb") ){
  21917. openMode = SHELL_OPEN_HEXDB;
  21918. }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
  21919. p->szMax = integerValue(azArg[++iName]);
  21920. #endif /* SQLITE_OMIT_DESERIALIZE */
  21921. }else
  21922. #endif /* !SQLITE_SHELL_FIDDLE */
  21923. if( z[0]=='-' ){
  21924. utf8_printf(stderr, "unknown option: %s\n", z);
  21925. rc = 1;
  21926. goto meta_command_exit;
  21927. }else if( zFN ){
  21928. utf8_printf(stderr, "extra argument: \"%s\"\n", z);
  21929. rc = 1;
  21930. goto meta_command_exit;
  21931. }else{
  21932. zFN = z;
  21933. }
  21934. }
  21935. /* Close the existing database */
  21936. session_close_all(p, -1);
  21937. close_db(p->db);
  21938. p->db = 0;
  21939. p->pAuxDb->zDbFilename = 0;
  21940. sqlite3_free(p->pAuxDb->zFreeOnClose);
  21941. p->pAuxDb->zFreeOnClose = 0;
  21942. p->openMode = openMode;
  21943. p->openFlags = 0;
  21944. p->szMax = 0;
  21945. /* If a filename is specified, try to open it first */
  21946. if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
  21947. if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
  21948. #ifndef SQLITE_SHELL_FIDDLE
  21949. if( p->bSafeMode
  21950. && p->openMode!=SHELL_OPEN_HEXDB
  21951. && zFN
  21952. && cli_strcmp(zFN,":memory:")!=0
  21953. ){
  21954. failIfSafeMode(p, "cannot open disk-based database files in safe mode");
  21955. }
  21956. #else
  21957. /* WASM mode has its own sandboxed pseudo-filesystem. */
  21958. #endif
  21959. if( zFN ){
  21960. zNewFilename = sqlite3_mprintf("%s", zFN);
  21961. shell_check_oom(zNewFilename);
  21962. }else{
  21963. zNewFilename = 0;
  21964. }
  21965. p->pAuxDb->zDbFilename = zNewFilename;
  21966. open_db(p, OPEN_DB_KEEPALIVE);
  21967. if( p->db==0 ){
  21968. utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
  21969. sqlite3_free(zNewFilename);
  21970. }else{
  21971. p->pAuxDb->zFreeOnClose = zNewFilename;
  21972. }
  21973. }
  21974. if( p->db==0 ){
  21975. /* As a fall-back open a TEMP database */
  21976. p->pAuxDb->zDbFilename = 0;
  21977. open_db(p, 0);
  21978. }
  21979. }else
  21980. #ifndef SQLITE_SHELL_FIDDLE
  21981. if( (c=='o'
  21982. && (cli_strncmp(azArg[0], "output", n)==0
  21983. || cli_strncmp(azArg[0], "once", n)==0))
  21984. || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
  21985. ){
  21986. char *zFile = 0;
  21987. int bTxtMode = 0;
  21988. int i;
  21989. int eMode = 0;
  21990. int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */
  21991. unsigned char zBOM[4]; /* Byte-order mark to using if --bom is present */
  21992. zBOM[0] = 0;
  21993. failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
  21994. if( c=='e' ){
  21995. eMode = 'x';
  21996. bOnce = 2;
  21997. }else if( cli_strncmp(azArg[0],"once",n)==0 ){
  21998. bOnce = 1;
  21999. }
  22000. for(i=1; i<nArg; i++){
  22001. char *z = azArg[i];
  22002. if( z[0]=='-' ){
  22003. if( z[1]=='-' ) z++;
  22004. if( cli_strcmp(z,"-bom")==0 ){
  22005. zBOM[0] = 0xef;
  22006. zBOM[1] = 0xbb;
  22007. zBOM[2] = 0xbf;
  22008. zBOM[3] = 0;
  22009. }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
  22010. eMode = 'x'; /* spreadsheet */
  22011. }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
  22012. eMode = 'e'; /* text editor */
  22013. }else{
  22014. utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n",
  22015. azArg[i]);
  22016. showHelp(p->out, azArg[0]);
  22017. rc = 1;
  22018. goto meta_command_exit;
  22019. }
  22020. }else if( zFile==0 && eMode!='e' && eMode!='x' ){
  22021. zFile = sqlite3_mprintf("%s", z);
  22022. if( zFile && zFile[0]=='|' ){
  22023. while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
  22024. break;
  22025. }
  22026. }else{
  22027. utf8_printf(p->out,"ERROR: extra parameter: \"%s\". Usage:\n",
  22028. azArg[i]);
  22029. showHelp(p->out, azArg[0]);
  22030. rc = 1;
  22031. sqlite3_free(zFile);
  22032. goto meta_command_exit;
  22033. }
  22034. }
  22035. if( zFile==0 ){
  22036. zFile = sqlite3_mprintf("stdout");
  22037. }
  22038. if( bOnce ){
  22039. p->outCount = 2;
  22040. }else{
  22041. p->outCount = 0;
  22042. }
  22043. output_reset(p);
  22044. #ifndef SQLITE_NOHAVE_SYSTEM
  22045. if( eMode=='e' || eMode=='x' ){
  22046. p->doXdgOpen = 1;
  22047. outputModePush(p);
  22048. if( eMode=='x' ){
  22049. /* spreadsheet mode. Output as CSV. */
  22050. newTempFile(p, "csv");
  22051. ShellClearFlag(p, SHFLG_Echo);
  22052. p->mode = MODE_Csv;
  22053. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  22054. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  22055. }else{
  22056. /* text editor mode */
  22057. newTempFile(p, "txt");
  22058. bTxtMode = 1;
  22059. }
  22060. sqlite3_free(zFile);
  22061. zFile = sqlite3_mprintf("%s", p->zTempFile);
  22062. }
  22063. #endif /* SQLITE_NOHAVE_SYSTEM */
  22064. shell_check_oom(zFile);
  22065. if( zFile[0]=='|' ){
  22066. #ifdef SQLITE_OMIT_POPEN
  22067. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  22068. rc = 1;
  22069. p->out = stdout;
  22070. #else
  22071. p->out = popen(zFile + 1, "w");
  22072. if( p->out==0 ){
  22073. utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
  22074. p->out = stdout;
  22075. rc = 1;
  22076. }else{
  22077. if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
  22078. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  22079. }
  22080. #endif
  22081. }else{
  22082. p->out = output_file_open(zFile, bTxtMode);
  22083. if( p->out==0 ){
  22084. if( cli_strcmp(zFile,"off")!=0 ){
  22085. utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
  22086. }
  22087. p->out = stdout;
  22088. rc = 1;
  22089. } else {
  22090. if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
  22091. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  22092. }
  22093. }
  22094. sqlite3_free(zFile);
  22095. }else
  22096. #endif /* !defined(SQLITE_SHELL_FIDDLE) */
  22097. if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
  22098. open_db(p,0);
  22099. if( nArg<=1 ) goto parameter_syntax_error;
  22100. /* .parameter clear
  22101. ** Clear all bind parameters by dropping the TEMP table that holds them.
  22102. */
  22103. if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
  22104. sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
  22105. 0, 0, 0);
  22106. }else
  22107. /* .parameter list
  22108. ** List all bind parameters.
  22109. */
  22110. if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
  22111. sqlite3_stmt *pStmt = 0;
  22112. int rx;
  22113. int len = 0;
  22114. rx = sqlite3_prepare_v2(p->db,
  22115. "SELECT max(length(key)) "
  22116. "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
  22117. if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
  22118. len = sqlite3_column_int(pStmt, 0);
  22119. if( len>40 ) len = 40;
  22120. }
  22121. sqlite3_finalize(pStmt);
  22122. pStmt = 0;
  22123. if( len ){
  22124. rx = sqlite3_prepare_v2(p->db,
  22125. "SELECT key, quote(value) "
  22126. "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
  22127. while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
  22128. utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
  22129. sqlite3_column_text(pStmt,1));
  22130. }
  22131. sqlite3_finalize(pStmt);
  22132. }
  22133. }else
  22134. /* .parameter init
  22135. ** Make sure the TEMP table used to hold bind parameters exists.
  22136. ** Create it if necessary.
  22137. */
  22138. if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
  22139. bind_table_init(p);
  22140. }else
  22141. /* .parameter set NAME VALUE
  22142. ** Set or reset a bind parameter. NAME should be the full parameter
  22143. ** name exactly as it appears in the query. (ex: $abc, @def). The
  22144. ** VALUE can be in either SQL literal notation, or if not it will be
  22145. ** understood to be a text string.
  22146. */
  22147. if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
  22148. int rx;
  22149. char *zSql;
  22150. sqlite3_stmt *pStmt;
  22151. const char *zKey = azArg[2];
  22152. const char *zValue = azArg[3];
  22153. bind_table_init(p);
  22154. zSql = sqlite3_mprintf(
  22155. "REPLACE INTO temp.sqlite_parameters(key,value)"
  22156. "VALUES(%Q,%s);", zKey, zValue);
  22157. shell_check_oom(zSql);
  22158. pStmt = 0;
  22159. rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  22160. sqlite3_free(zSql);
  22161. if( rx!=SQLITE_OK ){
  22162. sqlite3_finalize(pStmt);
  22163. pStmt = 0;
  22164. zSql = sqlite3_mprintf(
  22165. "REPLACE INTO temp.sqlite_parameters(key,value)"
  22166. "VALUES(%Q,%Q);", zKey, zValue);
  22167. shell_check_oom(zSql);
  22168. rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  22169. sqlite3_free(zSql);
  22170. if( rx!=SQLITE_OK ){
  22171. utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
  22172. sqlite3_finalize(pStmt);
  22173. pStmt = 0;
  22174. rc = 1;
  22175. }
  22176. }
  22177. sqlite3_step(pStmt);
  22178. sqlite3_finalize(pStmt);
  22179. }else
  22180. /* .parameter unset NAME
  22181. ** Remove the NAME binding from the parameter binding table, if it
  22182. ** exists.
  22183. */
  22184. if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
  22185. char *zSql = sqlite3_mprintf(
  22186. "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
  22187. shell_check_oom(zSql);
  22188. sqlite3_exec(p->db, zSql, 0, 0, 0);
  22189. sqlite3_free(zSql);
  22190. }else
  22191. /* If no command name matches, show a syntax error */
  22192. parameter_syntax_error:
  22193. showHelp(p->out, "parameter");
  22194. }else
  22195. if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
  22196. int i;
  22197. for(i=1; i<nArg; i++){
  22198. if( i>1 ) raw_printf(p->out, " ");
  22199. utf8_printf(p->out, "%s", azArg[i]);
  22200. }
  22201. raw_printf(p->out, "\n");
  22202. }else
  22203. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  22204. if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
  22205. int i;
  22206. int nn = 0;
  22207. p->flgProgress = 0;
  22208. p->mxProgress = 0;
  22209. p->nProgress = 0;
  22210. for(i=1; i<nArg; i++){
  22211. const char *z = azArg[i];
  22212. if( z[0]=='-' ){
  22213. z++;
  22214. if( z[0]=='-' ) z++;
  22215. if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
  22216. p->flgProgress |= SHELL_PROGRESS_QUIET;
  22217. continue;
  22218. }
  22219. if( cli_strcmp(z,"reset")==0 ){
  22220. p->flgProgress |= SHELL_PROGRESS_RESET;
  22221. continue;
  22222. }
  22223. if( cli_strcmp(z,"once")==0 ){
  22224. p->flgProgress |= SHELL_PROGRESS_ONCE;
  22225. continue;
  22226. }
  22227. if( cli_strcmp(z,"limit")==0 ){
  22228. if( i+1>=nArg ){
  22229. utf8_printf(stderr, "Error: missing argument on --limit\n");
  22230. rc = 1;
  22231. goto meta_command_exit;
  22232. }else{
  22233. p->mxProgress = (int)integerValue(azArg[++i]);
  22234. }
  22235. continue;
  22236. }
  22237. utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
  22238. rc = 1;
  22239. goto meta_command_exit;
  22240. }else{
  22241. nn = (int)integerValue(z);
  22242. }
  22243. }
  22244. open_db(p, 0);
  22245. sqlite3_progress_handler(p->db, nn, progress_handler, p);
  22246. }else
  22247. #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
  22248. if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
  22249. if( nArg >= 2) {
  22250. strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  22251. }
  22252. if( nArg >= 3) {
  22253. strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  22254. }
  22255. }else
  22256. #ifndef SQLITE_SHELL_FIDDLE
  22257. if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
  22258. rc = 2;
  22259. }else
  22260. #endif
  22261. #ifndef SQLITE_SHELL_FIDDLE
  22262. if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
  22263. FILE *inSaved = p->in;
  22264. int savedLineno = p->lineno;
  22265. failIfSafeMode(p, "cannot run .read in safe mode");
  22266. if( nArg!=2 ){
  22267. raw_printf(stderr, "Usage: .read FILE\n");
  22268. rc = 1;
  22269. goto meta_command_exit;
  22270. }
  22271. if( azArg[1][0]=='|' ){
  22272. #ifdef SQLITE_OMIT_POPEN
  22273. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  22274. rc = 1;
  22275. p->out = stdout;
  22276. #else
  22277. p->in = popen(azArg[1]+1, "r");
  22278. if( p->in==0 ){
  22279. utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  22280. rc = 1;
  22281. }else{
  22282. rc = process_input(p);
  22283. pclose(p->in);
  22284. }
  22285. #endif
  22286. }else if( (p->in = openChrSource(azArg[1]))==0 ){
  22287. utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
  22288. rc = 1;
  22289. }else{
  22290. rc = process_input(p);
  22291. fclose(p->in);
  22292. }
  22293. p->in = inSaved;
  22294. p->lineno = savedLineno;
  22295. }else
  22296. #endif /* !defined(SQLITE_SHELL_FIDDLE) */
  22297. #ifndef SQLITE_SHELL_FIDDLE
  22298. if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
  22299. const char *zSrcFile;
  22300. const char *zDb;
  22301. sqlite3 *pSrc;
  22302. sqlite3_backup *pBackup;
  22303. int nTimeout = 0;
  22304. failIfSafeMode(p, "cannot run .restore in safe mode");
  22305. if( nArg==2 ){
  22306. zSrcFile = azArg[1];
  22307. zDb = "main";
  22308. }else if( nArg==3 ){
  22309. zSrcFile = azArg[2];
  22310. zDb = azArg[1];
  22311. }else{
  22312. raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
  22313. rc = 1;
  22314. goto meta_command_exit;
  22315. }
  22316. rc = sqlite3_open(zSrcFile, &pSrc);
  22317. if( rc!=SQLITE_OK ){
  22318. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  22319. close_db(pSrc);
  22320. return 1;
  22321. }
  22322. open_db(p, 0);
  22323. pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  22324. if( pBackup==0 ){
  22325. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  22326. close_db(pSrc);
  22327. return 1;
  22328. }
  22329. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  22330. || rc==SQLITE_BUSY ){
  22331. if( rc==SQLITE_BUSY ){
  22332. if( nTimeout++ >= 3 ) break;
  22333. sqlite3_sleep(100);
  22334. }
  22335. }
  22336. sqlite3_backup_finish(pBackup);
  22337. if( rc==SQLITE_DONE ){
  22338. rc = 0;
  22339. }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  22340. raw_printf(stderr, "Error: source database is busy\n");
  22341. rc = 1;
  22342. }else{
  22343. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  22344. rc = 1;
  22345. }
  22346. close_db(pSrc);
  22347. }else
  22348. #endif /* !defined(SQLITE_SHELL_FIDDLE) */
  22349. if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
  22350. if( nArg==2 ){
  22351. p->scanstatsOn = (u8)booleanValue(azArg[1]);
  22352. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  22353. raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
  22354. #endif
  22355. }else{
  22356. raw_printf(stderr, "Usage: .scanstats on|off\n");
  22357. rc = 1;
  22358. }
  22359. }else
  22360. if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
  22361. ShellText sSelect;
  22362. ShellState data;
  22363. char *zErrMsg = 0;
  22364. const char *zDiv = "(";
  22365. const char *zName = 0;
  22366. int iSchema = 0;
  22367. int bDebug = 0;
  22368. int bNoSystemTabs = 0;
  22369. int ii;
  22370. open_db(p, 0);
  22371. memcpy(&data, p, sizeof(data));
  22372. data.showHeader = 0;
  22373. data.cMode = data.mode = MODE_Semi;
  22374. initText(&sSelect);
  22375. for(ii=1; ii<nArg; ii++){
  22376. if( optionMatch(azArg[ii],"indent") ){
  22377. data.cMode = data.mode = MODE_Pretty;
  22378. }else if( optionMatch(azArg[ii],"debug") ){
  22379. bDebug = 1;
  22380. }else if( optionMatch(azArg[ii],"nosys") ){
  22381. bNoSystemTabs = 1;
  22382. }else if( azArg[ii][0]=='-' ){
  22383. utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
  22384. rc = 1;
  22385. goto meta_command_exit;
  22386. }else if( zName==0 ){
  22387. zName = azArg[ii];
  22388. }else{
  22389. raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
  22390. rc = 1;
  22391. goto meta_command_exit;
  22392. }
  22393. }
  22394. if( zName!=0 ){
  22395. int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
  22396. || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
  22397. || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
  22398. || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
  22399. if( isSchema ){
  22400. char *new_argv[2], *new_colv[2];
  22401. new_argv[0] = sqlite3_mprintf(
  22402. "CREATE TABLE %s (\n"
  22403. " type text,\n"
  22404. " name text,\n"
  22405. " tbl_name text,\n"
  22406. " rootpage integer,\n"
  22407. " sql text\n"
  22408. ")", zName);
  22409. shell_check_oom(new_argv[0]);
  22410. new_argv[1] = 0;
  22411. new_colv[0] = "sql";
  22412. new_colv[1] = 0;
  22413. callback(&data, 1, new_argv, new_colv);
  22414. sqlite3_free(new_argv[0]);
  22415. }
  22416. }
  22417. if( zDiv ){
  22418. sqlite3_stmt *pStmt = 0;
  22419. rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
  22420. -1, &pStmt, 0);
  22421. if( rc ){
  22422. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  22423. sqlite3_finalize(pStmt);
  22424. rc = 1;
  22425. goto meta_command_exit;
  22426. }
  22427. appendText(&sSelect, "SELECT sql FROM", 0);
  22428. iSchema = 0;
  22429. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  22430. const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
  22431. char zScNum[30];
  22432. sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
  22433. appendText(&sSelect, zDiv, 0);
  22434. zDiv = " UNION ALL ";
  22435. appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
  22436. if( sqlite3_stricmp(zDb, "main")!=0 ){
  22437. appendText(&sSelect, zDb, '\'');
  22438. }else{
  22439. appendText(&sSelect, "NULL", 0);
  22440. }
  22441. appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
  22442. appendText(&sSelect, zScNum, 0);
  22443. appendText(&sSelect, " AS snum, ", 0);
  22444. appendText(&sSelect, zDb, '\'');
  22445. appendText(&sSelect, " AS sname FROM ", 0);
  22446. appendText(&sSelect, zDb, quoteChar(zDb));
  22447. appendText(&sSelect, ".sqlite_schema", 0);
  22448. }
  22449. sqlite3_finalize(pStmt);
  22450. #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
  22451. if( zName ){
  22452. appendText(&sSelect,
  22453. " UNION ALL SELECT shell_module_schema(name),"
  22454. " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
  22455. 0);
  22456. }
  22457. #endif
  22458. appendText(&sSelect, ") WHERE ", 0);
  22459. if( zName ){
  22460. char *zQarg = sqlite3_mprintf("%Q", zName);
  22461. int bGlob;
  22462. shell_check_oom(zQarg);
  22463. bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
  22464. strchr(zName, '[') != 0;
  22465. if( strchr(zName, '.') ){
  22466. appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
  22467. }else{
  22468. appendText(&sSelect, "lower(tbl_name)", 0);
  22469. }
  22470. appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
  22471. appendText(&sSelect, zQarg, 0);
  22472. if( !bGlob ){
  22473. appendText(&sSelect, " ESCAPE '\\' ", 0);
  22474. }
  22475. appendText(&sSelect, " AND ", 0);
  22476. sqlite3_free(zQarg);
  22477. }
  22478. if( bNoSystemTabs ){
  22479. appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
  22480. }
  22481. appendText(&sSelect, "sql IS NOT NULL"
  22482. " ORDER BY snum, rowid", 0);
  22483. if( bDebug ){
  22484. utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
  22485. }else{
  22486. rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
  22487. }
  22488. freeText(&sSelect);
  22489. }
  22490. if( zErrMsg ){
  22491. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  22492. sqlite3_free(zErrMsg);
  22493. rc = 1;
  22494. }else if( rc != SQLITE_OK ){
  22495. raw_printf(stderr,"Error: querying schema information\n");
  22496. rc = 1;
  22497. }else{
  22498. rc = 0;
  22499. }
  22500. }else
  22501. if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
  22502. || (c=='t' && n==9 && cli_strncmp(azArg[0], "treetrace", n)==0)
  22503. ){
  22504. unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
  22505. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
  22506. }else
  22507. #if defined(SQLITE_ENABLE_SESSION)
  22508. if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
  22509. struct AuxDb *pAuxDb = p->pAuxDb;
  22510. OpenSession *pSession = &pAuxDb->aSession[0];
  22511. char **azCmd = &azArg[1];
  22512. int iSes = 0;
  22513. int nCmd = nArg - 1;
  22514. int i;
  22515. if( nArg<=1 ) goto session_syntax_error;
  22516. open_db(p, 0);
  22517. if( nArg>=3 ){
  22518. for(iSes=0; iSes<pAuxDb->nSession; iSes++){
  22519. if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
  22520. }
  22521. if( iSes<pAuxDb->nSession ){
  22522. pSession = &pAuxDb->aSession[iSes];
  22523. azCmd++;
  22524. nCmd--;
  22525. }else{
  22526. pSession = &pAuxDb->aSession[0];
  22527. iSes = 0;
  22528. }
  22529. }
  22530. /* .session attach TABLE
  22531. ** Invoke the sqlite3session_attach() interface to attach a particular
  22532. ** table so that it is never filtered.
  22533. */
  22534. if( cli_strcmp(azCmd[0],"attach")==0 ){
  22535. if( nCmd!=2 ) goto session_syntax_error;
  22536. if( pSession->p==0 ){
  22537. session_not_open:
  22538. raw_printf(stderr, "ERROR: No sessions are open\n");
  22539. }else{
  22540. rc = sqlite3session_attach(pSession->p, azCmd[1]);
  22541. if( rc ){
  22542. raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
  22543. rc = 0;
  22544. }
  22545. }
  22546. }else
  22547. /* .session changeset FILE
  22548. ** .session patchset FILE
  22549. ** Write a changeset or patchset into a file. The file is overwritten.
  22550. */
  22551. if( cli_strcmp(azCmd[0],"changeset")==0
  22552. || cli_strcmp(azCmd[0],"patchset")==0
  22553. ){
  22554. FILE *out = 0;
  22555. failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
  22556. if( nCmd!=2 ) goto session_syntax_error;
  22557. if( pSession->p==0 ) goto session_not_open;
  22558. out = fopen(azCmd[1], "wb");
  22559. if( out==0 ){
  22560. utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
  22561. azCmd[1]);
  22562. }else{
  22563. int szChng;
  22564. void *pChng;
  22565. if( azCmd[0][0]=='c' ){
  22566. rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
  22567. }else{
  22568. rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
  22569. }
  22570. if( rc ){
  22571. printf("Error: error code %d\n", rc);
  22572. rc = 0;
  22573. }
  22574. if( pChng
  22575. && fwrite(pChng, szChng, 1, out)!=1 ){
  22576. raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
  22577. szChng);
  22578. }
  22579. sqlite3_free(pChng);
  22580. fclose(out);
  22581. }
  22582. }else
  22583. /* .session close
  22584. ** Close the identified session
  22585. */
  22586. if( cli_strcmp(azCmd[0], "close")==0 ){
  22587. if( nCmd!=1 ) goto session_syntax_error;
  22588. if( pAuxDb->nSession ){
  22589. session_close(pSession);
  22590. pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
  22591. }
  22592. }else
  22593. /* .session enable ?BOOLEAN?
  22594. ** Query or set the enable flag
  22595. */
  22596. if( cli_strcmp(azCmd[0], "enable")==0 ){
  22597. int ii;
  22598. if( nCmd>2 ) goto session_syntax_error;
  22599. ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  22600. if( pAuxDb->nSession ){
  22601. ii = sqlite3session_enable(pSession->p, ii);
  22602. utf8_printf(p->out, "session %s enable flag = %d\n",
  22603. pSession->zName, ii);
  22604. }
  22605. }else
  22606. /* .session filter GLOB ....
  22607. ** Set a list of GLOB patterns of table names to be excluded.
  22608. */
  22609. if( cli_strcmp(azCmd[0], "filter")==0 ){
  22610. int ii, nByte;
  22611. if( nCmd<2 ) goto session_syntax_error;
  22612. if( pAuxDb->nSession ){
  22613. for(ii=0; ii<pSession->nFilter; ii++){
  22614. sqlite3_free(pSession->azFilter[ii]);
  22615. }
  22616. sqlite3_free(pSession->azFilter);
  22617. nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
  22618. pSession->azFilter = sqlite3_malloc( nByte );
  22619. if( pSession->azFilter==0 ){
  22620. raw_printf(stderr, "Error: out or memory\n");
  22621. exit(1);
  22622. }
  22623. for(ii=1; ii<nCmd; ii++){
  22624. char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
  22625. shell_check_oom(x);
  22626. }
  22627. pSession->nFilter = ii-1;
  22628. }
  22629. }else
  22630. /* .session indirect ?BOOLEAN?
  22631. ** Query or set the indirect flag
  22632. */
  22633. if( cli_strcmp(azCmd[0], "indirect")==0 ){
  22634. int ii;
  22635. if( nCmd>2 ) goto session_syntax_error;
  22636. ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  22637. if( pAuxDb->nSession ){
  22638. ii = sqlite3session_indirect(pSession->p, ii);
  22639. utf8_printf(p->out, "session %s indirect flag = %d\n",
  22640. pSession->zName, ii);
  22641. }
  22642. }else
  22643. /* .session isempty
  22644. ** Determine if the session is empty
  22645. */
  22646. if( cli_strcmp(azCmd[0], "isempty")==0 ){
  22647. int ii;
  22648. if( nCmd!=1 ) goto session_syntax_error;
  22649. if( pAuxDb->nSession ){
  22650. ii = sqlite3session_isempty(pSession->p);
  22651. utf8_printf(p->out, "session %s isempty flag = %d\n",
  22652. pSession->zName, ii);
  22653. }
  22654. }else
  22655. /* .session list
  22656. ** List all currently open sessions
  22657. */
  22658. if( cli_strcmp(azCmd[0],"list")==0 ){
  22659. for(i=0; i<pAuxDb->nSession; i++){
  22660. utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
  22661. }
  22662. }else
  22663. /* .session open DB NAME
  22664. ** Open a new session called NAME on the attached database DB.
  22665. ** DB is normally "main".
  22666. */
  22667. if( cli_strcmp(azCmd[0],"open")==0 ){
  22668. char *zName;
  22669. if( nCmd!=3 ) goto session_syntax_error;
  22670. zName = azCmd[2];
  22671. if( zName[0]==0 ) goto session_syntax_error;
  22672. for(i=0; i<pAuxDb->nSession; i++){
  22673. if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
  22674. utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
  22675. goto meta_command_exit;
  22676. }
  22677. }
  22678. if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
  22679. raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
  22680. goto meta_command_exit;
  22681. }
  22682. pSession = &pAuxDb->aSession[pAuxDb->nSession];
  22683. rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
  22684. if( rc ){
  22685. raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
  22686. rc = 0;
  22687. goto meta_command_exit;
  22688. }
  22689. pSession->nFilter = 0;
  22690. sqlite3session_table_filter(pSession->p, session_filter, pSession);
  22691. pAuxDb->nSession++;
  22692. pSession->zName = sqlite3_mprintf("%s", zName);
  22693. shell_check_oom(pSession->zName);
  22694. }else
  22695. /* If no command name matches, show a syntax error */
  22696. session_syntax_error:
  22697. showHelp(p->out, "session");
  22698. }else
  22699. #endif
  22700. #ifdef SQLITE_DEBUG
  22701. /* Undocumented commands for internal testing. Subject to change
  22702. ** without notice. */
  22703. if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
  22704. if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
  22705. int i, v;
  22706. for(i=1; i<nArg; i++){
  22707. v = booleanValue(azArg[i]);
  22708. utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
  22709. }
  22710. }
  22711. if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
  22712. int i; sqlite3_int64 v;
  22713. for(i=1; i<nArg; i++){
  22714. char zBuf[200];
  22715. v = integerValue(azArg[i]);
  22716. sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
  22717. utf8_printf(p->out, "%s", zBuf);
  22718. }
  22719. }
  22720. }else
  22721. #endif
  22722. if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
  22723. int bIsInit = 0; /* True to initialize the SELFTEST table */
  22724. int bVerbose = 0; /* Verbose output */
  22725. int bSelftestExists; /* True if SELFTEST already exists */
  22726. int i, k; /* Loop counters */
  22727. int nTest = 0; /* Number of tests runs */
  22728. int nErr = 0; /* Number of errors seen */
  22729. ShellText str; /* Answer for a query */
  22730. sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
  22731. open_db(p,0);
  22732. for(i=1; i<nArg; i++){
  22733. const char *z = azArg[i];
  22734. if( z[0]=='-' && z[1]=='-' ) z++;
  22735. if( cli_strcmp(z,"-init")==0 ){
  22736. bIsInit = 1;
  22737. }else
  22738. if( cli_strcmp(z,"-v")==0 ){
  22739. bVerbose++;
  22740. }else
  22741. {
  22742. utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
  22743. azArg[i], azArg[0]);
  22744. raw_printf(stderr, "Should be one of: --init -v\n");
  22745. rc = 1;
  22746. goto meta_command_exit;
  22747. }
  22748. }
  22749. if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
  22750. != SQLITE_OK ){
  22751. bSelftestExists = 0;
  22752. }else{
  22753. bSelftestExists = 1;
  22754. }
  22755. if( bIsInit ){
  22756. createSelftestTable(p);
  22757. bSelftestExists = 1;
  22758. }
  22759. initText(&str);
  22760. appendText(&str, "x", 0);
  22761. for(k=bSelftestExists; k>=0; k--){
  22762. if( k==1 ){
  22763. rc = sqlite3_prepare_v2(p->db,
  22764. "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
  22765. -1, &pStmt, 0);
  22766. }else{
  22767. rc = sqlite3_prepare_v2(p->db,
  22768. "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
  22769. " (1,'run','PRAGMA integrity_check','ok')",
  22770. -1, &pStmt, 0);
  22771. }
  22772. if( rc ){
  22773. raw_printf(stderr, "Error querying the selftest table\n");
  22774. rc = 1;
  22775. sqlite3_finalize(pStmt);
  22776. goto meta_command_exit;
  22777. }
  22778. for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
  22779. int tno = sqlite3_column_int(pStmt, 0);
  22780. const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
  22781. const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
  22782. const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
  22783. if( zOp==0 ) continue;
  22784. if( zSql==0 ) continue;
  22785. if( zAns==0 ) continue;
  22786. k = 0;
  22787. if( bVerbose>0 ){
  22788. printf("%d: %s %s\n", tno, zOp, zSql);
  22789. }
  22790. if( cli_strcmp(zOp,"memo")==0 ){
  22791. utf8_printf(p->out, "%s\n", zSql);
  22792. }else
  22793. if( cli_strcmp(zOp,"run")==0 ){
  22794. char *zErrMsg = 0;
  22795. str.n = 0;
  22796. str.z[0] = 0;
  22797. rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
  22798. nTest++;
  22799. if( bVerbose ){
  22800. utf8_printf(p->out, "Result: %s\n", str.z);
  22801. }
  22802. if( rc || zErrMsg ){
  22803. nErr++;
  22804. rc = 1;
  22805. utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
  22806. sqlite3_free(zErrMsg);
  22807. }else if( cli_strcmp(zAns,str.z)!=0 ){
  22808. nErr++;
  22809. rc = 1;
  22810. utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
  22811. utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
  22812. }
  22813. }else
  22814. {
  22815. utf8_printf(stderr,
  22816. "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
  22817. rc = 1;
  22818. break;
  22819. }
  22820. } /* End loop over rows of content from SELFTEST */
  22821. sqlite3_finalize(pStmt);
  22822. } /* End loop over k */
  22823. freeText(&str);
  22824. utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
  22825. }else
  22826. if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
  22827. if( nArg<2 || nArg>3 ){
  22828. raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
  22829. rc = 1;
  22830. }
  22831. if( nArg>=2 ){
  22832. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
  22833. "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
  22834. }
  22835. if( nArg>=3 ){
  22836. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
  22837. "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
  22838. }
  22839. }else
  22840. if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
  22841. const char *zLike = 0; /* Which table to checksum. 0 means everything */
  22842. int i; /* Loop counter */
  22843. int bSchema = 0; /* Also hash the schema */
  22844. int bSeparate = 0; /* Hash each table separately */
  22845. int iSize = 224; /* Hash algorithm to use */
  22846. int bDebug = 0; /* Only show the query that would have run */
  22847. sqlite3_stmt *pStmt; /* For querying tables names */
  22848. char *zSql; /* SQL to be run */
  22849. char *zSep; /* Separator */
  22850. ShellText sSql; /* Complete SQL for the query to run the hash */
  22851. ShellText sQuery; /* Set of queries used to read all content */
  22852. open_db(p, 0);
  22853. for(i=1; i<nArg; i++){
  22854. const char *z = azArg[i];
  22855. if( z[0]=='-' ){
  22856. z++;
  22857. if( z[0]=='-' ) z++;
  22858. if( cli_strcmp(z,"schema")==0 ){
  22859. bSchema = 1;
  22860. }else
  22861. if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
  22862. || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
  22863. ){
  22864. iSize = atoi(&z[5]);
  22865. }else
  22866. if( cli_strcmp(z,"debug")==0 ){
  22867. bDebug = 1;
  22868. }else
  22869. {
  22870. utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
  22871. azArg[i], azArg[0]);
  22872. showHelp(p->out, azArg[0]);
  22873. rc = 1;
  22874. goto meta_command_exit;
  22875. }
  22876. }else if( zLike ){
  22877. raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
  22878. rc = 1;
  22879. goto meta_command_exit;
  22880. }else{
  22881. zLike = z;
  22882. bSeparate = 1;
  22883. if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
  22884. }
  22885. }
  22886. if( bSchema ){
  22887. zSql = "SELECT lower(name) FROM sqlite_schema"
  22888. " WHERE type='table' AND coalesce(rootpage,0)>1"
  22889. " UNION ALL SELECT 'sqlite_schema'"
  22890. " ORDER BY 1 collate nocase";
  22891. }else{
  22892. zSql = "SELECT lower(name) FROM sqlite_schema"
  22893. " WHERE type='table' AND coalesce(rootpage,0)>1"
  22894. " AND name NOT LIKE 'sqlite_%'"
  22895. " ORDER BY 1 collate nocase";
  22896. }
  22897. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  22898. initText(&sQuery);
  22899. initText(&sSql);
  22900. appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
  22901. zSep = "VALUES(";
  22902. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  22903. const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
  22904. if( zTab==0 ) continue;
  22905. if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
  22906. if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
  22907. appendText(&sQuery,"SELECT * FROM ", 0);
  22908. appendText(&sQuery,zTab,'"');
  22909. appendText(&sQuery," NOT INDEXED;", 0);
  22910. }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
  22911. appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
  22912. " ORDER BY name;", 0);
  22913. }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
  22914. appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
  22915. " ORDER BY name;", 0);
  22916. }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
  22917. appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
  22918. " ORDER BY tbl,idx;", 0);
  22919. }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
  22920. appendText(&sQuery, "SELECT * FROM ", 0);
  22921. appendText(&sQuery, zTab, 0);
  22922. appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
  22923. }
  22924. appendText(&sSql, zSep, 0);
  22925. appendText(&sSql, sQuery.z, '\'');
  22926. sQuery.n = 0;
  22927. appendText(&sSql, ",", 0);
  22928. appendText(&sSql, zTab, '\'');
  22929. zSep = "),(";
  22930. }
  22931. sqlite3_finalize(pStmt);
  22932. if( bSeparate ){
  22933. zSql = sqlite3_mprintf(
  22934. "%s))"
  22935. " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
  22936. " FROM [sha3sum$query]",
  22937. sSql.z, iSize);
  22938. }else{
  22939. zSql = sqlite3_mprintf(
  22940. "%s))"
  22941. " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
  22942. " FROM [sha3sum$query]",
  22943. sSql.z, iSize);
  22944. }
  22945. shell_check_oom(zSql);
  22946. freeText(&sQuery);
  22947. freeText(&sSql);
  22948. if( bDebug ){
  22949. utf8_printf(p->out, "%s\n", zSql);
  22950. }else{
  22951. shell_exec(p, zSql, 0);
  22952. }
  22953. sqlite3_free(zSql);
  22954. }else
  22955. #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
  22956. if( c=='s'
  22957. && (cli_strncmp(azArg[0], "shell", n)==0
  22958. || cli_strncmp(azArg[0],"system",n)==0)
  22959. ){
  22960. char *zCmd;
  22961. int i, x;
  22962. failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
  22963. if( nArg<2 ){
  22964. raw_printf(stderr, "Usage: .system COMMAND\n");
  22965. rc = 1;
  22966. goto meta_command_exit;
  22967. }
  22968. zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
  22969. for(i=2; i<nArg && zCmd!=0; i++){
  22970. zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
  22971. zCmd, azArg[i]);
  22972. }
  22973. x = zCmd!=0 ? system(zCmd) : 1;
  22974. sqlite3_free(zCmd);
  22975. if( x ) raw_printf(stderr, "System command returns %d\n", x);
  22976. }else
  22977. #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
  22978. if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
  22979. static const char *azBool[] = { "off", "on", "trigger", "full"};
  22980. const char *zOut;
  22981. int i;
  22982. if( nArg!=1 ){
  22983. raw_printf(stderr, "Usage: .show\n");
  22984. rc = 1;
  22985. goto meta_command_exit;
  22986. }
  22987. utf8_printf(p->out, "%12.12s: %s\n","echo",
  22988. azBool[ShellHasFlag(p, SHFLG_Echo)]);
  22989. utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
  22990. utf8_printf(p->out, "%12.12s: %s\n","explain",
  22991. p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
  22992. utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
  22993. if( p->mode==MODE_Column
  22994. || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
  22995. ){
  22996. utf8_printf
  22997. (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
  22998. modeDescr[p->mode], p->cmOpts.iWrap,
  22999. p->cmOpts.bWordWrap ? "on" : "off",
  23000. p->cmOpts.bQuote ? "" : "no");
  23001. }else{
  23002. utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
  23003. }
  23004. utf8_printf(p->out, "%12.12s: ", "nullvalue");
  23005. output_c_string(p->out, p->nullValue);
  23006. raw_printf(p->out, "\n");
  23007. utf8_printf(p->out,"%12.12s: %s\n","output",
  23008. strlen30(p->outfile) ? p->outfile : "stdout");
  23009. utf8_printf(p->out,"%12.12s: ", "colseparator");
  23010. output_c_string(p->out, p->colSeparator);
  23011. raw_printf(p->out, "\n");
  23012. utf8_printf(p->out,"%12.12s: ", "rowseparator");
  23013. output_c_string(p->out, p->rowSeparator);
  23014. raw_printf(p->out, "\n");
  23015. switch( p->statsOn ){
  23016. case 0: zOut = "off"; break;
  23017. default: zOut = "on"; break;
  23018. case 2: zOut = "stmt"; break;
  23019. case 3: zOut = "vmstep"; break;
  23020. }
  23021. utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
  23022. utf8_printf(p->out, "%12.12s: ", "width");
  23023. for (i=0;i<p->nWidth;i++) {
  23024. raw_printf(p->out, "%d ", p->colWidth[i]);
  23025. }
  23026. raw_printf(p->out, "\n");
  23027. utf8_printf(p->out, "%12.12s: %s\n", "filename",
  23028. p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
  23029. }else
  23030. if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
  23031. if( nArg==2 ){
  23032. if( cli_strcmp(azArg[1],"stmt")==0 ){
  23033. p->statsOn = 2;
  23034. }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
  23035. p->statsOn = 3;
  23036. }else{
  23037. p->statsOn = (u8)booleanValue(azArg[1]);
  23038. }
  23039. }else if( nArg==1 ){
  23040. display_stats(p->db, p, 0);
  23041. }else{
  23042. raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
  23043. rc = 1;
  23044. }
  23045. }else
  23046. if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
  23047. || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
  23048. || cli_strncmp(azArg[0], "indexes", n)==0) )
  23049. ){
  23050. sqlite3_stmt *pStmt;
  23051. char **azResult;
  23052. int nRow, nAlloc;
  23053. int ii;
  23054. ShellText s;
  23055. initText(&s);
  23056. open_db(p, 0);
  23057. rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
  23058. if( rc ){
  23059. sqlite3_finalize(pStmt);
  23060. return shellDatabaseError(p->db);
  23061. }
  23062. if( nArg>2 && c=='i' ){
  23063. /* It is an historical accident that the .indexes command shows an error
  23064. ** when called with the wrong number of arguments whereas the .tables
  23065. ** command does not. */
  23066. raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
  23067. rc = 1;
  23068. sqlite3_finalize(pStmt);
  23069. goto meta_command_exit;
  23070. }
  23071. for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
  23072. const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
  23073. if( zDbName==0 ) continue;
  23074. if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
  23075. if( sqlite3_stricmp(zDbName, "main")==0 ){
  23076. appendText(&s, "SELECT name FROM ", 0);
  23077. }else{
  23078. appendText(&s, "SELECT ", 0);
  23079. appendText(&s, zDbName, '\'');
  23080. appendText(&s, "||'.'||name FROM ", 0);
  23081. }
  23082. appendText(&s, zDbName, '"');
  23083. appendText(&s, ".sqlite_schema ", 0);
  23084. if( c=='t' ){
  23085. appendText(&s," WHERE type IN ('table','view')"
  23086. " AND name NOT LIKE 'sqlite_%'"
  23087. " AND name LIKE ?1", 0);
  23088. }else{
  23089. appendText(&s," WHERE type='index'"
  23090. " AND tbl_name LIKE ?1", 0);
  23091. }
  23092. }
  23093. rc = sqlite3_finalize(pStmt);
  23094. if( rc==SQLITE_OK ){
  23095. appendText(&s, " ORDER BY 1", 0);
  23096. rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
  23097. }
  23098. freeText(&s);
  23099. if( rc ) return shellDatabaseError(p->db);
  23100. /* Run the SQL statement prepared by the above block. Store the results
  23101. ** as an array of nul-terminated strings in azResult[]. */
  23102. nRow = nAlloc = 0;
  23103. azResult = 0;
  23104. if( nArg>1 ){
  23105. sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
  23106. }else{
  23107. sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
  23108. }
  23109. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  23110. if( nRow>=nAlloc ){
  23111. char **azNew;
  23112. int n2 = nAlloc*2 + 10;
  23113. azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
  23114. shell_check_oom(azNew);
  23115. nAlloc = n2;
  23116. azResult = azNew;
  23117. }
  23118. azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  23119. shell_check_oom(azResult[nRow]);
  23120. nRow++;
  23121. }
  23122. if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
  23123. rc = shellDatabaseError(p->db);
  23124. }
  23125. /* Pretty-print the contents of array azResult[] to the output */
  23126. if( rc==0 && nRow>0 ){
  23127. int len, maxlen = 0;
  23128. int i, j;
  23129. int nPrintCol, nPrintRow;
  23130. for(i=0; i<nRow; i++){
  23131. len = strlen30(azResult[i]);
  23132. if( len>maxlen ) maxlen = len;
  23133. }
  23134. nPrintCol = 80/(maxlen+2);
  23135. if( nPrintCol<1 ) nPrintCol = 1;
  23136. nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  23137. for(i=0; i<nPrintRow; i++){
  23138. for(j=i; j<nRow; j+=nPrintRow){
  23139. char *zSp = j<nPrintRow ? "" : " ";
  23140. utf8_printf(p->out, "%s%-*s", zSp, maxlen,
  23141. azResult[j] ? azResult[j]:"");
  23142. }
  23143. raw_printf(p->out, "\n");
  23144. }
  23145. }
  23146. for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
  23147. sqlite3_free(azResult);
  23148. }else
  23149. #ifndef SQLITE_SHELL_FIDDLE
  23150. /* Begin redirecting output to the file "testcase-out.txt" */
  23151. if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
  23152. output_reset(p);
  23153. p->out = output_file_open("testcase-out.txt", 0);
  23154. if( p->out==0 ){
  23155. raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
  23156. }
  23157. if( nArg>=2 ){
  23158. sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
  23159. }else{
  23160. sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
  23161. }
  23162. }else
  23163. #endif /* !defined(SQLITE_SHELL_FIDDLE) */
  23164. #ifndef SQLITE_UNTESTABLE
  23165. if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
  23166. static const struct {
  23167. const char *zCtrlName; /* Name of a test-control option */
  23168. int ctrlCode; /* Integer code for that option */
  23169. int unSafe; /* Not valid for --safe mode */
  23170. const char *zUsage; /* Usage notes */
  23171. } aCtrl[] = {
  23172. { "always", SQLITE_TESTCTRL_ALWAYS, 1, "BOOLEAN" },
  23173. { "assert", SQLITE_TESTCTRL_ASSERT, 1, "BOOLEAN" },
  23174. /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/
  23175. /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/
  23176. { "byteorder", SQLITE_TESTCTRL_BYTEORDER, 0, "" },
  23177. { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" },
  23178. /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/
  23179. { "imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
  23180. { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" },
  23181. { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" },
  23182. { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" },
  23183. { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" },
  23184. #ifdef YYCOVERAGE
  23185. { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" },
  23186. #endif
  23187. { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET " },
  23188. { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE,0, "" },
  23189. { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, 0, "" },
  23190. { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, 0, "SEED ?db?" },
  23191. { "seek_count", SQLITE_TESTCTRL_SEEK_COUNT, 0, "" },
  23192. { "sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX" },
  23193. { "tune", SQLITE_TESTCTRL_TUNE, 1, "ID VALUE" },
  23194. };
  23195. int testctrl = -1;
  23196. int iCtrl = -1;
  23197. int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
  23198. int isOk = 0;
  23199. int i, n2;
  23200. const char *zCmd = 0;
  23201. open_db(p, 0);
  23202. zCmd = nArg>=2 ? azArg[1] : "help";
  23203. /* The argument can optionally begin with "-" or "--" */
  23204. if( zCmd[0]=='-' && zCmd[1] ){
  23205. zCmd++;
  23206. if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
  23207. }
  23208. /* --help lists all test-controls */
  23209. if( cli_strcmp(zCmd,"help")==0 ){
  23210. utf8_printf(p->out, "Available test-controls:\n");
  23211. for(i=0; i<ArraySize(aCtrl); i++){
  23212. utf8_printf(p->out, " .testctrl %s %s\n",
  23213. aCtrl[i].zCtrlName, aCtrl[i].zUsage);
  23214. }
  23215. rc = 1;
  23216. goto meta_command_exit;
  23217. }
  23218. /* convert testctrl text option to value. allow any unique prefix
  23219. ** of the option name, or a numerical value. */
  23220. n2 = strlen30(zCmd);
  23221. for(i=0; i<ArraySize(aCtrl); i++){
  23222. if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
  23223. if( testctrl<0 ){
  23224. testctrl = aCtrl[i].ctrlCode;
  23225. iCtrl = i;
  23226. }else{
  23227. utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
  23228. "Use \".testctrl --help\" for help\n", zCmd);
  23229. rc = 1;
  23230. goto meta_command_exit;
  23231. }
  23232. }
  23233. }
  23234. if( testctrl<0 ){
  23235. utf8_printf(stderr,"Error: unknown test-control: %s\n"
  23236. "Use \".testctrl --help\" for help\n", zCmd);
  23237. }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
  23238. utf8_printf(stderr,
  23239. "line %d: \".testctrl %s\" may not be used in safe mode\n",
  23240. p->lineno, aCtrl[iCtrl].zCtrlName);
  23241. exit(1);
  23242. }else{
  23243. switch(testctrl){
  23244. /* sqlite3_test_control(int, db, int) */
  23245. case SQLITE_TESTCTRL_OPTIMIZATIONS:
  23246. if( nArg==3 ){
  23247. unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
  23248. rc2 = sqlite3_test_control(testctrl, p->db, opt);
  23249. isOk = 3;
  23250. }
  23251. break;
  23252. /* sqlite3_test_control(int) */
  23253. case SQLITE_TESTCTRL_PRNG_SAVE:
  23254. case SQLITE_TESTCTRL_PRNG_RESTORE:
  23255. case SQLITE_TESTCTRL_BYTEORDER:
  23256. if( nArg==2 ){
  23257. rc2 = sqlite3_test_control(testctrl);
  23258. isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
  23259. }
  23260. break;
  23261. /* sqlite3_test_control(int, uint) */
  23262. case SQLITE_TESTCTRL_PENDING_BYTE:
  23263. if( nArg==3 ){
  23264. unsigned int opt = (unsigned int)integerValue(azArg[2]);
  23265. rc2 = sqlite3_test_control(testctrl, opt);
  23266. isOk = 3;
  23267. }
  23268. break;
  23269. /* sqlite3_test_control(int, int, sqlite3*) */
  23270. case SQLITE_TESTCTRL_PRNG_SEED:
  23271. if( nArg==3 || nArg==4 ){
  23272. int ii = (int)integerValue(azArg[2]);
  23273. sqlite3 *db;
  23274. if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
  23275. sqlite3_randomness(sizeof(ii),&ii);
  23276. printf("-- random seed: %d\n", ii);
  23277. }
  23278. if( nArg==3 ){
  23279. db = 0;
  23280. }else{
  23281. db = p->db;
  23282. /* Make sure the schema has been loaded */
  23283. sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
  23284. }
  23285. rc2 = sqlite3_test_control(testctrl, ii, db);
  23286. isOk = 3;
  23287. }
  23288. break;
  23289. /* sqlite3_test_control(int, int) */
  23290. case SQLITE_TESTCTRL_ASSERT:
  23291. case SQLITE_TESTCTRL_ALWAYS:
  23292. if( nArg==3 ){
  23293. int opt = booleanValue(azArg[2]);
  23294. rc2 = sqlite3_test_control(testctrl, opt);
  23295. isOk = 1;
  23296. }
  23297. break;
  23298. /* sqlite3_test_control(int, int) */
  23299. case SQLITE_TESTCTRL_LOCALTIME_FAULT:
  23300. case SQLITE_TESTCTRL_NEVER_CORRUPT:
  23301. if( nArg==3 ){
  23302. int opt = booleanValue(azArg[2]);
  23303. rc2 = sqlite3_test_control(testctrl, opt);
  23304. isOk = 3;
  23305. }
  23306. break;
  23307. /* sqlite3_test_control(sqlite3*) */
  23308. case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
  23309. rc2 = sqlite3_test_control(testctrl, p->db);
  23310. isOk = 3;
  23311. break;
  23312. case SQLITE_TESTCTRL_IMPOSTER:
  23313. if( nArg==5 ){
  23314. rc2 = sqlite3_test_control(testctrl, p->db,
  23315. azArg[2],
  23316. integerValue(azArg[3]),
  23317. integerValue(azArg[4]));
  23318. isOk = 3;
  23319. }
  23320. break;
  23321. case SQLITE_TESTCTRL_SEEK_COUNT: {
  23322. u64 x = 0;
  23323. rc2 = sqlite3_test_control(testctrl, p->db, &x);
  23324. utf8_printf(p->out, "%llu\n", x);
  23325. isOk = 3;
  23326. break;
  23327. }
  23328. #ifdef YYCOVERAGE
  23329. case SQLITE_TESTCTRL_PARSER_COVERAGE: {
  23330. if( nArg==2 ){
  23331. sqlite3_test_control(testctrl, p->out);
  23332. isOk = 3;
  23333. }
  23334. break;
  23335. }
  23336. #endif
  23337. #ifdef SQLITE_DEBUG
  23338. case SQLITE_TESTCTRL_TUNE: {
  23339. if( nArg==4 ){
  23340. int id = (int)integerValue(azArg[2]);
  23341. int val = (int)integerValue(azArg[3]);
  23342. sqlite3_test_control(testctrl, id, &val);
  23343. isOk = 3;
  23344. }else if( nArg==3 ){
  23345. int id = (int)integerValue(azArg[2]);
  23346. sqlite3_test_control(testctrl, -id, &rc2);
  23347. isOk = 1;
  23348. }else if( nArg==2 ){
  23349. int id = 1;
  23350. while(1){
  23351. int val = 0;
  23352. rc2 = sqlite3_test_control(testctrl, -id, &val);
  23353. if( rc2!=SQLITE_OK ) break;
  23354. if( id>1 ) utf8_printf(p->out, " ");
  23355. utf8_printf(p->out, "%d: %d", id, val);
  23356. id++;
  23357. }
  23358. if( id>1 ) utf8_printf(p->out, "\n");
  23359. isOk = 3;
  23360. }
  23361. break;
  23362. }
  23363. #endif
  23364. case SQLITE_TESTCTRL_SORTER_MMAP:
  23365. if( nArg==3 ){
  23366. int opt = (unsigned int)integerValue(azArg[2]);
  23367. rc2 = sqlite3_test_control(testctrl, p->db, opt);
  23368. isOk = 3;
  23369. }
  23370. break;
  23371. }
  23372. }
  23373. if( isOk==0 && iCtrl>=0 ){
  23374. utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
  23375. rc = 1;
  23376. }else if( isOk==1 ){
  23377. raw_printf(p->out, "%d\n", rc2);
  23378. }else if( isOk==2 ){
  23379. raw_printf(p->out, "0x%08x\n", rc2);
  23380. }
  23381. }else
  23382. #endif /* !defined(SQLITE_UNTESTABLE) */
  23383. if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
  23384. open_db(p, 0);
  23385. sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
  23386. }else
  23387. if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
  23388. if( nArg==2 ){
  23389. enableTimer = booleanValue(azArg[1]);
  23390. if( enableTimer && !HAS_TIMER ){
  23391. raw_printf(stderr, "Error: timer not available on this system.\n");
  23392. enableTimer = 0;
  23393. }
  23394. }else{
  23395. raw_printf(stderr, "Usage: .timer on|off\n");
  23396. rc = 1;
  23397. }
  23398. }else
  23399. #ifndef SQLITE_OMIT_TRACE
  23400. if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
  23401. int mType = 0;
  23402. int jj;
  23403. open_db(p, 0);
  23404. for(jj=1; jj<nArg; jj++){
  23405. const char *z = azArg[jj];
  23406. if( z[0]=='-' ){
  23407. if( optionMatch(z, "expanded") ){
  23408. p->eTraceType = SHELL_TRACE_EXPANDED;
  23409. }
  23410. #ifdef SQLITE_ENABLE_NORMALIZE
  23411. else if( optionMatch(z, "normalized") ){
  23412. p->eTraceType = SHELL_TRACE_NORMALIZED;
  23413. }
  23414. #endif
  23415. else if( optionMatch(z, "plain") ){
  23416. p->eTraceType = SHELL_TRACE_PLAIN;
  23417. }
  23418. else if( optionMatch(z, "profile") ){
  23419. mType |= SQLITE_TRACE_PROFILE;
  23420. }
  23421. else if( optionMatch(z, "row") ){
  23422. mType |= SQLITE_TRACE_ROW;
  23423. }
  23424. else if( optionMatch(z, "stmt") ){
  23425. mType |= SQLITE_TRACE_STMT;
  23426. }
  23427. else if( optionMatch(z, "close") ){
  23428. mType |= SQLITE_TRACE_CLOSE;
  23429. }
  23430. else {
  23431. raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
  23432. rc = 1;
  23433. goto meta_command_exit;
  23434. }
  23435. }else{
  23436. output_file_close(p->traceOut);
  23437. p->traceOut = output_file_open(azArg[1], 0);
  23438. }
  23439. }
  23440. if( p->traceOut==0 ){
  23441. sqlite3_trace_v2(p->db, 0, 0, 0);
  23442. }else{
  23443. if( mType==0 ) mType = SQLITE_TRACE_STMT;
  23444. sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
  23445. }
  23446. }else
  23447. #endif /* !defined(SQLITE_OMIT_TRACE) */
  23448. #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
  23449. if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
  23450. int ii;
  23451. int lenOpt;
  23452. char *zOpt;
  23453. if( nArg<2 ){
  23454. raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
  23455. rc = 1;
  23456. goto meta_command_exit;
  23457. }
  23458. open_db(p, 0);
  23459. zOpt = azArg[1];
  23460. if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
  23461. lenOpt = (int)strlen(zOpt);
  23462. if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
  23463. assert( azArg[nArg]==0 );
  23464. sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
  23465. }else{
  23466. for(ii=1; ii<nArg; ii++){
  23467. sqlite3_create_module(p->db, azArg[ii], 0, 0);
  23468. }
  23469. }
  23470. }else
  23471. #endif
  23472. #if SQLITE_USER_AUTHENTICATION
  23473. if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
  23474. if( nArg<2 ){
  23475. raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
  23476. rc = 1;
  23477. goto meta_command_exit;
  23478. }
  23479. open_db(p, 0);
  23480. if( cli_strcmp(azArg[1],"login")==0 ){
  23481. if( nArg!=4 ){
  23482. raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
  23483. rc = 1;
  23484. goto meta_command_exit;
  23485. }
  23486. rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
  23487. strlen30(azArg[3]));
  23488. if( rc ){
  23489. utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
  23490. rc = 1;
  23491. }
  23492. }else if( cli_strcmp(azArg[1],"add")==0 ){
  23493. if( nArg!=5 ){
  23494. raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
  23495. rc = 1;
  23496. goto meta_command_exit;
  23497. }
  23498. rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
  23499. booleanValue(azArg[4]));
  23500. if( rc ){
  23501. raw_printf(stderr, "User-Add failed: %d\n", rc);
  23502. rc = 1;
  23503. }
  23504. }else if( cli_strcmp(azArg[1],"edit")==0 ){
  23505. if( nArg!=5 ){
  23506. raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
  23507. rc = 1;
  23508. goto meta_command_exit;
  23509. }
  23510. rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
  23511. booleanValue(azArg[4]));
  23512. if( rc ){
  23513. raw_printf(stderr, "User-Edit failed: %d\n", rc);
  23514. rc = 1;
  23515. }
  23516. }else if( cli_strcmp(azArg[1],"delete")==0 ){
  23517. if( nArg!=3 ){
  23518. raw_printf(stderr, "Usage: .user delete USER\n");
  23519. rc = 1;
  23520. goto meta_command_exit;
  23521. }
  23522. rc = sqlite3_user_delete(p->db, azArg[2]);
  23523. if( rc ){
  23524. raw_printf(stderr, "User-Delete failed: %d\n", rc);
  23525. rc = 1;
  23526. }
  23527. }else{
  23528. raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
  23529. rc = 1;
  23530. goto meta_command_exit;
  23531. }
  23532. }else
  23533. #endif /* SQLITE_USER_AUTHENTICATION */
  23534. if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
  23535. utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
  23536. sqlite3_libversion(), sqlite3_sourceid());
  23537. #if SQLITE_HAVE_ZLIB
  23538. utf8_printf(p->out, "zlib version %s\n", zlibVersion());
  23539. #endif
  23540. #define CTIMEOPT_VAL_(opt) #opt
  23541. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  23542. #if defined(__clang__) && defined(__clang_major__)
  23543. utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
  23544. CTIMEOPT_VAL(__clang_minor__) "."
  23545. CTIMEOPT_VAL(__clang_patchlevel__) "\n");
  23546. #elif defined(_MSC_VER)
  23547. utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
  23548. #elif defined(__GNUC__) && defined(__VERSION__)
  23549. utf8_printf(p->out, "gcc-" __VERSION__ "\n");
  23550. #endif
  23551. }else
  23552. if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
  23553. const char *zDbName = nArg==2 ? azArg[1] : "main";
  23554. sqlite3_vfs *pVfs = 0;
  23555. if( p->db ){
  23556. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
  23557. if( pVfs ){
  23558. utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
  23559. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  23560. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  23561. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  23562. }
  23563. }
  23564. }else
  23565. if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
  23566. sqlite3_vfs *pVfs;
  23567. sqlite3_vfs *pCurrent = 0;
  23568. if( p->db ){
  23569. sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
  23570. }
  23571. for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
  23572. utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
  23573. pVfs==pCurrent ? " <--- CURRENT" : "");
  23574. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  23575. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  23576. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  23577. if( pVfs->pNext ){
  23578. raw_printf(p->out, "-----------------------------------\n");
  23579. }
  23580. }
  23581. }else
  23582. if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
  23583. const char *zDbName = nArg==2 ? azArg[1] : "main";
  23584. char *zVfsName = 0;
  23585. if( p->db ){
  23586. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
  23587. if( zVfsName ){
  23588. utf8_printf(p->out, "%s\n", zVfsName);
  23589. sqlite3_free(zVfsName);
  23590. }
  23591. }
  23592. }else
  23593. if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
  23594. unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
  23595. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
  23596. }else
  23597. if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
  23598. int j;
  23599. assert( nArg<=ArraySize(azArg) );
  23600. p->nWidth = nArg-1;
  23601. p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
  23602. if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
  23603. if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
  23604. for(j=1; j<nArg; j++){
  23605. p->colWidth[j-1] = (int)integerValue(azArg[j]);
  23606. }
  23607. }else
  23608. {
  23609. utf8_printf(stderr, "Error: unknown command or invalid arguments: "
  23610. " \"%s\". Enter \".help\" for help\n", azArg[0]);
  23611. rc = 1;
  23612. }
  23613. meta_command_exit:
  23614. if( p->outCount ){
  23615. p->outCount--;
  23616. if( p->outCount==0 ) output_reset(p);
  23617. }
  23618. p->bSafeMode = p->bSafeModePersist;
  23619. return rc;
  23620. }
  23621. /* Line scan result and intermediate states (supporting scan resumption)
  23622. */
  23623. #ifndef CHAR_BIT
  23624. # define CHAR_BIT 8
  23625. #endif
  23626. typedef enum {
  23627. QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
  23628. QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
  23629. QSS_Start = 0
  23630. } QuickScanState;
  23631. #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
  23632. #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
  23633. #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
  23634. #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
  23635. #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
  23636. /*
  23637. ** Scan line for classification to guide shell's handling.
  23638. ** The scan is resumable for subsequent lines when prior
  23639. ** return values are passed as the 2nd argument.
  23640. */
  23641. static QuickScanState quickscan(char *zLine, QuickScanState qss){
  23642. char cin;
  23643. char cWait = (char)qss; /* intentional narrowing loss */
  23644. if( cWait==0 ){
  23645. PlainScan:
  23646. assert( cWait==0 );
  23647. while( (cin = *zLine++)!=0 ){
  23648. if( IsSpace(cin) )
  23649. continue;
  23650. switch (cin){
  23651. case '-':
  23652. if( *zLine!='-' )
  23653. break;
  23654. while((cin = *++zLine)!=0 )
  23655. if( cin=='\n')
  23656. goto PlainScan;
  23657. return qss;
  23658. case ';':
  23659. qss |= QSS_EndingSemi;
  23660. continue;
  23661. case '/':
  23662. if( *zLine=='*' ){
  23663. ++zLine;
  23664. cWait = '*';
  23665. qss = QSS_SETV(qss, cWait);
  23666. goto TermScan;
  23667. }
  23668. break;
  23669. case '[':
  23670. cin = ']';
  23671. /* fall thru */
  23672. case '`': case '\'': case '"':
  23673. cWait = cin;
  23674. qss = QSS_HasDark | cWait;
  23675. goto TermScan;
  23676. default:
  23677. break;
  23678. }
  23679. qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
  23680. }
  23681. }else{
  23682. TermScan:
  23683. while( (cin = *zLine++)!=0 ){
  23684. if( cin==cWait ){
  23685. switch( cWait ){
  23686. case '*':
  23687. if( *zLine != '/' )
  23688. continue;
  23689. ++zLine;
  23690. cWait = 0;
  23691. qss = QSS_SETV(qss, 0);
  23692. goto PlainScan;
  23693. case '`': case '\'': case '"':
  23694. if(*zLine==cWait){
  23695. ++zLine;
  23696. continue;
  23697. }
  23698. /* fall thru */
  23699. case ']':
  23700. cWait = 0;
  23701. qss = QSS_SETV(qss, 0);
  23702. goto PlainScan;
  23703. default: assert(0);
  23704. }
  23705. }
  23706. }
  23707. }
  23708. return qss;
  23709. }
  23710. /*
  23711. ** Return TRUE if the line typed in is an SQL command terminator other
  23712. ** than a semi-colon. The SQL Server style "go" command is understood
  23713. ** as is the Oracle "/".
  23714. */
  23715. static int line_is_command_terminator(char *zLine){
  23716. while( IsSpace(zLine[0]) ){ zLine++; };
  23717. if( zLine[0]=='/' )
  23718. zLine += 1; /* Oracle */
  23719. else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
  23720. zLine += 2; /* SQL Server */
  23721. else
  23722. return 0;
  23723. return quickscan(zLine, QSS_Start)==QSS_Start;
  23724. }
  23725. /*
  23726. ** We need a default sqlite3_complete() implementation to use in case
  23727. ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
  23728. ** any arbitrary text is a complete SQL statement. This is not very
  23729. ** user-friendly, but it does seem to work.
  23730. */
  23731. #ifdef SQLITE_OMIT_COMPLETE
  23732. #define sqlite3_complete(x) 1
  23733. #endif
  23734. /*
  23735. ** Return true if zSql is a complete SQL statement. Return false if it
  23736. ** ends in the middle of a string literal or C-style comment.
  23737. */
  23738. static int line_is_complete(char *zSql, int nSql){
  23739. int rc;
  23740. if( zSql==0 ) return 1;
  23741. zSql[nSql] = ';';
  23742. zSql[nSql+1] = 0;
  23743. rc = sqlite3_complete(zSql);
  23744. zSql[nSql] = 0;
  23745. return rc;
  23746. }
  23747. /*
  23748. ** Run a single line of SQL. Return the number of errors.
  23749. */
  23750. static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
  23751. int rc;
  23752. char *zErrMsg = 0;
  23753. open_db(p, 0);
  23754. if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
  23755. if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
  23756. BEGIN_TIMER;
  23757. rc = shell_exec(p, zSql, &zErrMsg);
  23758. END_TIMER;
  23759. if( rc || zErrMsg ){
  23760. char zPrefix[100];
  23761. const char *zErrorTail;
  23762. const char *zErrorType;
  23763. if( zErrMsg==0 ){
  23764. zErrorType = "Error";
  23765. zErrorTail = sqlite3_errmsg(p->db);
  23766. }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
  23767. zErrorType = "Parse error";
  23768. zErrorTail = &zErrMsg[12];
  23769. }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
  23770. zErrorType = "Runtime error";
  23771. zErrorTail = &zErrMsg[10];
  23772. }else{
  23773. zErrorType = "Error";
  23774. zErrorTail = zErrMsg;
  23775. }
  23776. if( in!=0 || !stdin_is_interactive ){
  23777. sqlite3_snprintf(sizeof(zPrefix), zPrefix,
  23778. "%s near line %d:", zErrorType, startline);
  23779. }else{
  23780. sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
  23781. }
  23782. utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
  23783. sqlite3_free(zErrMsg);
  23784. zErrMsg = 0;
  23785. return 1;
  23786. }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
  23787. char zLineBuf[2000];
  23788. sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
  23789. "changes: %lld total_changes: %lld",
  23790. sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
  23791. raw_printf(p->out, "%s\n", zLineBuf);
  23792. }
  23793. return 0;
  23794. }
  23795. static void echo_group_input(ShellState *p, const char *zDo){
  23796. if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
  23797. }
  23798. #ifdef SQLITE_SHELL_FIDDLE
  23799. /*
  23800. ** Alternate one_input_line() impl for wasm mode. This is not in the primary impl
  23801. ** because we need the global shellState and cannot access it from that function
  23802. ** without moving lots of code around (creating a larger/messier diff).
  23803. */
  23804. static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
  23805. /* Parse the next line from shellState.wasm.zInput. */
  23806. const char *zBegin = shellState.wasm.zPos;
  23807. const char *z = zBegin;
  23808. char *zLine = 0;
  23809. i64 nZ = 0;
  23810. UNUSED_PARAMETER(in);
  23811. UNUSED_PARAMETER(isContinuation);
  23812. if(!z || !*z){
  23813. return 0;
  23814. }
  23815. while(*z && isspace(*z)) ++z;
  23816. zBegin = z;
  23817. for(; *z && '\n'!=*z; ++nZ, ++z){}
  23818. if(nZ>0 && '\r'==zBegin[nZ-1]){
  23819. --nZ;
  23820. }
  23821. shellState.wasm.zPos = z;
  23822. zLine = realloc(zPrior, nZ+1);
  23823. shell_check_oom(zLine);
  23824. memcpy(zLine, zBegin, nZ);
  23825. zLine[nZ] = 0;
  23826. return zLine;
  23827. }
  23828. #endif /* SQLITE_SHELL_FIDDLE */
  23829. /*
  23830. ** Read input from *in and process it. If *in==0 then input
  23831. ** is interactive - the user is typing it it. Otherwise, input
  23832. ** is coming from a file or device. A prompt is issued and history
  23833. ** is saved only if input is interactive. An interrupt signal will
  23834. ** cause this routine to exit immediately, unless input is interactive.
  23835. **
  23836. ** Return the number of errors.
  23837. */
  23838. static int process_input(ShellState *p){
  23839. char *zLine = 0; /* A single input line */
  23840. char *zSql = 0; /* Accumulated SQL text */
  23841. i64 nLine; /* Length of current line */
  23842. i64 nSql = 0; /* Bytes of zSql[] used */
  23843. i64 nAlloc = 0; /* Allocated zSql[] space */
  23844. int rc; /* Error code */
  23845. int errCnt = 0; /* Number of errors seen */
  23846. i64 startline = 0; /* Line number for start of current input */
  23847. QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
  23848. if( p->inputNesting==MAX_INPUT_NESTING ){
  23849. /* This will be more informative in a later version. */
  23850. utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
  23851. " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
  23852. return 1;
  23853. }
  23854. ++p->inputNesting;
  23855. p->lineno = 0;
  23856. while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
  23857. fflush(p->out);
  23858. zLine = one_input_line(p->in, zLine, nSql>0);
  23859. if( zLine==0 ){
  23860. /* End of input */
  23861. if( p->in==0 && stdin_is_interactive ) printf("\n");
  23862. break;
  23863. }
  23864. if( seenInterrupt ){
  23865. if( p->in!=0 ) break;
  23866. seenInterrupt = 0;
  23867. }
  23868. p->lineno++;
  23869. if( QSS_INPLAIN(qss)
  23870. && line_is_command_terminator(zLine)
  23871. && line_is_complete(zSql, nSql) ){
  23872. memcpy(zLine,";",2);
  23873. }
  23874. qss = quickscan(zLine, qss);
  23875. if( QSS_PLAINWHITE(qss) && nSql==0 ){
  23876. /* Just swallow single-line whitespace */
  23877. echo_group_input(p, zLine);
  23878. qss = QSS_Start;
  23879. continue;
  23880. }
  23881. if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
  23882. echo_group_input(p, zLine);
  23883. if( zLine[0]=='.' ){
  23884. rc = do_meta_command(zLine, p);
  23885. if( rc==2 ){ /* exit requested */
  23886. break;
  23887. }else if( rc ){
  23888. errCnt++;
  23889. }
  23890. }
  23891. qss = QSS_Start;
  23892. continue;
  23893. }
  23894. /* No single-line dispositions remain; accumulate line(s). */
  23895. nLine = strlen(zLine);
  23896. if( nSql+nLine+2>=nAlloc ){
  23897. /* Grow buffer by half-again increments when big. */
  23898. nAlloc = nSql+(nSql>>1)+nLine+100;
  23899. zSql = realloc(zSql, nAlloc);
  23900. shell_check_oom(zSql);
  23901. }
  23902. if( nSql==0 ){
  23903. i64 i;
  23904. for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
  23905. assert( nAlloc>0 && zSql!=0 );
  23906. memcpy(zSql, zLine+i, nLine+1-i);
  23907. startline = p->lineno;
  23908. nSql = nLine-i;
  23909. }else{
  23910. zSql[nSql++] = '\n';
  23911. memcpy(zSql+nSql, zLine, nLine+1);
  23912. nSql += nLine;
  23913. }
  23914. if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
  23915. echo_group_input(p, zSql);
  23916. errCnt += runOneSqlLine(p, zSql, p->in, startline);
  23917. nSql = 0;
  23918. if( p->outCount ){
  23919. output_reset(p);
  23920. p->outCount = 0;
  23921. }else{
  23922. clearTempFile(p);
  23923. }
  23924. p->bSafeMode = p->bSafeModePersist;
  23925. qss = QSS_Start;
  23926. }else if( nSql && QSS_PLAINWHITE(qss) ){
  23927. echo_group_input(p, zSql);
  23928. nSql = 0;
  23929. qss = QSS_Start;
  23930. }
  23931. }
  23932. if( nSql ){
  23933. /* This may be incomplete. Let the SQL parser deal with that. */
  23934. echo_group_input(p, zSql);
  23935. errCnt += runOneSqlLine(p, zSql, p->in, startline);
  23936. }
  23937. free(zSql);
  23938. free(zLine);
  23939. --p->inputNesting;
  23940. return errCnt>0;
  23941. }
  23942. /*
  23943. ** Return a pathname which is the user's home directory. A
  23944. ** 0 return indicates an error of some kind.
  23945. */
  23946. static char *find_home_dir(int clearFlag){
  23947. static char *home_dir = NULL;
  23948. if( clearFlag ){
  23949. free(home_dir);
  23950. home_dir = 0;
  23951. return 0;
  23952. }
  23953. if( home_dir ) return home_dir;
  23954. #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
  23955. && !defined(__RTP__) && !defined(_WRS_KERNEL)
  23956. {
  23957. struct passwd *pwent;
  23958. uid_t uid = getuid();
  23959. if( (pwent=getpwuid(uid)) != NULL) {
  23960. home_dir = pwent->pw_dir;
  23961. }
  23962. }
  23963. #endif
  23964. #if defined(_WIN32_WCE)
  23965. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  23966. */
  23967. home_dir = "/";
  23968. #else
  23969. #if defined(_WIN32) || defined(WIN32)
  23970. if (!home_dir) {
  23971. home_dir = getenv("USERPROFILE");
  23972. }
  23973. #endif
  23974. if (!home_dir) {
  23975. home_dir = getenv("HOME");
  23976. }
  23977. #if defined(_WIN32) || defined(WIN32)
  23978. if (!home_dir) {
  23979. char *zDrive, *zPath;
  23980. int n;
  23981. zDrive = getenv("HOMEDRIVE");
  23982. zPath = getenv("HOMEPATH");
  23983. if( zDrive && zPath ){
  23984. n = strlen30(zDrive) + strlen30(zPath) + 1;
  23985. home_dir = malloc( n );
  23986. if( home_dir==0 ) return 0;
  23987. sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  23988. return home_dir;
  23989. }
  23990. home_dir = "c:\\";
  23991. }
  23992. #endif
  23993. #endif /* !_WIN32_WCE */
  23994. if( home_dir ){
  23995. i64 n = strlen(home_dir) + 1;
  23996. char *z = malloc( n );
  23997. if( z ) memcpy(z, home_dir, n);
  23998. home_dir = z;
  23999. }
  24000. return home_dir;
  24001. }
  24002. /*
  24003. ** Read input from the file given by sqliterc_override. Or if that
  24004. ** parameter is NULL, take input from ~/.sqliterc
  24005. **
  24006. ** Returns the number of errors.
  24007. */
  24008. static void process_sqliterc(
  24009. ShellState *p, /* Configuration data */
  24010. const char *sqliterc_override /* Name of config file. NULL to use default */
  24011. ){
  24012. char *home_dir = NULL;
  24013. const char *sqliterc = sqliterc_override;
  24014. char *zBuf = 0;
  24015. FILE *inSaved = p->in;
  24016. int savedLineno = p->lineno;
  24017. if (sqliterc == NULL) {
  24018. home_dir = find_home_dir(0);
  24019. if( home_dir==0 ){
  24020. raw_printf(stderr, "-- warning: cannot find home directory;"
  24021. " cannot read ~/.sqliterc\n");
  24022. return;
  24023. }
  24024. zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
  24025. shell_check_oom(zBuf);
  24026. sqliterc = zBuf;
  24027. }
  24028. p->in = fopen(sqliterc,"rb");
  24029. if( p->in ){
  24030. if( stdin_is_interactive ){
  24031. utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
  24032. }
  24033. if( process_input(p) && bail_on_error ) exit(1);
  24034. fclose(p->in);
  24035. }else if( sqliterc_override!=0 ){
  24036. utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
  24037. if( bail_on_error ) exit(1);
  24038. }
  24039. p->in = inSaved;
  24040. p->lineno = savedLineno;
  24041. sqlite3_free(zBuf);
  24042. }
  24043. /*
  24044. ** Show available command line options
  24045. */
  24046. static const char zOptions[] =
  24047. #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
  24048. " -A ARGS... run \".archive ARGS\" and exit\n"
  24049. #endif
  24050. " -append append the database to the end of the file\n"
  24051. " -ascii set output mode to 'ascii'\n"
  24052. " -bail stop after hitting an error\n"
  24053. " -batch force batch I/O\n"
  24054. " -box set output mode to 'box'\n"
  24055. " -column set output mode to 'column'\n"
  24056. " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
  24057. " -csv set output mode to 'csv'\n"
  24058. #if !defined(SQLITE_OMIT_DESERIALIZE)
  24059. " -deserialize open the database using sqlite3_deserialize()\n"
  24060. #endif
  24061. " -echo print inputs before execution\n"
  24062. " -init FILENAME read/process named file\n"
  24063. " -[no]header turn headers on or off\n"
  24064. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  24065. " -heap SIZE Size of heap for memsys3 or memsys5\n"
  24066. #endif
  24067. " -help show this message\n"
  24068. " -html set output mode to HTML\n"
  24069. " -interactive force interactive I/O\n"
  24070. " -json set output mode to 'json'\n"
  24071. " -line set output mode to 'line'\n"
  24072. " -list set output mode to 'list'\n"
  24073. " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
  24074. " -markdown set output mode to 'markdown'\n"
  24075. #if !defined(SQLITE_OMIT_DESERIALIZE)
  24076. " -maxsize N maximum size for a --deserialize database\n"
  24077. #endif
  24078. " -memtrace trace all memory allocations and deallocations\n"
  24079. " -mmap N default mmap size set to N\n"
  24080. #ifdef SQLITE_ENABLE_MULTIPLEX
  24081. " -multiplex enable the multiplexor VFS\n"
  24082. #endif
  24083. " -newline SEP set output row separator. Default: '\\n'\n"
  24084. " -nofollow refuse to open symbolic links to database files\n"
  24085. " -nonce STRING set the safe-mode escape nonce\n"
  24086. " -nullvalue TEXT set text string for NULL values. Default ''\n"
  24087. " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
  24088. " -quote set output mode to 'quote'\n"
  24089. " -readonly open the database read-only\n"
  24090. " -safe enable safe-mode\n"
  24091. " -separator SEP set output column separator. Default: '|'\n"
  24092. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  24093. " -sorterref SIZE sorter references threshold size\n"
  24094. #endif
  24095. " -stats print memory stats before each finalize\n"
  24096. " -table set output mode to 'table'\n"
  24097. " -tabs set output mode to 'tabs'\n"
  24098. " -version show SQLite version\n"
  24099. " -vfs NAME use NAME as the default VFS\n"
  24100. #ifdef SQLITE_ENABLE_VFSTRACE
  24101. " -vfstrace enable tracing of all VFS calls\n"
  24102. #endif
  24103. #ifdef SQLITE_HAVE_ZLIB
  24104. " -zip open the file as a ZIP Archive\n"
  24105. #endif
  24106. ;
  24107. static void usage(int showDetail){
  24108. utf8_printf(stderr,
  24109. "Usage: %s [OPTIONS] FILENAME [SQL]\n"
  24110. "FILENAME is the name of an SQLite database. A new database is created\n"
  24111. "if the file does not previously exist.\n", Argv0);
  24112. if( showDetail ){
  24113. utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
  24114. }else{
  24115. raw_printf(stderr, "Use the -help option for additional information\n");
  24116. }
  24117. exit(1);
  24118. }
  24119. /*
  24120. ** Internal check: Verify that the SQLite is uninitialized. Print a
  24121. ** error message if it is initialized.
  24122. */
  24123. static void verify_uninitialized(void){
  24124. if( sqlite3_config(-1)==SQLITE_MISUSE ){
  24125. utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
  24126. " initialization.\n");
  24127. }
  24128. }
  24129. /*
  24130. ** Initialize the state information in data
  24131. */
  24132. static void main_init(ShellState *data) {
  24133. memset(data, 0, sizeof(*data));
  24134. data->normalMode = data->cMode = data->mode = MODE_List;
  24135. data->autoExplain = 1;
  24136. data->pAuxDb = &data->aAuxDb[0];
  24137. memcpy(data->colSeparator,SEP_Column, 2);
  24138. memcpy(data->rowSeparator,SEP_Row, 2);
  24139. data->showHeader = 0;
  24140. data->shellFlgs = SHFLG_Lookaside;
  24141. verify_uninitialized();
  24142. sqlite3_config(SQLITE_CONFIG_URI, 1);
  24143. sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
  24144. sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
  24145. sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  24146. sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
  24147. }
  24148. /*
  24149. ** Output text to the console in a font that attracts extra attention.
  24150. */
  24151. #ifdef _WIN32
  24152. static void printBold(const char *zText){
  24153. #if !SQLITE_OS_WINRT
  24154. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  24155. CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
  24156. GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
  24157. SetConsoleTextAttribute(out,
  24158. FOREGROUND_RED|FOREGROUND_INTENSITY
  24159. );
  24160. #endif
  24161. printf("%s", zText);
  24162. #if !SQLITE_OS_WINRT
  24163. SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
  24164. #endif
  24165. }
  24166. #else
  24167. static void printBold(const char *zText){
  24168. printf("\033[1m%s\033[0m", zText);
  24169. }
  24170. #endif
  24171. /*
  24172. ** Get the argument to an --option. Throw an error and die if no argument
  24173. ** is available.
  24174. */
  24175. static char *cmdline_option_value(int argc, char **argv, int i){
  24176. if( i==argc ){
  24177. utf8_printf(stderr, "%s: Error: missing argument to %s\n",
  24178. argv[0], argv[argc-1]);
  24179. exit(1);
  24180. }
  24181. return argv[i];
  24182. }
  24183. #ifndef SQLITE_SHELL_IS_UTF8
  24184. # if (defined(_WIN32) || defined(WIN32)) \
  24185. && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
  24186. # define SQLITE_SHELL_IS_UTF8 (0)
  24187. # else
  24188. # define SQLITE_SHELL_IS_UTF8 (1)
  24189. # endif
  24190. #endif
  24191. #ifdef SQLITE_SHELL_FIDDLE
  24192. # define main fiddle_main
  24193. #endif
  24194. #if SQLITE_SHELL_IS_UTF8
  24195. int SQLITE_CDECL main(int argc, char **argv){
  24196. #else
  24197. int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
  24198. char **argv;
  24199. #endif
  24200. #ifdef SQLITE_DEBUG
  24201. sqlite3_int64 mem_main_enter = sqlite3_memory_used();
  24202. #endif
  24203. char *zErrMsg = 0;
  24204. #ifdef SQLITE_SHELL_FIDDLE
  24205. # define data shellState
  24206. #else
  24207. ShellState data;
  24208. #endif
  24209. const char *zInitFile = 0;
  24210. int i;
  24211. int rc = 0;
  24212. int warnInmemoryDb = 0;
  24213. int readStdin = 1;
  24214. int nCmd = 0;
  24215. char **azCmd = 0;
  24216. const char *zVfs = 0; /* Value of -vfs command-line option */
  24217. #if !SQLITE_SHELL_IS_UTF8
  24218. char **argvToFree = 0;
  24219. int argcToFree = 0;
  24220. #endif
  24221. setBinaryMode(stdin, 0);
  24222. setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
  24223. #ifdef SQLITE_SHELL_FIDDLE
  24224. stdin_is_interactive = 0;
  24225. stdout_is_console = 1;
  24226. data.wasm.zDefaultDbName = "/fiddle.sqlite3";
  24227. #else
  24228. stdin_is_interactive = isatty(0);
  24229. stdout_is_console = isatty(1);
  24230. #endif
  24231. #if !defined(_WIN32_WCE)
  24232. if( getenv("SQLITE_DEBUG_BREAK") ){
  24233. if( isatty(0) && isatty(2) ){
  24234. fprintf(stderr,
  24235. "attach debugger to process %d and press any key to continue.\n",
  24236. GETPID());
  24237. fgetc(stdin);
  24238. }else{
  24239. #if defined(_WIN32) || defined(WIN32)
  24240. #if SQLITE_OS_WINRT
  24241. __debugbreak();
  24242. #else
  24243. DebugBreak();
  24244. #endif
  24245. #elif defined(SIGTRAP)
  24246. raise(SIGTRAP);
  24247. #endif
  24248. }
  24249. }
  24250. #endif
  24251. #if USE_SYSTEM_SQLITE+0!=1
  24252. if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
  24253. utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
  24254. sqlite3_sourceid(), SQLITE_SOURCE_ID);
  24255. exit(1);
  24256. }
  24257. #endif
  24258. main_init(&data);
  24259. /* On Windows, we must translate command-line arguments into UTF-8.
  24260. ** The SQLite memory allocator subsystem has to be enabled in order to
  24261. ** do this. But we want to run an sqlite3_shutdown() afterwards so that
  24262. ** subsequent sqlite3_config() calls will work. So copy all results into
  24263. ** memory that does not come from the SQLite memory allocator.
  24264. */
  24265. #if !SQLITE_SHELL_IS_UTF8
  24266. sqlite3_initialize();
  24267. argvToFree = malloc(sizeof(argv[0])*argc*2);
  24268. shell_check_oom(argvToFree);
  24269. argcToFree = argc;
  24270. argv = argvToFree + argc;
  24271. for(i=0; i<argc; i++){
  24272. char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
  24273. i64 n;
  24274. shell_check_oom(z);
  24275. n = strlen(z);
  24276. argv[i] = malloc( n+1 );
  24277. shell_check_oom(argv[i]);
  24278. memcpy(argv[i], z, n+1);
  24279. argvToFree[i] = argv[i];
  24280. sqlite3_free(z);
  24281. }
  24282. sqlite3_shutdown();
  24283. #endif
  24284. assert( argc>=1 && argv && argv[0] );
  24285. Argv0 = argv[0];
  24286. /* Make sure we have a valid signal handler early, before anything
  24287. ** else is done.
  24288. */
  24289. #ifdef SIGINT
  24290. signal(SIGINT, interrupt_handler);
  24291. #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
  24292. SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
  24293. #endif
  24294. #ifdef SQLITE_SHELL_DBNAME_PROC
  24295. {
  24296. /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
  24297. ** of a C-function that will provide the name of the database file. Use
  24298. ** this compile-time option to embed this shell program in larger
  24299. ** applications. */
  24300. extern void SQLITE_SHELL_DBNAME_PROC(const char**);
  24301. SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
  24302. warnInmemoryDb = 0;
  24303. }
  24304. #endif
  24305. /* Do an initial pass through the command-line argument to locate
  24306. ** the name of the database file, the name of the initialization file,
  24307. ** the size of the alternative malloc heap,
  24308. ** and the first command to execute.
  24309. */
  24310. verify_uninitialized();
  24311. for(i=1; i<argc; i++){
  24312. char *z;
  24313. z = argv[i];
  24314. if( z[0]!='-' ){
  24315. if( data.aAuxDb->zDbFilename==0 ){
  24316. data.aAuxDb->zDbFilename = z;
  24317. }else{
  24318. /* Excesss arguments are interpreted as SQL (or dot-commands) and
  24319. ** mean that nothing is read from stdin */
  24320. readStdin = 0;
  24321. nCmd++;
  24322. azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
  24323. shell_check_oom(azCmd);
  24324. azCmd[nCmd-1] = z;
  24325. }
  24326. }
  24327. if( z[1]=='-' ) z++;
  24328. if( cli_strcmp(z,"-separator")==0
  24329. || cli_strcmp(z,"-nullvalue")==0
  24330. || cli_strcmp(z,"-newline")==0
  24331. || cli_strcmp(z,"-cmd")==0
  24332. ){
  24333. (void)cmdline_option_value(argc, argv, ++i);
  24334. }else if( cli_strcmp(z,"-init")==0 ){
  24335. zInitFile = cmdline_option_value(argc, argv, ++i);
  24336. }else if( cli_strcmp(z,"-batch")==0 ){
  24337. /* Need to check for batch mode here to so we can avoid printing
  24338. ** informational messages (like from process_sqliterc) before
  24339. ** we do the actual processing of arguments later in a second pass.
  24340. */
  24341. stdin_is_interactive = 0;
  24342. }else if( cli_strcmp(z,"-heap")==0 ){
  24343. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  24344. const char *zSize;
  24345. sqlite3_int64 szHeap;
  24346. zSize = cmdline_option_value(argc, argv, ++i);
  24347. szHeap = integerValue(zSize);
  24348. if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
  24349. sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
  24350. #else
  24351. (void)cmdline_option_value(argc, argv, ++i);
  24352. #endif
  24353. }else if( cli_strcmp(z,"-pagecache")==0 ){
  24354. sqlite3_int64 n, sz;
  24355. sz = integerValue(cmdline_option_value(argc,argv,++i));
  24356. if( sz>70000 ) sz = 70000;
  24357. if( sz<0 ) sz = 0;
  24358. n = integerValue(cmdline_option_value(argc,argv,++i));
  24359. if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
  24360. n = 0xffffffffffffLL/sz;
  24361. }
  24362. sqlite3_config(SQLITE_CONFIG_PAGECACHE,
  24363. (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
  24364. data.shellFlgs |= SHFLG_Pagecache;
  24365. }else if( cli_strcmp(z,"-lookaside")==0 ){
  24366. int n, sz;
  24367. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  24368. if( sz<0 ) sz = 0;
  24369. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  24370. if( n<0 ) n = 0;
  24371. sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
  24372. if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
  24373. }else if( cli_strcmp(z,"-threadsafe")==0 ){
  24374. int n;
  24375. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  24376. switch( n ){
  24377. case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); break;
  24378. case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD); break;
  24379. default: sqlite3_config(SQLITE_CONFIG_SERIALIZED); break;
  24380. }
  24381. #ifdef SQLITE_ENABLE_VFSTRACE
  24382. }else if( cli_strcmp(z,"-vfstrace")==0 ){
  24383. extern int vfstrace_register(
  24384. const char *zTraceName,
  24385. const char *zOldVfsName,
  24386. int (*xOut)(const char*,void*),
  24387. void *pOutArg,
  24388. int makeDefault
  24389. );
  24390. vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
  24391. #endif
  24392. #ifdef SQLITE_ENABLE_MULTIPLEX
  24393. }else if( cli_strcmp(z,"-multiplex")==0 ){
  24394. extern int sqlite3_multiple_initialize(const char*,int);
  24395. sqlite3_multiplex_initialize(0, 1);
  24396. #endif
  24397. }else if( cli_strcmp(z,"-mmap")==0 ){
  24398. sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  24399. sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
  24400. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  24401. }else if( cli_strcmp(z,"-sorterref")==0 ){
  24402. sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  24403. sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
  24404. #endif
  24405. }else if( cli_strcmp(z,"-vfs")==0 ){
  24406. zVfs = cmdline_option_value(argc, argv, ++i);
  24407. #ifdef SQLITE_HAVE_ZLIB
  24408. }else if( cli_strcmp(z,"-zip")==0 ){
  24409. data.openMode = SHELL_OPEN_ZIPFILE;
  24410. #endif
  24411. }else if( cli_strcmp(z,"-append")==0 ){
  24412. data.openMode = SHELL_OPEN_APPENDVFS;
  24413. #ifndef SQLITE_OMIT_DESERIALIZE
  24414. }else if( cli_strcmp(z,"-deserialize")==0 ){
  24415. data.openMode = SHELL_OPEN_DESERIALIZE;
  24416. }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
  24417. data.szMax = integerValue(argv[++i]);
  24418. #endif
  24419. }else if( cli_strcmp(z,"-readonly")==0 ){
  24420. data.openMode = SHELL_OPEN_READONLY;
  24421. }else if( cli_strcmp(z,"-nofollow")==0 ){
  24422. data.openFlags = SQLITE_OPEN_NOFOLLOW;
  24423. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  24424. }else if( cli_strncmp(z, "-A",2)==0 ){
  24425. /* All remaining command-line arguments are passed to the ".archive"
  24426. ** command, so ignore them */
  24427. break;
  24428. #endif
  24429. }else if( cli_strcmp(z, "-memtrace")==0 ){
  24430. sqlite3MemTraceActivate(stderr);
  24431. }else if( cli_strcmp(z,"-bail")==0 ){
  24432. bail_on_error = 1;
  24433. }else if( cli_strcmp(z,"-nonce")==0 ){
  24434. free(data.zNonce);
  24435. data.zNonce = strdup(argv[++i]);
  24436. }else if( cli_strcmp(z,"-safe")==0 ){
  24437. /* no-op - catch this on the second pass */
  24438. }
  24439. }
  24440. verify_uninitialized();
  24441. #ifdef SQLITE_SHELL_INIT_PROC
  24442. {
  24443. /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
  24444. ** of a C-function that will perform initialization actions on SQLite that
  24445. ** occur just before or after sqlite3_initialize(). Use this compile-time
  24446. ** option to embed this shell program in larger applications. */
  24447. extern void SQLITE_SHELL_INIT_PROC(void);
  24448. SQLITE_SHELL_INIT_PROC();
  24449. }
  24450. #else
  24451. /* All the sqlite3_config() calls have now been made. So it is safe
  24452. ** to call sqlite3_initialize() and process any command line -vfs option. */
  24453. sqlite3_initialize();
  24454. #endif
  24455. if( zVfs ){
  24456. sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
  24457. if( pVfs ){
  24458. sqlite3_vfs_register(pVfs, 1);
  24459. }else{
  24460. utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
  24461. exit(1);
  24462. }
  24463. }
  24464. if( data.pAuxDb->zDbFilename==0 ){
  24465. #ifndef SQLITE_OMIT_MEMORYDB
  24466. data.pAuxDb->zDbFilename = ":memory:";
  24467. warnInmemoryDb = argc==1;
  24468. #else
  24469. utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
  24470. return 1;
  24471. #endif
  24472. }
  24473. data.out = stdout;
  24474. #ifndef SQLITE_SHELL_FIDDLE
  24475. sqlite3_appendvfs_init(0,0,0);
  24476. #endif
  24477. /* Go ahead and open the database file if it already exists. If the
  24478. ** file does not exist, delay opening it. This prevents empty database
  24479. ** files from being created if a user mistypes the database name argument
  24480. ** to the sqlite command-line tool.
  24481. */
  24482. if( access(data.pAuxDb->zDbFilename, 0)==0 ){
  24483. open_db(&data, 0);
  24484. }
  24485. /* Process the initialization file if there is one. If no -init option
  24486. ** is given on the command line, look for a file named ~/.sqliterc and
  24487. ** try to process it.
  24488. */
  24489. process_sqliterc(&data,zInitFile);
  24490. /* Make a second pass through the command-line argument and set
  24491. ** options. This second pass is delayed until after the initialization
  24492. ** file is processed so that the command-line arguments will override
  24493. ** settings in the initialization file.
  24494. */
  24495. for(i=1; i<argc; i++){
  24496. char *z = argv[i];
  24497. if( z[0]!='-' ) continue;
  24498. if( z[1]=='-' ){ z++; }
  24499. if( cli_strcmp(z,"-init")==0 ){
  24500. i++;
  24501. }else if( cli_strcmp(z,"-html")==0 ){
  24502. data.mode = MODE_Html;
  24503. }else if( cli_strcmp(z,"-list")==0 ){
  24504. data.mode = MODE_List;
  24505. }else if( cli_strcmp(z,"-quote")==0 ){
  24506. data.mode = MODE_Quote;
  24507. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
  24508. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
  24509. }else if( cli_strcmp(z,"-line")==0 ){
  24510. data.mode = MODE_Line;
  24511. }else if( cli_strcmp(z,"-column")==0 ){
  24512. data.mode = MODE_Column;
  24513. }else if( cli_strcmp(z,"-json")==0 ){
  24514. data.mode = MODE_Json;
  24515. }else if( cli_strcmp(z,"-markdown")==0 ){
  24516. data.mode = MODE_Markdown;
  24517. }else if( cli_strcmp(z,"-table")==0 ){
  24518. data.mode = MODE_Table;
  24519. }else if( cli_strcmp(z,"-box")==0 ){
  24520. data.mode = MODE_Box;
  24521. }else if( cli_strcmp(z,"-csv")==0 ){
  24522. data.mode = MODE_Csv;
  24523. memcpy(data.colSeparator,",",2);
  24524. #ifdef SQLITE_HAVE_ZLIB
  24525. }else if( cli_strcmp(z,"-zip")==0 ){
  24526. data.openMode = SHELL_OPEN_ZIPFILE;
  24527. #endif
  24528. }else if( cli_strcmp(z,"-append")==0 ){
  24529. data.openMode = SHELL_OPEN_APPENDVFS;
  24530. #ifndef SQLITE_OMIT_DESERIALIZE
  24531. }else if( cli_strcmp(z,"-deserialize")==0 ){
  24532. data.openMode = SHELL_OPEN_DESERIALIZE;
  24533. }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
  24534. data.szMax = integerValue(argv[++i]);
  24535. #endif
  24536. }else if( cli_strcmp(z,"-readonly")==0 ){
  24537. data.openMode = SHELL_OPEN_READONLY;
  24538. }else if( cli_strcmp(z,"-nofollow")==0 ){
  24539. data.openFlags |= SQLITE_OPEN_NOFOLLOW;
  24540. }else if( cli_strcmp(z,"-ascii")==0 ){
  24541. data.mode = MODE_Ascii;
  24542. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
  24543. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
  24544. }else if( cli_strcmp(z,"-tabs")==0 ){
  24545. data.mode = MODE_List;
  24546. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
  24547. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
  24548. }else if( cli_strcmp(z,"-separator")==0 ){
  24549. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  24550. "%s",cmdline_option_value(argc,argv,++i));
  24551. }else if( cli_strcmp(z,"-newline")==0 ){
  24552. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  24553. "%s",cmdline_option_value(argc,argv,++i));
  24554. }else if( cli_strcmp(z,"-nullvalue")==0 ){
  24555. sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
  24556. "%s",cmdline_option_value(argc,argv,++i));
  24557. }else if( cli_strcmp(z,"-header")==0 ){
  24558. data.showHeader = 1;
  24559. ShellSetFlag(&data, SHFLG_HeaderSet);
  24560. }else if( cli_strcmp(z,"-noheader")==0 ){
  24561. data.showHeader = 0;
  24562. ShellSetFlag(&data, SHFLG_HeaderSet);
  24563. }else if( cli_strcmp(z,"-echo")==0 ){
  24564. ShellSetFlag(&data, SHFLG_Echo);
  24565. }else if( cli_strcmp(z,"-eqp")==0 ){
  24566. data.autoEQP = AUTOEQP_on;
  24567. }else if( cli_strcmp(z,"-eqpfull")==0 ){
  24568. data.autoEQP = AUTOEQP_full;
  24569. }else if( cli_strcmp(z,"-stats")==0 ){
  24570. data.statsOn = 1;
  24571. }else if( cli_strcmp(z,"-scanstats")==0 ){
  24572. data.scanstatsOn = 1;
  24573. }else if( cli_strcmp(z,"-backslash")==0 ){
  24574. /* Undocumented command-line option: -backslash
  24575. ** Causes C-style backslash escapes to be evaluated in SQL statements
  24576. ** prior to sending the SQL into SQLite. Useful for injecting
  24577. ** crazy bytes in the middle of SQL statements for testing and debugging.
  24578. */
  24579. ShellSetFlag(&data, SHFLG_Backslash);
  24580. }else if( cli_strcmp(z,"-bail")==0 ){
  24581. /* No-op. The bail_on_error flag should already be set. */
  24582. }else if( cli_strcmp(z,"-version")==0 ){
  24583. printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
  24584. return 0;
  24585. }else if( cli_strcmp(z,"-interactive")==0 ){
  24586. stdin_is_interactive = 1;
  24587. }else if( cli_strcmp(z,"-batch")==0 ){
  24588. stdin_is_interactive = 0;
  24589. }else if( cli_strcmp(z,"-heap")==0 ){
  24590. i++;
  24591. }else if( cli_strcmp(z,"-pagecache")==0 ){
  24592. i+=2;
  24593. }else if( cli_strcmp(z,"-lookaside")==0 ){
  24594. i+=2;
  24595. }else if( cli_strcmp(z,"-threadsafe")==0 ){
  24596. i+=2;
  24597. }else if( cli_strcmp(z,"-nonce")==0 ){
  24598. i += 2;
  24599. }else if( cli_strcmp(z,"-mmap")==0 ){
  24600. i++;
  24601. }else if( cli_strcmp(z,"-memtrace")==0 ){
  24602. i++;
  24603. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  24604. }else if( cli_strcmp(z,"-sorterref")==0 ){
  24605. i++;
  24606. #endif
  24607. }else if( cli_strcmp(z,"-vfs")==0 ){
  24608. i++;
  24609. #ifdef SQLITE_ENABLE_VFSTRACE
  24610. }else if( cli_strcmp(z,"-vfstrace")==0 ){
  24611. i++;
  24612. #endif
  24613. #ifdef SQLITE_ENABLE_MULTIPLEX
  24614. }else if( cli_strcmp(z,"-multiplex")==0 ){
  24615. i++;
  24616. #endif
  24617. }else if( cli_strcmp(z,"-help")==0 ){
  24618. usage(1);
  24619. }else if( cli_strcmp(z,"-cmd")==0 ){
  24620. /* Run commands that follow -cmd first and separately from commands
  24621. ** that simply appear on the command-line. This seems goofy. It would
  24622. ** be better if all commands ran in the order that they appear. But
  24623. ** we retain the goofy behavior for historical compatibility. */
  24624. if( i==argc-1 ) break;
  24625. z = cmdline_option_value(argc,argv,++i);
  24626. if( z[0]=='.' ){
  24627. rc = do_meta_command(z, &data);
  24628. if( rc && bail_on_error ) return rc==2 ? 0 : rc;
  24629. }else{
  24630. open_db(&data, 0);
  24631. rc = shell_exec(&data, z, &zErrMsg);
  24632. if( zErrMsg!=0 ){
  24633. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  24634. if( bail_on_error ) return rc!=0 ? rc : 1;
  24635. }else if( rc!=0 ){
  24636. utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
  24637. if( bail_on_error ) return rc;
  24638. }
  24639. }
  24640. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  24641. }else if( cli_strncmp(z, "-A", 2)==0 ){
  24642. if( nCmd>0 ){
  24643. utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
  24644. " with \"%s\"\n", z);
  24645. return 1;
  24646. }
  24647. open_db(&data, OPEN_DB_ZIPFILE);
  24648. if( z[2] ){
  24649. argv[i] = &z[2];
  24650. arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
  24651. }else{
  24652. arDotCommand(&data, 1, argv+i, argc-i);
  24653. }
  24654. readStdin = 0;
  24655. break;
  24656. #endif
  24657. }else if( cli_strcmp(z,"-safe")==0 ){
  24658. data.bSafeMode = data.bSafeModePersist = 1;
  24659. }else{
  24660. utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
  24661. raw_printf(stderr,"Use -help for a list of options.\n");
  24662. return 1;
  24663. }
  24664. data.cMode = data.mode;
  24665. }
  24666. if( !readStdin ){
  24667. /* Run all arguments that do not begin with '-' as if they were separate
  24668. ** command-line inputs, except for the argToSkip argument which contains
  24669. ** the database filename.
  24670. */
  24671. for(i=0; i<nCmd; i++){
  24672. if( azCmd[i][0]=='.' ){
  24673. rc = do_meta_command(azCmd[i], &data);
  24674. if( rc ){
  24675. free(azCmd);
  24676. return rc==2 ? 0 : rc;
  24677. }
  24678. }else{
  24679. open_db(&data, 0);
  24680. rc = shell_exec(&data, azCmd[i], &zErrMsg);
  24681. if( zErrMsg || rc ){
  24682. if( zErrMsg!=0 ){
  24683. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  24684. }else{
  24685. utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
  24686. }
  24687. sqlite3_free(zErrMsg);
  24688. free(azCmd);
  24689. return rc!=0 ? rc : 1;
  24690. }
  24691. }
  24692. }
  24693. }else{
  24694. /* Run commands received from standard input
  24695. */
  24696. if( stdin_is_interactive ){
  24697. char *zHome;
  24698. char *zHistory;
  24699. int nHistory;
  24700. printf(
  24701. "SQLite version %s %.19s\n" /*extra-version-info*/
  24702. "Enter \".help\" for usage hints.\n",
  24703. sqlite3_libversion(), sqlite3_sourceid()
  24704. );
  24705. if( warnInmemoryDb ){
  24706. printf("Connected to a ");
  24707. printBold("transient in-memory database");
  24708. printf(".\nUse \".open FILENAME\" to reopen on a "
  24709. "persistent database.\n");
  24710. }
  24711. zHistory = getenv("SQLITE_HISTORY");
  24712. if( zHistory ){
  24713. zHistory = strdup(zHistory);
  24714. }else if( (zHome = find_home_dir(0))!=0 ){
  24715. nHistory = strlen30(zHome) + 20;
  24716. if( (zHistory = malloc(nHistory))!=0 ){
  24717. sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  24718. }
  24719. }
  24720. if( zHistory ){ shell_read_history(zHistory); }
  24721. #if HAVE_READLINE || HAVE_EDITLINE
  24722. rl_attempted_completion_function = readline_completion;
  24723. #elif HAVE_LINENOISE
  24724. linenoiseSetCompletionCallback(linenoise_completion);
  24725. #endif
  24726. data.in = 0;
  24727. rc = process_input(&data);
  24728. if( zHistory ){
  24729. shell_stifle_history(2000);
  24730. shell_write_history(zHistory);
  24731. free(zHistory);
  24732. }
  24733. }else{
  24734. data.in = stdin;
  24735. rc = process_input(&data);
  24736. }
  24737. }
  24738. #ifndef SQLITE_SHELL_FIDDLE
  24739. /* In WASM mode we have to leave the db state in place so that
  24740. ** client code can "push" SQL into it after this call returns. */
  24741. free(azCmd);
  24742. set_table_name(&data, 0);
  24743. if( data.db ){
  24744. session_close_all(&data, -1);
  24745. close_db(data.db);
  24746. }
  24747. for(i=0; i<ArraySize(data.aAuxDb); i++){
  24748. sqlite3_free(data.aAuxDb[i].zFreeOnClose);
  24749. if( data.aAuxDb[i].db ){
  24750. session_close_all(&data, i);
  24751. close_db(data.aAuxDb[i].db);
  24752. }
  24753. }
  24754. find_home_dir(1);
  24755. output_reset(&data);
  24756. data.doXdgOpen = 0;
  24757. clearTempFile(&data);
  24758. #if !SQLITE_SHELL_IS_UTF8
  24759. for(i=0; i<argcToFree; i++) free(argvToFree[i]);
  24760. free(argvToFree);
  24761. #endif
  24762. free(data.colWidth);
  24763. free(data.zNonce);
  24764. /* Clear the global data structure so that valgrind will detect memory
  24765. ** leaks */
  24766. memset(&data, 0, sizeof(data));
  24767. #ifdef SQLITE_DEBUG
  24768. if( sqlite3_memory_used()>mem_main_enter ){
  24769. utf8_printf(stderr, "Memory leaked: %u bytes\n",
  24770. (unsigned int)(sqlite3_memory_used()-mem_main_enter));
  24771. }
  24772. #endif
  24773. #endif /* !SQLITE_SHELL_FIDDLE */
  24774. return rc;
  24775. }
  24776. #ifdef SQLITE_SHELL_FIDDLE
  24777. /* Only for emcc experimentation purposes. */
  24778. int fiddle_experiment(int a,int b){
  24779. return a + b;
  24780. }
  24781. /*
  24782. ** Returns a pointer to the current DB handle.
  24783. */
  24784. sqlite3 * fiddle_db_handle(){
  24785. return globalDb;
  24786. }
  24787. /*
  24788. ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
  24789. ** "main" is assumed. Returns 0 if no db with the given name is
  24790. ** open.
  24791. */
  24792. sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
  24793. sqlite3_vfs * pVfs = 0;
  24794. if(globalDb){
  24795. sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
  24796. SQLITE_FCNTL_VFS_POINTER, &pVfs);
  24797. }
  24798. return pVfs;
  24799. }
  24800. /* Only for emcc experimentation purposes. */
  24801. sqlite3 * fiddle_db_arg(sqlite3 *arg){
  24802. printf("fiddle_db_arg(%p)\n", (const void*)arg);
  24803. return arg;
  24804. }
  24805. /*
  24806. ** Intended to be called via a SharedWorker() while a separate
  24807. ** SharedWorker() (which manages the wasm module) is performing work
  24808. ** which should be interrupted. Unfortunately, SharedWorker is not
  24809. ** portable enough to make real use of.
  24810. */
  24811. void fiddle_interrupt(void){
  24812. if( globalDb ) sqlite3_interrupt(globalDb);
  24813. }
  24814. /*
  24815. ** Returns the filename of the given db name, assuming "main" if
  24816. ** zDbName is NULL. Returns NULL if globalDb is not opened.
  24817. */
  24818. const char * fiddle_db_filename(const char * zDbName){
  24819. return globalDb
  24820. ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
  24821. : NULL;
  24822. }
  24823. /*
  24824. ** Completely wipes out the contents of the currently-opened database
  24825. ** but leaves its storage intact for reuse.
  24826. */
  24827. void fiddle_reset_db(void){
  24828. if( globalDb ){
  24829. int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
  24830. if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
  24831. sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
  24832. }
  24833. }
  24834. /*
  24835. ** Uses the current database's VFS xRead to stream the db file's
  24836. ** contents out to the given callback. The callback gets a single
  24837. ** chunk of size n (its 2nd argument) on each call and must return 0
  24838. ** on success, non-0 on error. This function returns 0 on success,
  24839. ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
  24840. ** code from the callback. Note that this is not thread-friendly: it
  24841. ** expects that it will be the only thread reading the db file and
  24842. ** takes no measures to ensure that is the case.
  24843. */
  24844. int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
  24845. sqlite3_int64 nSize = 0;
  24846. sqlite3_int64 nPos = 0;
  24847. sqlite3_file * pFile = 0;
  24848. unsigned char buf[1024 * 8];
  24849. int nBuf = (int)sizeof(buf);
  24850. int rc = shellState.db
  24851. ? sqlite3_file_control(shellState.db, "main",
  24852. SQLITE_FCNTL_FILE_POINTER, &pFile)
  24853. : SQLITE_NOTFOUND;
  24854. if( rc ) return rc;
  24855. rc = pFile->pMethods->xFileSize(pFile, &nSize);
  24856. if( rc ) return rc;
  24857. if(nSize % nBuf){
  24858. /* DB size is not an even multiple of the buffer size. Reduce
  24859. ** buffer size so that we do not unduly inflate the db size when
  24860. ** exporting. */
  24861. if(0 == nSize % 4096) nBuf = 4096;
  24862. else if(0 == nSize % 2048) nBuf = 2048;
  24863. else if(0 == nSize % 1024) nBuf = 1024;
  24864. else nBuf = 512;
  24865. }
  24866. for( ; 0==rc && nPos<nSize; nPos += nBuf ){
  24867. rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
  24868. if(SQLITE_IOERR_SHORT_READ == rc){
  24869. rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
  24870. }
  24871. if( 0==rc ) rc = xCallback(buf, nBuf);
  24872. }
  24873. return rc;
  24874. }
  24875. /*
  24876. ** Trivial exportable function for emscripten. It processes zSql as if
  24877. ** it were input to the sqlite3 shell and redirects all output to the
  24878. ** wasm binding. fiddle_main() must have been called before this
  24879. ** is called, or results are undefined.
  24880. */
  24881. void fiddle_exec(const char * zSql){
  24882. if(zSql && *zSql){
  24883. if('.'==*zSql) puts(zSql);
  24884. shellState.wasm.zInput = zSql;
  24885. shellState.wasm.zPos = zSql;
  24886. process_input(&shellState);
  24887. shellState.wasm.zInput = shellState.wasm.zPos = 0;
  24888. }
  24889. }
  24890. #endif /* SQLITE_SHELL_FIDDLE */