shell.c 708 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503
  1. /* DO NOT EDIT!
  2. ** This file is automatically generated by the script in the canonical
  3. ** SQLite source tree at tool/mkshellc.tcl. That script combines source
  4. ** code from various constituent source files of SQLite into this single
  5. ** "shell.c" file used to implement the SQLite command-line shell.
  6. **
  7. ** Most of the code found below comes from the "src/shell.c.in" file in
  8. ** the canonical SQLite source tree. That main file contains "INCLUDE"
  9. ** lines that specify other files in the canonical source tree that are
  10. ** inserted to getnerate this complete program source file.
  11. **
  12. ** The code from multiple files is combined into this single "shell.c"
  13. ** source file to help make the command-line program easier to compile.
  14. **
  15. ** To modify this program, get a copy of the canonical SQLite source tree,
  16. ** edit the src/shell.c.in" and/or some of the other files that are included
  17. ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
  18. */
  19. /*
  20. ** 2001 September 15
  21. **
  22. ** The author disclaims copyright to this source code. In place of
  23. ** a legal notice, here is a blessing:
  24. **
  25. ** May you do good and not evil.
  26. ** May you find forgiveness for yourself and forgive others.
  27. ** May you share freely, never taking more than you give.
  28. **
  29. *************************************************************************
  30. ** This file contains code to implement the "sqlite" command line
  31. ** utility for accessing SQLite databases.
  32. */
  33. #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
  34. /* This needs to come before any includes for MSVC compiler */
  35. #define _CRT_SECURE_NO_WARNINGS
  36. #endif
  37. /*
  38. ** Optionally #include a user-defined header, whereby compilation options
  39. ** may be set prior to where they take effect, but after platform setup.
  40. ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
  41. ** file. Note that this macro has a like effect on sqlite3.c compilation.
  42. */
  43. # define SHELL_STRINGIFY_(f) #f
  44. # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
  45. #ifdef SQLITE_CUSTOM_INCLUDE
  46. # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
  47. #endif
  48. /*
  49. ** Determine if we are dealing with WinRT, which provides only a subset of
  50. ** the full Win32 API.
  51. */
  52. #if !defined(SQLITE_OS_WINRT)
  53. # define SQLITE_OS_WINRT 0
  54. #endif
  55. /*
  56. ** Warning pragmas copied from msvc.h in the core.
  57. */
  58. #if defined(_MSC_VER)
  59. #pragma warning(disable : 4054)
  60. #pragma warning(disable : 4055)
  61. #pragma warning(disable : 4100)
  62. #pragma warning(disable : 4127)
  63. #pragma warning(disable : 4130)
  64. #pragma warning(disable : 4152)
  65. #pragma warning(disable : 4189)
  66. #pragma warning(disable : 4206)
  67. #pragma warning(disable : 4210)
  68. #pragma warning(disable : 4232)
  69. #pragma warning(disable : 4244)
  70. #pragma warning(disable : 4305)
  71. #pragma warning(disable : 4306)
  72. #pragma warning(disable : 4702)
  73. #pragma warning(disable : 4706)
  74. #endif /* defined(_MSC_VER) */
  75. /*
  76. ** No support for loadable extensions in VxWorks.
  77. */
  78. #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
  79. # define SQLITE_OMIT_LOAD_EXTENSION 1
  80. #endif
  81. /*
  82. ** Enable large-file support for fopen() and friends on unix.
  83. */
  84. #ifndef SQLITE_DISABLE_LFS
  85. # define _LARGE_FILE 1
  86. # ifndef _FILE_OFFSET_BITS
  87. # define _FILE_OFFSET_BITS 64
  88. # endif
  89. # define _LARGEFILE_SOURCE 1
  90. #endif
  91. #include <stdlib.h>
  92. #include <string.h>
  93. #include <stdio.h>
  94. #include <assert.h>
  95. #include "sqlite3.h"
  96. typedef sqlite3_int64 i64;
  97. typedef sqlite3_uint64 u64;
  98. typedef unsigned char u8;
  99. #if SQLITE_USER_AUTHENTICATION
  100. # include "sqlite3userauth.h"
  101. #endif
  102. #include <ctype.h>
  103. #include <stdarg.h>
  104. #if !defined(_WIN32) && !defined(WIN32)
  105. # include <signal.h>
  106. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  107. # include <pwd.h>
  108. # endif
  109. #endif
  110. #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
  111. # include <unistd.h>
  112. # include <dirent.h>
  113. # define GETPID getpid
  114. # if defined(__MINGW32__)
  115. # define DIRENT dirent
  116. # ifndef S_ISLNK
  117. # define S_ISLNK(mode) (0)
  118. # endif
  119. # endif
  120. #else
  121. # define GETPID (int)GetCurrentProcessId
  122. #endif
  123. #include <sys/types.h>
  124. #include <sys/stat.h>
  125. #if HAVE_READLINE
  126. # include <readline/readline.h>
  127. # include <readline/history.h>
  128. #endif
  129. #if HAVE_EDITLINE
  130. # include <editline/readline.h>
  131. #endif
  132. #if HAVE_EDITLINE || HAVE_READLINE
  133. # define shell_add_history(X) add_history(X)
  134. # define shell_read_history(X) read_history(X)
  135. # define shell_write_history(X) write_history(X)
  136. # define shell_stifle_history(X) stifle_history(X)
  137. # define shell_readline(X) readline(X)
  138. #elif HAVE_LINENOISE
  139. # include "linenoise.h"
  140. # define shell_add_history(X) linenoiseHistoryAdd(X)
  141. # define shell_read_history(X) linenoiseHistoryLoad(X)
  142. # define shell_write_history(X) linenoiseHistorySave(X)
  143. # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
  144. # define shell_readline(X) linenoise(X)
  145. #else
  146. # define shell_read_history(X)
  147. # define shell_write_history(X)
  148. # define shell_stifle_history(X)
  149. # define SHELL_USE_LOCAL_GETLINE 1
  150. #endif
  151. #if defined(_WIN32) || defined(WIN32)
  152. # if SQLITE_OS_WINRT
  153. # define SQLITE_OMIT_POPEN 1
  154. # else
  155. # include <io.h>
  156. # include <fcntl.h>
  157. # define isatty(h) _isatty(h)
  158. # ifndef access
  159. # define access(f,m) _access((f),(m))
  160. # endif
  161. # ifndef unlink
  162. # define unlink _unlink
  163. # endif
  164. # ifndef strdup
  165. # define strdup _strdup
  166. # endif
  167. # undef popen
  168. # define popen _popen
  169. # undef pclose
  170. # define pclose _pclose
  171. # endif
  172. #else
  173. /* Make sure isatty() has a prototype. */
  174. extern int isatty(int);
  175. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  176. /* popen and pclose are not C89 functions and so are
  177. ** sometimes omitted from the <stdio.h> header */
  178. extern FILE *popen(const char*,const char*);
  179. extern int pclose(FILE*);
  180. # else
  181. # define SQLITE_OMIT_POPEN 1
  182. # endif
  183. #endif
  184. #if defined(_WIN32_WCE)
  185. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
  186. * thus we always assume that we have a console. That can be
  187. * overridden with the -batch command line option.
  188. */
  189. #define isatty(x) 1
  190. #endif
  191. /* ctype macros that work with signed characters */
  192. #define IsSpace(X) isspace((unsigned char)X)
  193. #define IsDigit(X) isdigit((unsigned char)X)
  194. #define ToLower(X) (char)tolower((unsigned char)X)
  195. #if defined(_WIN32) || defined(WIN32)
  196. #if SQLITE_OS_WINRT
  197. #include <intrin.h>
  198. #endif
  199. #include <windows.h>
  200. /* string conversion routines only needed on Win32 */
  201. extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
  202. extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
  203. extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
  204. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
  205. #endif
  206. /* On Windows, we normally run with output mode of TEXT so that \n characters
  207. ** are automatically translated into \r\n. However, this behavior needs
  208. ** to be disabled in some cases (ex: when generating CSV output and when
  209. ** rendering quoted strings that contain \n characters). The following
  210. ** routines take care of that.
  211. */
  212. #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
  213. static void setBinaryMode(FILE *file, int isOutput){
  214. if( isOutput ) fflush(file);
  215. _setmode(_fileno(file), _O_BINARY);
  216. }
  217. static void setTextMode(FILE *file, int isOutput){
  218. if( isOutput ) fflush(file);
  219. _setmode(_fileno(file), _O_TEXT);
  220. }
  221. #else
  222. # define setBinaryMode(X,Y)
  223. # define setTextMode(X,Y)
  224. #endif
  225. /* True if the timer is enabled */
  226. static int enableTimer = 0;
  227. /* Return the current wall-clock time */
  228. static sqlite3_int64 timeOfDay(void){
  229. static sqlite3_vfs *clockVfs = 0;
  230. sqlite3_int64 t;
  231. if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
  232. if( clockVfs==0 ) return 0; /* Never actually happens */
  233. if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
  234. clockVfs->xCurrentTimeInt64(clockVfs, &t);
  235. }else{
  236. double r;
  237. clockVfs->xCurrentTime(clockVfs, &r);
  238. t = (sqlite3_int64)(r*86400000.0);
  239. }
  240. return t;
  241. }
  242. #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
  243. #include <sys/time.h>
  244. #include <sys/resource.h>
  245. /* VxWorks does not support getrusage() as far as we can determine */
  246. #if defined(_WRS_KERNEL) || defined(__RTP__)
  247. struct rusage {
  248. struct timeval ru_utime; /* user CPU time used */
  249. struct timeval ru_stime; /* system CPU time used */
  250. };
  251. #define getrusage(A,B) memset(B,0,sizeof(*B))
  252. #endif
  253. /* Saved resource information for the beginning of an operation */
  254. static struct rusage sBegin; /* CPU time at start */
  255. static sqlite3_int64 iBegin; /* Wall-clock time at start */
  256. /*
  257. ** Begin timing an operation
  258. */
  259. static void beginTimer(void){
  260. if( enableTimer ){
  261. getrusage(RUSAGE_SELF, &sBegin);
  262. iBegin = timeOfDay();
  263. }
  264. }
  265. /* Return the difference of two time_structs in seconds */
  266. static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  267. return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
  268. (double)(pEnd->tv_sec - pStart->tv_sec);
  269. }
  270. /*
  271. ** Print the timing results.
  272. */
  273. static void endTimer(void){
  274. if( enableTimer ){
  275. sqlite3_int64 iEnd = timeOfDay();
  276. struct rusage sEnd;
  277. getrusage(RUSAGE_SELF, &sEnd);
  278. printf("Run Time: real %.3f user %f sys %f\n",
  279. (iEnd - iBegin)*0.001,
  280. timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
  281. timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  282. }
  283. }
  284. #define BEGIN_TIMER beginTimer()
  285. #define END_TIMER endTimer()
  286. #define HAS_TIMER 1
  287. #elif (defined(_WIN32) || defined(WIN32))
  288. /* Saved resource information for the beginning of an operation */
  289. static HANDLE hProcess;
  290. static FILETIME ftKernelBegin;
  291. static FILETIME ftUserBegin;
  292. static sqlite3_int64 ftWallBegin;
  293. typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
  294. LPFILETIME, LPFILETIME);
  295. static GETPROCTIMES getProcessTimesAddr = NULL;
  296. /*
  297. ** Check to see if we have timer support. Return 1 if necessary
  298. ** support found (or found previously).
  299. */
  300. static int hasTimer(void){
  301. if( getProcessTimesAddr ){
  302. return 1;
  303. } else {
  304. #if !SQLITE_OS_WINRT
  305. /* GetProcessTimes() isn't supported in WIN95 and some other Windows
  306. ** versions. See if the version we are running on has it, and if it
  307. ** does, save off a pointer to it and the current process handle.
  308. */
  309. hProcess = GetCurrentProcess();
  310. if( hProcess ){
  311. HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
  312. if( NULL != hinstLib ){
  313. getProcessTimesAddr =
  314. (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
  315. if( NULL != getProcessTimesAddr ){
  316. return 1;
  317. }
  318. FreeLibrary(hinstLib);
  319. }
  320. }
  321. #endif
  322. }
  323. return 0;
  324. }
  325. /*
  326. ** Begin timing an operation
  327. */
  328. static void beginTimer(void){
  329. if( enableTimer && getProcessTimesAddr ){
  330. FILETIME ftCreation, ftExit;
  331. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
  332. &ftKernelBegin,&ftUserBegin);
  333. ftWallBegin = timeOfDay();
  334. }
  335. }
  336. /* Return the difference of two FILETIME structs in seconds */
  337. static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
  338. sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
  339. sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
  340. return (double) ((i64End - i64Start) / 10000000.0);
  341. }
  342. /*
  343. ** Print the timing results.
  344. */
  345. static void endTimer(void){
  346. if( enableTimer && getProcessTimesAddr){
  347. FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
  348. sqlite3_int64 ftWallEnd = timeOfDay();
  349. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
  350. printf("Run Time: real %.3f user %f sys %f\n",
  351. (ftWallEnd - ftWallBegin)*0.001,
  352. timeDiff(&ftUserBegin, &ftUserEnd),
  353. timeDiff(&ftKernelBegin, &ftKernelEnd));
  354. }
  355. }
  356. #define BEGIN_TIMER beginTimer()
  357. #define END_TIMER endTimer()
  358. #define HAS_TIMER hasTimer()
  359. #else
  360. #define BEGIN_TIMER
  361. #define END_TIMER
  362. #define HAS_TIMER 0
  363. #endif
  364. /*
  365. ** Used to prevent warnings about unused parameters
  366. */
  367. #define UNUSED_PARAMETER(x) (void)(x)
  368. /*
  369. ** Number of elements in an array
  370. */
  371. #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
  372. /*
  373. ** If the following flag is set, then command execution stops
  374. ** at an error if we are not interactive.
  375. */
  376. static int bail_on_error = 0;
  377. /*
  378. ** Threat stdin as an interactive input if the following variable
  379. ** is true. Otherwise, assume stdin is connected to a file or pipe.
  380. */
  381. static int stdin_is_interactive = 1;
  382. /*
  383. ** On Windows systems we have to know if standard output is a console
  384. ** in order to translate UTF-8 into MBCS. The following variable is
  385. ** true if translation is required.
  386. */
  387. static int stdout_is_console = 1;
  388. /*
  389. ** The following is the open SQLite database. We make a pointer
  390. ** to this database a static variable so that it can be accessed
  391. ** by the SIGINT handler to interrupt database processing.
  392. */
  393. static sqlite3 *globalDb = 0;
  394. /*
  395. ** True if an interrupt (Control-C) has been received.
  396. */
  397. static volatile int seenInterrupt = 0;
  398. /*
  399. ** This is the name of our program. It is set in main(), used
  400. ** in a number of other places, mostly for error messages.
  401. */
  402. static char *Argv0;
  403. /*
  404. ** Prompt strings. Initialized in main. Settable with
  405. ** .prompt main continue
  406. */
  407. static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
  408. static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
  409. /*
  410. ** Render output like fprintf(). Except, if the output is going to the
  411. ** console and if this is running on a Windows machine, translate the
  412. ** output from UTF-8 into MBCS.
  413. */
  414. #if defined(_WIN32) || defined(WIN32)
  415. void utf8_printf(FILE *out, const char *zFormat, ...){
  416. va_list ap;
  417. va_start(ap, zFormat);
  418. if( stdout_is_console && (out==stdout || out==stderr) ){
  419. char *z1 = sqlite3_vmprintf(zFormat, ap);
  420. char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
  421. sqlite3_free(z1);
  422. fputs(z2, out);
  423. sqlite3_free(z2);
  424. }else{
  425. vfprintf(out, zFormat, ap);
  426. }
  427. va_end(ap);
  428. }
  429. #elif !defined(utf8_printf)
  430. # define utf8_printf fprintf
  431. #endif
  432. /*
  433. ** Render output like fprintf(). This should not be used on anything that
  434. ** includes string formatting (e.g. "%s").
  435. */
  436. #if !defined(raw_printf)
  437. # define raw_printf fprintf
  438. #endif
  439. /* Indicate out-of-memory and exit. */
  440. static void shell_out_of_memory(void){
  441. raw_printf(stderr,"Error: out of memory\n");
  442. exit(1);
  443. }
  444. /* Check a pointer to see if it is NULL. If it is NULL, exit with an
  445. ** out-of-memory error.
  446. */
  447. static void shell_check_oom(void *p){
  448. if( p==0 ) shell_out_of_memory();
  449. }
  450. /*
  451. ** Write I/O traces to the following stream.
  452. */
  453. #ifdef SQLITE_ENABLE_IOTRACE
  454. static FILE *iotrace = 0;
  455. #endif
  456. /*
  457. ** This routine works like printf in that its first argument is a
  458. ** format string and subsequent arguments are values to be substituted
  459. ** in place of % fields. The result of formatting this string
  460. ** is written to iotrace.
  461. */
  462. #ifdef SQLITE_ENABLE_IOTRACE
  463. static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
  464. va_list ap;
  465. char *z;
  466. if( iotrace==0 ) return;
  467. va_start(ap, zFormat);
  468. z = sqlite3_vmprintf(zFormat, ap);
  469. va_end(ap);
  470. utf8_printf(iotrace, "%s", z);
  471. sqlite3_free(z);
  472. }
  473. #endif
  474. /*
  475. ** Output string zUtf to stream pOut as w characters. If w is negative,
  476. ** then right-justify the text. W is the width in UTF-8 characters, not
  477. ** in bytes. This is different from the %*.*s specification in printf
  478. ** since with %*.*s the width is measured in bytes, not characters.
  479. */
  480. static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
  481. int i;
  482. int n;
  483. int aw = w<0 ? -w : w;
  484. for(i=n=0; zUtf[i]; i++){
  485. if( (zUtf[i]&0xc0)!=0x80 ){
  486. n++;
  487. if( n==aw ){
  488. do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
  489. break;
  490. }
  491. }
  492. }
  493. if( n>=aw ){
  494. utf8_printf(pOut, "%.*s", i, zUtf);
  495. }else if( w<0 ){
  496. utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
  497. }else{
  498. utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
  499. }
  500. }
  501. /*
  502. ** Determines if a string is a number of not.
  503. */
  504. static int isNumber(const char *z, int *realnum){
  505. if( *z=='-' || *z=='+' ) z++;
  506. if( !IsDigit(*z) ){
  507. return 0;
  508. }
  509. z++;
  510. if( realnum ) *realnum = 0;
  511. while( IsDigit(*z) ){ z++; }
  512. if( *z=='.' ){
  513. z++;
  514. if( !IsDigit(*z) ) return 0;
  515. while( IsDigit(*z) ){ z++; }
  516. if( realnum ) *realnum = 1;
  517. }
  518. if( *z=='e' || *z=='E' ){
  519. z++;
  520. if( *z=='+' || *z=='-' ) z++;
  521. if( !IsDigit(*z) ) return 0;
  522. while( IsDigit(*z) ){ z++; }
  523. if( realnum ) *realnum = 1;
  524. }
  525. return *z==0;
  526. }
  527. /*
  528. ** Compute a string length that is limited to what can be stored in
  529. ** lower 30 bits of a 32-bit signed integer.
  530. */
  531. static int strlen30(const char *z){
  532. const char *z2 = z;
  533. while( *z2 ){ z2++; }
  534. return 0x3fffffff & (int)(z2 - z);
  535. }
  536. /*
  537. ** Return the length of a string in characters. Multibyte UTF8 characters
  538. ** count as a single character.
  539. */
  540. static int strlenChar(const char *z){
  541. int n = 0;
  542. while( *z ){
  543. if( (0xc0&*(z++))!=0x80 ) n++;
  544. }
  545. return n;
  546. }
  547. /*
  548. ** Return open FILE * if zFile exists, can be opened for read
  549. ** and is an ordinary file or a character stream source.
  550. ** Otherwise return 0.
  551. */
  552. static FILE * openChrSource(const char *zFile){
  553. #ifdef _WIN32
  554. struct _stat x = {0};
  555. # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
  556. /* On Windows, open first, then check the stream nature. This order
  557. ** is necessary because _stat() and sibs, when checking a named pipe,
  558. ** effectively break the pipe as its supplier sees it. */
  559. FILE *rv = fopen(zFile, "rb");
  560. if( rv==0 ) return 0;
  561. if( _fstat(_fileno(rv), &x) != 0
  562. || !STAT_CHR_SRC(x.st_mode)){
  563. fclose(rv);
  564. rv = 0;
  565. }
  566. return rv;
  567. #else
  568. struct stat x = {0};
  569. int rc = stat(zFile, &x);
  570. # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
  571. if( rc!=0 ) return 0;
  572. if( STAT_CHR_SRC(x.st_mode) ){
  573. return fopen(zFile, "rb");
  574. }else{
  575. return 0;
  576. }
  577. #endif
  578. #undef STAT_CHR_SRC
  579. }
  580. /*
  581. ** This routine reads a line of text from FILE in, stores
  582. ** the text in memory obtained from malloc() and returns a pointer
  583. ** to the text. NULL is returned at end of file, or if malloc()
  584. ** fails.
  585. **
  586. ** If zLine is not NULL then it is a malloced buffer returned from
  587. ** a previous call to this routine that may be reused.
  588. */
  589. static char *local_getline(char *zLine, FILE *in){
  590. int nLine = zLine==0 ? 0 : 100;
  591. int n = 0;
  592. while( 1 ){
  593. if( n+100>nLine ){
  594. nLine = nLine*2 + 100;
  595. zLine = realloc(zLine, nLine);
  596. shell_check_oom(zLine);
  597. }
  598. if( fgets(&zLine[n], nLine - n, in)==0 ){
  599. if( n==0 ){
  600. free(zLine);
  601. return 0;
  602. }
  603. zLine[n] = 0;
  604. break;
  605. }
  606. while( zLine[n] ) n++;
  607. if( n>0 && zLine[n-1]=='\n' ){
  608. n--;
  609. if( n>0 && zLine[n-1]=='\r' ) n--;
  610. zLine[n] = 0;
  611. break;
  612. }
  613. }
  614. #if defined(_WIN32) || defined(WIN32)
  615. /* For interactive input on Windows systems, translate the
  616. ** multi-byte characterset characters into UTF-8. */
  617. if( stdin_is_interactive && in==stdin ){
  618. char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
  619. if( zTrans ){
  620. int nTrans = strlen30(zTrans)+1;
  621. if( nTrans>nLine ){
  622. zLine = realloc(zLine, nTrans);
  623. shell_check_oom(zLine);
  624. }
  625. memcpy(zLine, zTrans, nTrans);
  626. sqlite3_free(zTrans);
  627. }
  628. }
  629. #endif /* defined(_WIN32) || defined(WIN32) */
  630. return zLine;
  631. }
  632. /*
  633. ** Retrieve a single line of input text.
  634. **
  635. ** If in==0 then read from standard input and prompt before each line.
  636. ** If isContinuation is true, then a continuation prompt is appropriate.
  637. ** If isContinuation is zero, then the main prompt should be used.
  638. **
  639. ** If zPrior is not NULL then it is a buffer from a prior call to this
  640. ** routine that can be reused.
  641. **
  642. ** The result is stored in space obtained from malloc() and must either
  643. ** be freed by the caller or else passed back into this routine via the
  644. ** zPrior argument for reuse.
  645. */
  646. static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
  647. char *zPrompt;
  648. char *zResult;
  649. if( in!=0 ){
  650. zResult = local_getline(zPrior, in);
  651. }else{
  652. zPrompt = isContinuation ? continuePrompt : mainPrompt;
  653. #if SHELL_USE_LOCAL_GETLINE
  654. printf("%s", zPrompt);
  655. fflush(stdout);
  656. zResult = local_getline(zPrior, stdin);
  657. #else
  658. free(zPrior);
  659. zResult = shell_readline(zPrompt);
  660. if( zResult && *zResult ) shell_add_history(zResult);
  661. #endif
  662. }
  663. return zResult;
  664. }
  665. /*
  666. ** Return the value of a hexadecimal digit. Return -1 if the input
  667. ** is not a hex digit.
  668. */
  669. static int hexDigitValue(char c){
  670. if( c>='0' && c<='9' ) return c - '0';
  671. if( c>='a' && c<='f' ) return c - 'a' + 10;
  672. if( c>='A' && c<='F' ) return c - 'A' + 10;
  673. return -1;
  674. }
  675. /*
  676. ** Interpret zArg as an integer value, possibly with suffixes.
  677. */
  678. static sqlite3_int64 integerValue(const char *zArg){
  679. sqlite3_int64 v = 0;
  680. static const struct { char *zSuffix; int iMult; } aMult[] = {
  681. { "KiB", 1024 },
  682. { "MiB", 1024*1024 },
  683. { "GiB", 1024*1024*1024 },
  684. { "KB", 1000 },
  685. { "MB", 1000000 },
  686. { "GB", 1000000000 },
  687. { "K", 1000 },
  688. { "M", 1000000 },
  689. { "G", 1000000000 },
  690. };
  691. int i;
  692. int isNeg = 0;
  693. if( zArg[0]=='-' ){
  694. isNeg = 1;
  695. zArg++;
  696. }else if( zArg[0]=='+' ){
  697. zArg++;
  698. }
  699. if( zArg[0]=='0' && zArg[1]=='x' ){
  700. int x;
  701. zArg += 2;
  702. while( (x = hexDigitValue(zArg[0]))>=0 ){
  703. v = (v<<4) + x;
  704. zArg++;
  705. }
  706. }else{
  707. while( IsDigit(zArg[0]) ){
  708. v = v*10 + zArg[0] - '0';
  709. zArg++;
  710. }
  711. }
  712. for(i=0; i<ArraySize(aMult); i++){
  713. if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
  714. v *= aMult[i].iMult;
  715. break;
  716. }
  717. }
  718. return isNeg? -v : v;
  719. }
  720. /*
  721. ** A variable length string to which one can append text.
  722. */
  723. typedef struct ShellText ShellText;
  724. struct ShellText {
  725. char *z;
  726. int n;
  727. int nAlloc;
  728. };
  729. /*
  730. ** Initialize and destroy a ShellText object
  731. */
  732. static void initText(ShellText *p){
  733. memset(p, 0, sizeof(*p));
  734. }
  735. static void freeText(ShellText *p){
  736. free(p->z);
  737. initText(p);
  738. }
  739. /* zIn is either a pointer to a NULL-terminated string in memory obtained
  740. ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  741. ** added to zIn, and the result returned in memory obtained from malloc().
  742. ** zIn, if it was not NULL, is freed.
  743. **
  744. ** If the third argument, quote, is not '\0', then it is used as a
  745. ** quote character for zAppend.
  746. */
  747. static void appendText(ShellText *p, char const *zAppend, char quote){
  748. int len;
  749. int i;
  750. int nAppend = strlen30(zAppend);
  751. len = nAppend+p->n+1;
  752. if( quote ){
  753. len += 2;
  754. for(i=0; i<nAppend; i++){
  755. if( zAppend[i]==quote ) len++;
  756. }
  757. }
  758. if( p->z==0 || p->n+len>=p->nAlloc ){
  759. p->nAlloc = p->nAlloc*2 + len + 20;
  760. p->z = realloc(p->z, p->nAlloc);
  761. shell_check_oom(p->z);
  762. }
  763. if( quote ){
  764. char *zCsr = p->z+p->n;
  765. *zCsr++ = quote;
  766. for(i=0; i<nAppend; i++){
  767. *zCsr++ = zAppend[i];
  768. if( zAppend[i]==quote ) *zCsr++ = quote;
  769. }
  770. *zCsr++ = quote;
  771. p->n = (int)(zCsr - p->z);
  772. *zCsr = '\0';
  773. }else{
  774. memcpy(p->z+p->n, zAppend, nAppend);
  775. p->n += nAppend;
  776. p->z[p->n] = '\0';
  777. }
  778. }
  779. /*
  780. ** Attempt to determine if identifier zName needs to be quoted, either
  781. ** because it contains non-alphanumeric characters, or because it is an
  782. ** SQLite keyword. Be conservative in this estimate: When in doubt assume
  783. ** that quoting is required.
  784. **
  785. ** Return '"' if quoting is required. Return 0 if no quoting is required.
  786. */
  787. static char quoteChar(const char *zName){
  788. int i;
  789. if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
  790. for(i=0; zName[i]; i++){
  791. if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
  792. }
  793. return sqlite3_keyword_check(zName, i) ? '"' : 0;
  794. }
  795. /*
  796. ** Construct a fake object name and column list to describe the structure
  797. ** of the view, virtual table, or table valued function zSchema.zName.
  798. */
  799. static char *shellFakeSchema(
  800. sqlite3 *db, /* The database connection containing the vtab */
  801. const char *zSchema, /* Schema of the database holding the vtab */
  802. const char *zName /* The name of the virtual table */
  803. ){
  804. sqlite3_stmt *pStmt = 0;
  805. char *zSql;
  806. ShellText s;
  807. char cQuote;
  808. char *zDiv = "(";
  809. int nRow = 0;
  810. zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
  811. zSchema ? zSchema : "main", zName);
  812. shell_check_oom(zSql);
  813. sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  814. sqlite3_free(zSql);
  815. initText(&s);
  816. if( zSchema ){
  817. cQuote = quoteChar(zSchema);
  818. if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
  819. appendText(&s, zSchema, cQuote);
  820. appendText(&s, ".", 0);
  821. }
  822. cQuote = quoteChar(zName);
  823. appendText(&s, zName, cQuote);
  824. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  825. const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
  826. nRow++;
  827. appendText(&s, zDiv, 0);
  828. zDiv = ",";
  829. if( zCol==0 ) zCol = "";
  830. cQuote = quoteChar(zCol);
  831. appendText(&s, zCol, cQuote);
  832. }
  833. appendText(&s, ")", 0);
  834. sqlite3_finalize(pStmt);
  835. if( nRow==0 ){
  836. freeText(&s);
  837. s.z = 0;
  838. }
  839. return s.z;
  840. }
  841. /*
  842. ** SQL function: shell_module_schema(X)
  843. **
  844. ** Return a fake schema for the table-valued function or eponymous virtual
  845. ** table X.
  846. */
  847. static void shellModuleSchema(
  848. sqlite3_context *pCtx,
  849. int nVal,
  850. sqlite3_value **apVal
  851. ){
  852. const char *zName;
  853. char *zFake;
  854. UNUSED_PARAMETER(nVal);
  855. zName = (const char*)sqlite3_value_text(apVal[0]);
  856. zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
  857. if( zFake ){
  858. sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
  859. -1, sqlite3_free);
  860. free(zFake);
  861. }
  862. }
  863. /*
  864. ** SQL function: shell_add_schema(S,X)
  865. **
  866. ** Add the schema name X to the CREATE statement in S and return the result.
  867. ** Examples:
  868. **
  869. ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
  870. **
  871. ** Also works on
  872. **
  873. ** CREATE INDEX
  874. ** CREATE UNIQUE INDEX
  875. ** CREATE VIEW
  876. ** CREATE TRIGGER
  877. ** CREATE VIRTUAL TABLE
  878. **
  879. ** This UDF is used by the .schema command to insert the schema name of
  880. ** attached databases into the middle of the sqlite_schema.sql field.
  881. */
  882. static void shellAddSchemaName(
  883. sqlite3_context *pCtx,
  884. int nVal,
  885. sqlite3_value **apVal
  886. ){
  887. static const char *aPrefix[] = {
  888. "TABLE",
  889. "INDEX",
  890. "UNIQUE INDEX",
  891. "VIEW",
  892. "TRIGGER",
  893. "VIRTUAL TABLE"
  894. };
  895. int i = 0;
  896. const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
  897. const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
  898. const char *zName = (const char*)sqlite3_value_text(apVal[2]);
  899. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  900. UNUSED_PARAMETER(nVal);
  901. if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
  902. for(i=0; i<ArraySize(aPrefix); i++){
  903. int n = strlen30(aPrefix[i]);
  904. if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
  905. char *z = 0;
  906. char *zFake = 0;
  907. if( zSchema ){
  908. char cQuote = quoteChar(zSchema);
  909. if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
  910. z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
  911. }else{
  912. z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
  913. }
  914. }
  915. if( zName
  916. && aPrefix[i][0]=='V'
  917. && (zFake = shellFakeSchema(db, zSchema, zName))!=0
  918. ){
  919. if( z==0 ){
  920. z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
  921. }else{
  922. z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
  923. }
  924. free(zFake);
  925. }
  926. if( z ){
  927. sqlite3_result_text(pCtx, z, -1, sqlite3_free);
  928. return;
  929. }
  930. }
  931. }
  932. }
  933. sqlite3_result_value(pCtx, apVal[0]);
  934. }
  935. /*
  936. ** The source code for several run-time loadable extensions is inserted
  937. ** below by the ../tool/mkshellc.tcl script. Before processing that included
  938. ** code, we need to override some macros to make the included program code
  939. ** work here in the middle of this regular program.
  940. */
  941. #define SQLITE_EXTENSION_INIT1
  942. #define SQLITE_EXTENSION_INIT2(X) (void)(X)
  943. #if defined(_WIN32) && defined(_MSC_VER)
  944. /************************* Begin test_windirent.h ******************/
  945. /*
  946. ** 2015 November 30
  947. **
  948. ** The author disclaims copyright to this source code. In place of
  949. ** a legal notice, here is a blessing:
  950. **
  951. ** May you do good and not evil.
  952. ** May you find forgiveness for yourself and forgive others.
  953. ** May you share freely, never taking more than you give.
  954. **
  955. *************************************************************************
  956. ** This file contains declarations for most of the opendir() family of
  957. ** POSIX functions on Win32 using the MSVCRT.
  958. */
  959. #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
  960. #define SQLITE_WINDIRENT_H
  961. /*
  962. ** We need several data types from the Windows SDK header.
  963. */
  964. #ifndef WIN32_LEAN_AND_MEAN
  965. #define WIN32_LEAN_AND_MEAN
  966. #endif
  967. #include "windows.h"
  968. /*
  969. ** We need several support functions from the SQLite core.
  970. */
  971. /* #include "sqlite3.h" */
  972. /*
  973. ** We need several things from the ANSI and MSVCRT headers.
  974. */
  975. #include <stdio.h>
  976. #include <stdlib.h>
  977. #include <errno.h>
  978. #include <io.h>
  979. #include <limits.h>
  980. #include <sys/types.h>
  981. #include <sys/stat.h>
  982. /*
  983. ** We may need several defines that should have been in "sys/stat.h".
  984. */
  985. #ifndef S_ISREG
  986. #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
  987. #endif
  988. #ifndef S_ISDIR
  989. #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
  990. #endif
  991. #ifndef S_ISLNK
  992. #define S_ISLNK(mode) (0)
  993. #endif
  994. /*
  995. ** We may need to provide the "mode_t" type.
  996. */
  997. #ifndef MODE_T_DEFINED
  998. #define MODE_T_DEFINED
  999. typedef unsigned short mode_t;
  1000. #endif
  1001. /*
  1002. ** We may need to provide the "ino_t" type.
  1003. */
  1004. #ifndef INO_T_DEFINED
  1005. #define INO_T_DEFINED
  1006. typedef unsigned short ino_t;
  1007. #endif
  1008. /*
  1009. ** We need to define "NAME_MAX" if it was not present in "limits.h".
  1010. */
  1011. #ifndef NAME_MAX
  1012. # ifdef FILENAME_MAX
  1013. # define NAME_MAX (FILENAME_MAX)
  1014. # else
  1015. # define NAME_MAX (260)
  1016. # endif
  1017. #endif
  1018. /*
  1019. ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
  1020. */
  1021. #ifndef NULL_INTPTR_T
  1022. # define NULL_INTPTR_T ((intptr_t)(0))
  1023. #endif
  1024. #ifndef BAD_INTPTR_T
  1025. # define BAD_INTPTR_T ((intptr_t)(-1))
  1026. #endif
  1027. /*
  1028. ** We need to provide the necessary structures and related types.
  1029. */
  1030. #ifndef DIRENT_DEFINED
  1031. #define DIRENT_DEFINED
  1032. typedef struct DIRENT DIRENT;
  1033. typedef DIRENT *LPDIRENT;
  1034. struct DIRENT {
  1035. ino_t d_ino; /* Sequence number, do not use. */
  1036. unsigned d_attributes; /* Win32 file attributes. */
  1037. char d_name[NAME_MAX + 1]; /* Name within the directory. */
  1038. };
  1039. #endif
  1040. #ifndef DIR_DEFINED
  1041. #define DIR_DEFINED
  1042. typedef struct DIR DIR;
  1043. typedef DIR *LPDIR;
  1044. struct DIR {
  1045. intptr_t d_handle; /* Value returned by "_findfirst". */
  1046. DIRENT d_first; /* DIRENT constructed based on "_findfirst". */
  1047. DIRENT d_next; /* DIRENT constructed based on "_findnext". */
  1048. };
  1049. #endif
  1050. /*
  1051. ** Provide a macro, for use by the implementation, to determine if a
  1052. ** particular directory entry should be skipped over when searching for
  1053. ** the next directory entry that should be returned by the readdir() or
  1054. ** readdir_r() functions.
  1055. */
  1056. #ifndef is_filtered
  1057. # define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
  1058. #endif
  1059. /*
  1060. ** Provide the function prototype for the POSIX compatiable getenv()
  1061. ** function. This function is not thread-safe.
  1062. */
  1063. extern const char *windirent_getenv(const char *name);
  1064. /*
  1065. ** Finally, we can provide the function prototypes for the opendir(),
  1066. ** readdir(), readdir_r(), and closedir() POSIX functions.
  1067. */
  1068. extern LPDIR opendir(const char *dirname);
  1069. extern LPDIRENT readdir(LPDIR dirp);
  1070. extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
  1071. extern INT closedir(LPDIR dirp);
  1072. #endif /* defined(WIN32) && defined(_MSC_VER) */
  1073. /************************* End test_windirent.h ********************/
  1074. /************************* Begin test_windirent.c ******************/
  1075. /*
  1076. ** 2015 November 30
  1077. **
  1078. ** The author disclaims copyright to this source code. In place of
  1079. ** a legal notice, here is a blessing:
  1080. **
  1081. ** May you do good and not evil.
  1082. ** May you find forgiveness for yourself and forgive others.
  1083. ** May you share freely, never taking more than you give.
  1084. **
  1085. *************************************************************************
  1086. ** This file contains code to implement most of the opendir() family of
  1087. ** POSIX functions on Win32 using the MSVCRT.
  1088. */
  1089. #if defined(_WIN32) && defined(_MSC_VER)
  1090. /* #include "test_windirent.h" */
  1091. /*
  1092. ** Implementation of the POSIX getenv() function using the Win32 API.
  1093. ** This function is not thread-safe.
  1094. */
  1095. const char *windirent_getenv(
  1096. const char *name
  1097. ){
  1098. static char value[32768]; /* Maximum length, per MSDN */
  1099. DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
  1100. DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
  1101. memset(value, 0, sizeof(value));
  1102. dwRet = GetEnvironmentVariableA(name, value, dwSize);
  1103. if( dwRet==0 || dwRet>dwSize ){
  1104. /*
  1105. ** The function call to GetEnvironmentVariableA() failed -OR-
  1106. ** the buffer is not large enough. Either way, return NULL.
  1107. */
  1108. return 0;
  1109. }else{
  1110. /*
  1111. ** The function call to GetEnvironmentVariableA() succeeded
  1112. ** -AND- the buffer contains the entire value.
  1113. */
  1114. return value;
  1115. }
  1116. }
  1117. /*
  1118. ** Implementation of the POSIX opendir() function using the MSVCRT.
  1119. */
  1120. LPDIR opendir(
  1121. const char *dirname
  1122. ){
  1123. struct _finddata_t data;
  1124. LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
  1125. SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
  1126. if( dirp==NULL ) return NULL;
  1127. memset(dirp, 0, sizeof(DIR));
  1128. /* TODO: Remove this if Unix-style root paths are not used. */
  1129. if( sqlite3_stricmp(dirname, "/")==0 ){
  1130. dirname = windirent_getenv("SystemDrive");
  1131. }
  1132. memset(&data, 0, sizeof(struct _finddata_t));
  1133. _snprintf(data.name, namesize, "%s\\*", dirname);
  1134. dirp->d_handle = _findfirst(data.name, &data);
  1135. if( dirp->d_handle==BAD_INTPTR_T ){
  1136. closedir(dirp);
  1137. return NULL;
  1138. }
  1139. /* TODO: Remove this block to allow hidden and/or system files. */
  1140. if( is_filtered(data) ){
  1141. next:
  1142. memset(&data, 0, sizeof(struct _finddata_t));
  1143. if( _findnext(dirp->d_handle, &data)==-1 ){
  1144. closedir(dirp);
  1145. return NULL;
  1146. }
  1147. /* TODO: Remove this block to allow hidden and/or system files. */
  1148. if( is_filtered(data) ) goto next;
  1149. }
  1150. dirp->d_first.d_attributes = data.attrib;
  1151. strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
  1152. dirp->d_first.d_name[NAME_MAX] = '\0';
  1153. return dirp;
  1154. }
  1155. /*
  1156. ** Implementation of the POSIX readdir() function using the MSVCRT.
  1157. */
  1158. LPDIRENT readdir(
  1159. LPDIR dirp
  1160. ){
  1161. struct _finddata_t data;
  1162. if( dirp==NULL ) return NULL;
  1163. if( dirp->d_first.d_ino==0 ){
  1164. dirp->d_first.d_ino++;
  1165. dirp->d_next.d_ino++;
  1166. return &dirp->d_first;
  1167. }
  1168. next:
  1169. memset(&data, 0, sizeof(struct _finddata_t));
  1170. if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
  1171. /* TODO: Remove this block to allow hidden and/or system files. */
  1172. if( is_filtered(data) ) goto next;
  1173. dirp->d_next.d_ino++;
  1174. dirp->d_next.d_attributes = data.attrib;
  1175. strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
  1176. dirp->d_next.d_name[NAME_MAX] = '\0';
  1177. return &dirp->d_next;
  1178. }
  1179. /*
  1180. ** Implementation of the POSIX readdir_r() function using the MSVCRT.
  1181. */
  1182. INT readdir_r(
  1183. LPDIR dirp,
  1184. LPDIRENT entry,
  1185. LPDIRENT *result
  1186. ){
  1187. struct _finddata_t data;
  1188. if( dirp==NULL ) return EBADF;
  1189. if( dirp->d_first.d_ino==0 ){
  1190. dirp->d_first.d_ino++;
  1191. dirp->d_next.d_ino++;
  1192. entry->d_ino = dirp->d_first.d_ino;
  1193. entry->d_attributes = dirp->d_first.d_attributes;
  1194. strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
  1195. entry->d_name[NAME_MAX] = '\0';
  1196. *result = entry;
  1197. return 0;
  1198. }
  1199. next:
  1200. memset(&data, 0, sizeof(struct _finddata_t));
  1201. if( _findnext(dirp->d_handle, &data)==-1 ){
  1202. *result = NULL;
  1203. return ENOENT;
  1204. }
  1205. /* TODO: Remove this block to allow hidden and/or system files. */
  1206. if( is_filtered(data) ) goto next;
  1207. entry->d_ino = (ino_t)-1; /* not available */
  1208. entry->d_attributes = data.attrib;
  1209. strncpy(entry->d_name, data.name, NAME_MAX);
  1210. entry->d_name[NAME_MAX] = '\0';
  1211. *result = entry;
  1212. return 0;
  1213. }
  1214. /*
  1215. ** Implementation of the POSIX closedir() function using the MSVCRT.
  1216. */
  1217. INT closedir(
  1218. LPDIR dirp
  1219. ){
  1220. INT result = 0;
  1221. if( dirp==NULL ) return EINVAL;
  1222. if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
  1223. result = _findclose(dirp->d_handle);
  1224. }
  1225. sqlite3_free(dirp);
  1226. return result;
  1227. }
  1228. #endif /* defined(WIN32) && defined(_MSC_VER) */
  1229. /************************* End test_windirent.c ********************/
  1230. #define dirent DIRENT
  1231. #endif
  1232. /************************* Begin ../ext/misc/shathree.c ******************/
  1233. /*
  1234. ** 2017-03-08
  1235. **
  1236. ** The author disclaims copyright to this source code. In place of
  1237. ** a legal notice, here is a blessing:
  1238. **
  1239. ** May you do good and not evil.
  1240. ** May you find forgiveness for yourself and forgive others.
  1241. ** May you share freely, never taking more than you give.
  1242. **
  1243. ******************************************************************************
  1244. **
  1245. ** This SQLite extension implements functions that compute SHA3 hashes.
  1246. ** Two SQL functions are implemented:
  1247. **
  1248. ** sha3(X,SIZE)
  1249. ** sha3_query(Y,SIZE)
  1250. **
  1251. ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
  1252. ** X is NULL.
  1253. **
  1254. ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
  1255. ** and returns a hash of their results.
  1256. **
  1257. ** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm
  1258. ** is used. If SIZE is included it must be one of the integers 224, 256,
  1259. ** 384, or 512, to determine SHA3 hash variant that is computed.
  1260. */
  1261. /* #include "sqlite3ext.h" */
  1262. SQLITE_EXTENSION_INIT1
  1263. #include <assert.h>
  1264. #include <string.h>
  1265. #include <stdarg.h>
  1266. #ifndef SQLITE_AMALGAMATION
  1267. /* typedef sqlite3_uint64 u64; */
  1268. #endif /* SQLITE_AMALGAMATION */
  1269. /******************************************************************************
  1270. ** The Hash Engine
  1271. */
  1272. /*
  1273. ** Macros to determine whether the machine is big or little endian,
  1274. ** and whether or not that determination is run-time or compile-time.
  1275. **
  1276. ** For best performance, an attempt is made to guess at the byte-order
  1277. ** using C-preprocessor macros. If that is unsuccessful, or if
  1278. ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
  1279. ** at run-time.
  1280. */
  1281. #ifndef SHA3_BYTEORDER
  1282. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  1283. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  1284. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  1285. defined(__arm__)
  1286. # define SHA3_BYTEORDER 1234
  1287. # elif defined(sparc) || defined(__ppc__)
  1288. # define SHA3_BYTEORDER 4321
  1289. # else
  1290. # define SHA3_BYTEORDER 0
  1291. # endif
  1292. #endif
  1293. /*
  1294. ** State structure for a SHA3 hash in progress
  1295. */
  1296. typedef struct SHA3Context SHA3Context;
  1297. struct SHA3Context {
  1298. union {
  1299. u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
  1300. unsigned char x[1600]; /* ... or 1600 bytes */
  1301. } u;
  1302. unsigned nRate; /* Bytes of input accepted per Keccak iteration */
  1303. unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
  1304. unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
  1305. };
  1306. /*
  1307. ** A single step of the Keccak mixing function for a 1600-bit state
  1308. */
  1309. static void KeccakF1600Step(SHA3Context *p){
  1310. int i;
  1311. u64 b0, b1, b2, b3, b4;
  1312. u64 c0, c1, c2, c3, c4;
  1313. u64 d0, d1, d2, d3, d4;
  1314. static const u64 RC[] = {
  1315. 0x0000000000000001ULL, 0x0000000000008082ULL,
  1316. 0x800000000000808aULL, 0x8000000080008000ULL,
  1317. 0x000000000000808bULL, 0x0000000080000001ULL,
  1318. 0x8000000080008081ULL, 0x8000000000008009ULL,
  1319. 0x000000000000008aULL, 0x0000000000000088ULL,
  1320. 0x0000000080008009ULL, 0x000000008000000aULL,
  1321. 0x000000008000808bULL, 0x800000000000008bULL,
  1322. 0x8000000000008089ULL, 0x8000000000008003ULL,
  1323. 0x8000000000008002ULL, 0x8000000000000080ULL,
  1324. 0x000000000000800aULL, 0x800000008000000aULL,
  1325. 0x8000000080008081ULL, 0x8000000000008080ULL,
  1326. 0x0000000080000001ULL, 0x8000000080008008ULL
  1327. };
  1328. # define a00 (p->u.s[0])
  1329. # define a01 (p->u.s[1])
  1330. # define a02 (p->u.s[2])
  1331. # define a03 (p->u.s[3])
  1332. # define a04 (p->u.s[4])
  1333. # define a10 (p->u.s[5])
  1334. # define a11 (p->u.s[6])
  1335. # define a12 (p->u.s[7])
  1336. # define a13 (p->u.s[8])
  1337. # define a14 (p->u.s[9])
  1338. # define a20 (p->u.s[10])
  1339. # define a21 (p->u.s[11])
  1340. # define a22 (p->u.s[12])
  1341. # define a23 (p->u.s[13])
  1342. # define a24 (p->u.s[14])
  1343. # define a30 (p->u.s[15])
  1344. # define a31 (p->u.s[16])
  1345. # define a32 (p->u.s[17])
  1346. # define a33 (p->u.s[18])
  1347. # define a34 (p->u.s[19])
  1348. # define a40 (p->u.s[20])
  1349. # define a41 (p->u.s[21])
  1350. # define a42 (p->u.s[22])
  1351. # define a43 (p->u.s[23])
  1352. # define a44 (p->u.s[24])
  1353. # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
  1354. for(i=0; i<24; i+=4){
  1355. c0 = a00^a10^a20^a30^a40;
  1356. c1 = a01^a11^a21^a31^a41;
  1357. c2 = a02^a12^a22^a32^a42;
  1358. c3 = a03^a13^a23^a33^a43;
  1359. c4 = a04^a14^a24^a34^a44;
  1360. d0 = c4^ROL64(c1, 1);
  1361. d1 = c0^ROL64(c2, 1);
  1362. d2 = c1^ROL64(c3, 1);
  1363. d3 = c2^ROL64(c4, 1);
  1364. d4 = c3^ROL64(c0, 1);
  1365. b0 = (a00^d0);
  1366. b1 = ROL64((a11^d1), 44);
  1367. b2 = ROL64((a22^d2), 43);
  1368. b3 = ROL64((a33^d3), 21);
  1369. b4 = ROL64((a44^d4), 14);
  1370. a00 = b0 ^((~b1)& b2 );
  1371. a00 ^= RC[i];
  1372. a11 = b1 ^((~b2)& b3 );
  1373. a22 = b2 ^((~b3)& b4 );
  1374. a33 = b3 ^((~b4)& b0 );
  1375. a44 = b4 ^((~b0)& b1 );
  1376. b2 = ROL64((a20^d0), 3);
  1377. b3 = ROL64((a31^d1), 45);
  1378. b4 = ROL64((a42^d2), 61);
  1379. b0 = ROL64((a03^d3), 28);
  1380. b1 = ROL64((a14^d4), 20);
  1381. a20 = b0 ^((~b1)& b2 );
  1382. a31 = b1 ^((~b2)& b3 );
  1383. a42 = b2 ^((~b3)& b4 );
  1384. a03 = b3 ^((~b4)& b0 );
  1385. a14 = b4 ^((~b0)& b1 );
  1386. b4 = ROL64((a40^d0), 18);
  1387. b0 = ROL64((a01^d1), 1);
  1388. b1 = ROL64((a12^d2), 6);
  1389. b2 = ROL64((a23^d3), 25);
  1390. b3 = ROL64((a34^d4), 8);
  1391. a40 = b0 ^((~b1)& b2 );
  1392. a01 = b1 ^((~b2)& b3 );
  1393. a12 = b2 ^((~b3)& b4 );
  1394. a23 = b3 ^((~b4)& b0 );
  1395. a34 = b4 ^((~b0)& b1 );
  1396. b1 = ROL64((a10^d0), 36);
  1397. b2 = ROL64((a21^d1), 10);
  1398. b3 = ROL64((a32^d2), 15);
  1399. b4 = ROL64((a43^d3), 56);
  1400. b0 = ROL64((a04^d4), 27);
  1401. a10 = b0 ^((~b1)& b2 );
  1402. a21 = b1 ^((~b2)& b3 );
  1403. a32 = b2 ^((~b3)& b4 );
  1404. a43 = b3 ^((~b4)& b0 );
  1405. a04 = b4 ^((~b0)& b1 );
  1406. b3 = ROL64((a30^d0), 41);
  1407. b4 = ROL64((a41^d1), 2);
  1408. b0 = ROL64((a02^d2), 62);
  1409. b1 = ROL64((a13^d3), 55);
  1410. b2 = ROL64((a24^d4), 39);
  1411. a30 = b0 ^((~b1)& b2 );
  1412. a41 = b1 ^((~b2)& b3 );
  1413. a02 = b2 ^((~b3)& b4 );
  1414. a13 = b3 ^((~b4)& b0 );
  1415. a24 = b4 ^((~b0)& b1 );
  1416. c0 = a00^a20^a40^a10^a30;
  1417. c1 = a11^a31^a01^a21^a41;
  1418. c2 = a22^a42^a12^a32^a02;
  1419. c3 = a33^a03^a23^a43^a13;
  1420. c4 = a44^a14^a34^a04^a24;
  1421. d0 = c4^ROL64(c1, 1);
  1422. d1 = c0^ROL64(c2, 1);
  1423. d2 = c1^ROL64(c3, 1);
  1424. d3 = c2^ROL64(c4, 1);
  1425. d4 = c3^ROL64(c0, 1);
  1426. b0 = (a00^d0);
  1427. b1 = ROL64((a31^d1), 44);
  1428. b2 = ROL64((a12^d2), 43);
  1429. b3 = ROL64((a43^d3), 21);
  1430. b4 = ROL64((a24^d4), 14);
  1431. a00 = b0 ^((~b1)& b2 );
  1432. a00 ^= RC[i+1];
  1433. a31 = b1 ^((~b2)& b3 );
  1434. a12 = b2 ^((~b3)& b4 );
  1435. a43 = b3 ^((~b4)& b0 );
  1436. a24 = b4 ^((~b0)& b1 );
  1437. b2 = ROL64((a40^d0), 3);
  1438. b3 = ROL64((a21^d1), 45);
  1439. b4 = ROL64((a02^d2), 61);
  1440. b0 = ROL64((a33^d3), 28);
  1441. b1 = ROL64((a14^d4), 20);
  1442. a40 = b0 ^((~b1)& b2 );
  1443. a21 = b1 ^((~b2)& b3 );
  1444. a02 = b2 ^((~b3)& b4 );
  1445. a33 = b3 ^((~b4)& b0 );
  1446. a14 = b4 ^((~b0)& b1 );
  1447. b4 = ROL64((a30^d0), 18);
  1448. b0 = ROL64((a11^d1), 1);
  1449. b1 = ROL64((a42^d2), 6);
  1450. b2 = ROL64((a23^d3), 25);
  1451. b3 = ROL64((a04^d4), 8);
  1452. a30 = b0 ^((~b1)& b2 );
  1453. a11 = b1 ^((~b2)& b3 );
  1454. a42 = b2 ^((~b3)& b4 );
  1455. a23 = b3 ^((~b4)& b0 );
  1456. a04 = b4 ^((~b0)& b1 );
  1457. b1 = ROL64((a20^d0), 36);
  1458. b2 = ROL64((a01^d1), 10);
  1459. b3 = ROL64((a32^d2), 15);
  1460. b4 = ROL64((a13^d3), 56);
  1461. b0 = ROL64((a44^d4), 27);
  1462. a20 = b0 ^((~b1)& b2 );
  1463. a01 = b1 ^((~b2)& b3 );
  1464. a32 = b2 ^((~b3)& b4 );
  1465. a13 = b3 ^((~b4)& b0 );
  1466. a44 = b4 ^((~b0)& b1 );
  1467. b3 = ROL64((a10^d0), 41);
  1468. b4 = ROL64((a41^d1), 2);
  1469. b0 = ROL64((a22^d2), 62);
  1470. b1 = ROL64((a03^d3), 55);
  1471. b2 = ROL64((a34^d4), 39);
  1472. a10 = b0 ^((~b1)& b2 );
  1473. a41 = b1 ^((~b2)& b3 );
  1474. a22 = b2 ^((~b3)& b4 );
  1475. a03 = b3 ^((~b4)& b0 );
  1476. a34 = b4 ^((~b0)& b1 );
  1477. c0 = a00^a40^a30^a20^a10;
  1478. c1 = a31^a21^a11^a01^a41;
  1479. c2 = a12^a02^a42^a32^a22;
  1480. c3 = a43^a33^a23^a13^a03;
  1481. c4 = a24^a14^a04^a44^a34;
  1482. d0 = c4^ROL64(c1, 1);
  1483. d1 = c0^ROL64(c2, 1);
  1484. d2 = c1^ROL64(c3, 1);
  1485. d3 = c2^ROL64(c4, 1);
  1486. d4 = c3^ROL64(c0, 1);
  1487. b0 = (a00^d0);
  1488. b1 = ROL64((a21^d1), 44);
  1489. b2 = ROL64((a42^d2), 43);
  1490. b3 = ROL64((a13^d3), 21);
  1491. b4 = ROL64((a34^d4), 14);
  1492. a00 = b0 ^((~b1)& b2 );
  1493. a00 ^= RC[i+2];
  1494. a21 = b1 ^((~b2)& b3 );
  1495. a42 = b2 ^((~b3)& b4 );
  1496. a13 = b3 ^((~b4)& b0 );
  1497. a34 = b4 ^((~b0)& b1 );
  1498. b2 = ROL64((a30^d0), 3);
  1499. b3 = ROL64((a01^d1), 45);
  1500. b4 = ROL64((a22^d2), 61);
  1501. b0 = ROL64((a43^d3), 28);
  1502. b1 = ROL64((a14^d4), 20);
  1503. a30 = b0 ^((~b1)& b2 );
  1504. a01 = b1 ^((~b2)& b3 );
  1505. a22 = b2 ^((~b3)& b4 );
  1506. a43 = b3 ^((~b4)& b0 );
  1507. a14 = b4 ^((~b0)& b1 );
  1508. b4 = ROL64((a10^d0), 18);
  1509. b0 = ROL64((a31^d1), 1);
  1510. b1 = ROL64((a02^d2), 6);
  1511. b2 = ROL64((a23^d3), 25);
  1512. b3 = ROL64((a44^d4), 8);
  1513. a10 = b0 ^((~b1)& b2 );
  1514. a31 = b1 ^((~b2)& b3 );
  1515. a02 = b2 ^((~b3)& b4 );
  1516. a23 = b3 ^((~b4)& b0 );
  1517. a44 = b4 ^((~b0)& b1 );
  1518. b1 = ROL64((a40^d0), 36);
  1519. b2 = ROL64((a11^d1), 10);
  1520. b3 = ROL64((a32^d2), 15);
  1521. b4 = ROL64((a03^d3), 56);
  1522. b0 = ROL64((a24^d4), 27);
  1523. a40 = b0 ^((~b1)& b2 );
  1524. a11 = b1 ^((~b2)& b3 );
  1525. a32 = b2 ^((~b3)& b4 );
  1526. a03 = b3 ^((~b4)& b0 );
  1527. a24 = b4 ^((~b0)& b1 );
  1528. b3 = ROL64((a20^d0), 41);
  1529. b4 = ROL64((a41^d1), 2);
  1530. b0 = ROL64((a12^d2), 62);
  1531. b1 = ROL64((a33^d3), 55);
  1532. b2 = ROL64((a04^d4), 39);
  1533. a20 = b0 ^((~b1)& b2 );
  1534. a41 = b1 ^((~b2)& b3 );
  1535. a12 = b2 ^((~b3)& b4 );
  1536. a33 = b3 ^((~b4)& b0 );
  1537. a04 = b4 ^((~b0)& b1 );
  1538. c0 = a00^a30^a10^a40^a20;
  1539. c1 = a21^a01^a31^a11^a41;
  1540. c2 = a42^a22^a02^a32^a12;
  1541. c3 = a13^a43^a23^a03^a33;
  1542. c4 = a34^a14^a44^a24^a04;
  1543. d0 = c4^ROL64(c1, 1);
  1544. d1 = c0^ROL64(c2, 1);
  1545. d2 = c1^ROL64(c3, 1);
  1546. d3 = c2^ROL64(c4, 1);
  1547. d4 = c3^ROL64(c0, 1);
  1548. b0 = (a00^d0);
  1549. b1 = ROL64((a01^d1), 44);
  1550. b2 = ROL64((a02^d2), 43);
  1551. b3 = ROL64((a03^d3), 21);
  1552. b4 = ROL64((a04^d4), 14);
  1553. a00 = b0 ^((~b1)& b2 );
  1554. a00 ^= RC[i+3];
  1555. a01 = b1 ^((~b2)& b3 );
  1556. a02 = b2 ^((~b3)& b4 );
  1557. a03 = b3 ^((~b4)& b0 );
  1558. a04 = b4 ^((~b0)& b1 );
  1559. b2 = ROL64((a10^d0), 3);
  1560. b3 = ROL64((a11^d1), 45);
  1561. b4 = ROL64((a12^d2), 61);
  1562. b0 = ROL64((a13^d3), 28);
  1563. b1 = ROL64((a14^d4), 20);
  1564. a10 = b0 ^((~b1)& b2 );
  1565. a11 = b1 ^((~b2)& b3 );
  1566. a12 = b2 ^((~b3)& b4 );
  1567. a13 = b3 ^((~b4)& b0 );
  1568. a14 = b4 ^((~b0)& b1 );
  1569. b4 = ROL64((a20^d0), 18);
  1570. b0 = ROL64((a21^d1), 1);
  1571. b1 = ROL64((a22^d2), 6);
  1572. b2 = ROL64((a23^d3), 25);
  1573. b3 = ROL64((a24^d4), 8);
  1574. a20 = b0 ^((~b1)& b2 );
  1575. a21 = b1 ^((~b2)& b3 );
  1576. a22 = b2 ^((~b3)& b4 );
  1577. a23 = b3 ^((~b4)& b0 );
  1578. a24 = b4 ^((~b0)& b1 );
  1579. b1 = ROL64((a30^d0), 36);
  1580. b2 = ROL64((a31^d1), 10);
  1581. b3 = ROL64((a32^d2), 15);
  1582. b4 = ROL64((a33^d3), 56);
  1583. b0 = ROL64((a34^d4), 27);
  1584. a30 = b0 ^((~b1)& b2 );
  1585. a31 = b1 ^((~b2)& b3 );
  1586. a32 = b2 ^((~b3)& b4 );
  1587. a33 = b3 ^((~b4)& b0 );
  1588. a34 = b4 ^((~b0)& b1 );
  1589. b3 = ROL64((a40^d0), 41);
  1590. b4 = ROL64((a41^d1), 2);
  1591. b0 = ROL64((a42^d2), 62);
  1592. b1 = ROL64((a43^d3), 55);
  1593. b2 = ROL64((a44^d4), 39);
  1594. a40 = b0 ^((~b1)& b2 );
  1595. a41 = b1 ^((~b2)& b3 );
  1596. a42 = b2 ^((~b3)& b4 );
  1597. a43 = b3 ^((~b4)& b0 );
  1598. a44 = b4 ^((~b0)& b1 );
  1599. }
  1600. }
  1601. /*
  1602. ** Initialize a new hash. iSize determines the size of the hash
  1603. ** in bits and should be one of 224, 256, 384, or 512. Or iSize
  1604. ** can be zero to use the default hash size of 256 bits.
  1605. */
  1606. static void SHA3Init(SHA3Context *p, int iSize){
  1607. memset(p, 0, sizeof(*p));
  1608. if( iSize>=128 && iSize<=512 ){
  1609. p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
  1610. }else{
  1611. p->nRate = (1600 - 2*256)/8;
  1612. }
  1613. #if SHA3_BYTEORDER==1234
  1614. /* Known to be little-endian at compile-time. No-op */
  1615. #elif SHA3_BYTEORDER==4321
  1616. p->ixMask = 7; /* Big-endian */
  1617. #else
  1618. {
  1619. static unsigned int one = 1;
  1620. if( 1==*(unsigned char*)&one ){
  1621. /* Little endian. No byte swapping. */
  1622. p->ixMask = 0;
  1623. }else{
  1624. /* Big endian. Byte swap. */
  1625. p->ixMask = 7;
  1626. }
  1627. }
  1628. #endif
  1629. }
  1630. /*
  1631. ** Make consecutive calls to the SHA3Update function to add new content
  1632. ** to the hash
  1633. */
  1634. static void SHA3Update(
  1635. SHA3Context *p,
  1636. const unsigned char *aData,
  1637. unsigned int nData
  1638. ){
  1639. unsigned int i = 0;
  1640. if( aData==0 ) return;
  1641. #if SHA3_BYTEORDER==1234
  1642. if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
  1643. for(; i+7<nData; i+=8){
  1644. p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
  1645. p->nLoaded += 8;
  1646. if( p->nLoaded>=p->nRate ){
  1647. KeccakF1600Step(p);
  1648. p->nLoaded = 0;
  1649. }
  1650. }
  1651. }
  1652. #endif
  1653. for(; i<nData; i++){
  1654. #if SHA3_BYTEORDER==1234
  1655. p->u.x[p->nLoaded] ^= aData[i];
  1656. #elif SHA3_BYTEORDER==4321
  1657. p->u.x[p->nLoaded^0x07] ^= aData[i];
  1658. #else
  1659. p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
  1660. #endif
  1661. p->nLoaded++;
  1662. if( p->nLoaded==p->nRate ){
  1663. KeccakF1600Step(p);
  1664. p->nLoaded = 0;
  1665. }
  1666. }
  1667. }
  1668. /*
  1669. ** After all content has been added, invoke SHA3Final() to compute
  1670. ** the final hash. The function returns a pointer to the binary
  1671. ** hash value.
  1672. */
  1673. static unsigned char *SHA3Final(SHA3Context *p){
  1674. unsigned int i;
  1675. if( p->nLoaded==p->nRate-1 ){
  1676. const unsigned char c1 = 0x86;
  1677. SHA3Update(p, &c1, 1);
  1678. }else{
  1679. const unsigned char c2 = 0x06;
  1680. const unsigned char c3 = 0x80;
  1681. SHA3Update(p, &c2, 1);
  1682. p->nLoaded = p->nRate - 1;
  1683. SHA3Update(p, &c3, 1);
  1684. }
  1685. for(i=0; i<p->nRate; i++){
  1686. p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
  1687. }
  1688. return &p->u.x[p->nRate];
  1689. }
  1690. /* End of the hashing logic
  1691. *****************************************************************************/
  1692. /*
  1693. ** Implementation of the sha3(X,SIZE) function.
  1694. **
  1695. ** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
  1696. ** size is 256. If X is a BLOB, it is hashed as is.
  1697. ** For all other non-NULL types of input, X is converted into a UTF-8 string
  1698. ** and the string is hashed without the trailing 0x00 terminator. The hash
  1699. ** of a NULL value is NULL.
  1700. */
  1701. static void sha3Func(
  1702. sqlite3_context *context,
  1703. int argc,
  1704. sqlite3_value **argv
  1705. ){
  1706. SHA3Context cx;
  1707. int eType = sqlite3_value_type(argv[0]);
  1708. int nByte = sqlite3_value_bytes(argv[0]);
  1709. int iSize;
  1710. if( argc==1 ){
  1711. iSize = 256;
  1712. }else{
  1713. iSize = sqlite3_value_int(argv[1]);
  1714. if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
  1715. sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
  1716. "384 512", -1);
  1717. return;
  1718. }
  1719. }
  1720. if( eType==SQLITE_NULL ) return;
  1721. SHA3Init(&cx, iSize);
  1722. if( eType==SQLITE_BLOB ){
  1723. SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
  1724. }else{
  1725. SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
  1726. }
  1727. sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
  1728. }
  1729. /* Compute a string using sqlite3_vsnprintf() with a maximum length
  1730. ** of 50 bytes and add it to the hash.
  1731. */
  1732. static void hash_step_vformat(
  1733. SHA3Context *p, /* Add content to this context */
  1734. const char *zFormat,
  1735. ...
  1736. ){
  1737. va_list ap;
  1738. int n;
  1739. char zBuf[50];
  1740. va_start(ap, zFormat);
  1741. sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
  1742. va_end(ap);
  1743. n = (int)strlen(zBuf);
  1744. SHA3Update(p, (unsigned char*)zBuf, n);
  1745. }
  1746. /*
  1747. ** Implementation of the sha3_query(SQL,SIZE) function.
  1748. **
  1749. ** This function compiles and runs the SQL statement(s) given in the
  1750. ** argument. The results are hashed using a SIZE-bit SHA3. The default
  1751. ** size is 256.
  1752. **
  1753. ** The format of the byte stream that is hashed is summarized as follows:
  1754. **
  1755. ** S<n>:<sql>
  1756. ** R
  1757. ** N
  1758. ** I<int>
  1759. ** F<ieee-float>
  1760. ** B<size>:<bytes>
  1761. ** T<size>:<text>
  1762. **
  1763. ** <sql> is the original SQL text for each statement run and <n> is
  1764. ** the size of that text. The SQL text is UTF-8. A single R character
  1765. ** occurs before the start of each row. N means a NULL value.
  1766. ** I mean an 8-byte little-endian integer <int>. F is a floating point
  1767. ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
  1768. ** B means blobs of <size> bytes. T means text rendered as <size>
  1769. ** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
  1770. ** text integers.
  1771. **
  1772. ** For each SQL statement in the X input, there is one S segment. Each
  1773. ** S segment is followed by zero or more R segments, one for each row in the
  1774. ** result set. After each R, there are one or more N, I, F, B, or T segments,
  1775. ** one for each column in the result set. Segments are concatentated directly
  1776. ** with no delimiters of any kind.
  1777. */
  1778. static void sha3QueryFunc(
  1779. sqlite3_context *context,
  1780. int argc,
  1781. sqlite3_value **argv
  1782. ){
  1783. sqlite3 *db = sqlite3_context_db_handle(context);
  1784. const char *zSql = (const char*)sqlite3_value_text(argv[0]);
  1785. sqlite3_stmt *pStmt = 0;
  1786. int nCol; /* Number of columns in the result set */
  1787. int i; /* Loop counter */
  1788. int rc;
  1789. int n;
  1790. const char *z;
  1791. SHA3Context cx;
  1792. int iSize;
  1793. if( argc==1 ){
  1794. iSize = 256;
  1795. }else{
  1796. iSize = sqlite3_value_int(argv[1]);
  1797. if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
  1798. sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
  1799. "384 512", -1);
  1800. return;
  1801. }
  1802. }
  1803. if( zSql==0 ) return;
  1804. SHA3Init(&cx, iSize);
  1805. while( zSql[0] ){
  1806. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
  1807. if( rc ){
  1808. char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
  1809. zSql, sqlite3_errmsg(db));
  1810. sqlite3_finalize(pStmt);
  1811. sqlite3_result_error(context, zMsg, -1);
  1812. sqlite3_free(zMsg);
  1813. return;
  1814. }
  1815. if( !sqlite3_stmt_readonly(pStmt) ){
  1816. char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
  1817. sqlite3_finalize(pStmt);
  1818. sqlite3_result_error(context, zMsg, -1);
  1819. sqlite3_free(zMsg);
  1820. return;
  1821. }
  1822. nCol = sqlite3_column_count(pStmt);
  1823. z = sqlite3_sql(pStmt);
  1824. if( z ){
  1825. n = (int)strlen(z);
  1826. hash_step_vformat(&cx,"S%d:",n);
  1827. SHA3Update(&cx,(unsigned char*)z,n);
  1828. }
  1829. /* Compute a hash over the result of the query */
  1830. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  1831. SHA3Update(&cx,(const unsigned char*)"R",1);
  1832. for(i=0; i<nCol; i++){
  1833. switch( sqlite3_column_type(pStmt,i) ){
  1834. case SQLITE_NULL: {
  1835. SHA3Update(&cx, (const unsigned char*)"N",1);
  1836. break;
  1837. }
  1838. case SQLITE_INTEGER: {
  1839. sqlite3_uint64 u;
  1840. int j;
  1841. unsigned char x[9];
  1842. sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
  1843. memcpy(&u, &v, 8);
  1844. for(j=8; j>=1; j--){
  1845. x[j] = u & 0xff;
  1846. u >>= 8;
  1847. }
  1848. x[0] = 'I';
  1849. SHA3Update(&cx, x, 9);
  1850. break;
  1851. }
  1852. case SQLITE_FLOAT: {
  1853. sqlite3_uint64 u;
  1854. int j;
  1855. unsigned char x[9];
  1856. double r = sqlite3_column_double(pStmt,i);
  1857. memcpy(&u, &r, 8);
  1858. for(j=8; j>=1; j--){
  1859. x[j] = u & 0xff;
  1860. u >>= 8;
  1861. }
  1862. x[0] = 'F';
  1863. SHA3Update(&cx,x,9);
  1864. break;
  1865. }
  1866. case SQLITE_TEXT: {
  1867. int n2 = sqlite3_column_bytes(pStmt, i);
  1868. const unsigned char *z2 = sqlite3_column_text(pStmt, i);
  1869. hash_step_vformat(&cx,"T%d:",n2);
  1870. SHA3Update(&cx, z2, n2);
  1871. break;
  1872. }
  1873. case SQLITE_BLOB: {
  1874. int n2 = sqlite3_column_bytes(pStmt, i);
  1875. const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
  1876. hash_step_vformat(&cx,"B%d:",n2);
  1877. SHA3Update(&cx, z2, n2);
  1878. break;
  1879. }
  1880. }
  1881. }
  1882. }
  1883. sqlite3_finalize(pStmt);
  1884. }
  1885. sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
  1886. }
  1887. #ifdef _WIN32
  1888. #endif
  1889. int sqlite3_shathree_init(
  1890. sqlite3 *db,
  1891. char **pzErrMsg,
  1892. const sqlite3_api_routines *pApi
  1893. ){
  1894. int rc = SQLITE_OK;
  1895. SQLITE_EXTENSION_INIT2(pApi);
  1896. (void)pzErrMsg; /* Unused parameter */
  1897. rc = sqlite3_create_function(db, "sha3", 1,
  1898. SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
  1899. 0, sha3Func, 0, 0);
  1900. if( rc==SQLITE_OK ){
  1901. rc = sqlite3_create_function(db, "sha3", 2,
  1902. SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
  1903. 0, sha3Func, 0, 0);
  1904. }
  1905. if( rc==SQLITE_OK ){
  1906. rc = sqlite3_create_function(db, "sha3_query", 1,
  1907. SQLITE_UTF8 | SQLITE_DIRECTONLY,
  1908. 0, sha3QueryFunc, 0, 0);
  1909. }
  1910. if( rc==SQLITE_OK ){
  1911. rc = sqlite3_create_function(db, "sha3_query", 2,
  1912. SQLITE_UTF8 | SQLITE_DIRECTONLY,
  1913. 0, sha3QueryFunc, 0, 0);
  1914. }
  1915. return rc;
  1916. }
  1917. /************************* End ../ext/misc/shathree.c ********************/
  1918. /************************* Begin ../ext/misc/fileio.c ******************/
  1919. /*
  1920. ** 2014-06-13
  1921. **
  1922. ** The author disclaims copyright to this source code. In place of
  1923. ** a legal notice, here is a blessing:
  1924. **
  1925. ** May you do good and not evil.
  1926. ** May you find forgiveness for yourself and forgive others.
  1927. ** May you share freely, never taking more than you give.
  1928. **
  1929. ******************************************************************************
  1930. **
  1931. ** This SQLite extension implements SQL functions readfile() and
  1932. ** writefile(), and eponymous virtual type "fsdir".
  1933. **
  1934. ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
  1935. **
  1936. ** If neither of the optional arguments is present, then this UDF
  1937. ** function writes blob DATA to file FILE. If successful, the number
  1938. ** of bytes written is returned. If an error occurs, NULL is returned.
  1939. **
  1940. ** If the first option argument - MODE - is present, then it must
  1941. ** be passed an integer value that corresponds to a POSIX mode
  1942. ** value (file type + permissions, as returned in the stat.st_mode
  1943. ** field by the stat() system call). Three types of files may
  1944. ** be written/created:
  1945. **
  1946. ** regular files: (mode & 0170000)==0100000
  1947. ** symbolic links: (mode & 0170000)==0120000
  1948. ** directories: (mode & 0170000)==0040000
  1949. **
  1950. ** For a directory, the DATA is ignored. For a symbolic link, it is
  1951. ** interpreted as text and used as the target of the link. For a
  1952. ** regular file, it is interpreted as a blob and written into the
  1953. ** named file. Regardless of the type of file, its permissions are
  1954. ** set to (mode & 0777) before returning.
  1955. **
  1956. ** If the optional MTIME argument is present, then it is interpreted
  1957. ** as an integer - the number of seconds since the unix epoch. The
  1958. ** modification-time of the target file is set to this value before
  1959. ** returning.
  1960. **
  1961. ** If three or more arguments are passed to this function and an
  1962. ** error is encountered, an exception is raised.
  1963. **
  1964. ** READFILE(FILE):
  1965. **
  1966. ** Read and return the contents of file FILE (type blob) from disk.
  1967. **
  1968. ** FSDIR:
  1969. **
  1970. ** Used as follows:
  1971. **
  1972. ** SELECT * FROM fsdir($path [, $dir]);
  1973. **
  1974. ** Parameter $path is an absolute or relative pathname. If the file that it
  1975. ** refers to does not exist, it is an error. If the path refers to a regular
  1976. ** file or symbolic link, it returns a single row. Or, if the path refers
  1977. ** to a directory, it returns one row for the directory, and one row for each
  1978. ** file within the hierarchy rooted at $path.
  1979. **
  1980. ** Each row has the following columns:
  1981. **
  1982. ** name: Path to file or directory (text value).
  1983. ** mode: Value of stat.st_mode for directory entry (an integer).
  1984. ** mtime: Value of stat.st_mtime for directory entry (an integer).
  1985. ** data: For a regular file, a blob containing the file data. For a
  1986. ** symlink, a text value containing the text of the link. For a
  1987. ** directory, NULL.
  1988. **
  1989. ** If a non-NULL value is specified for the optional $dir parameter and
  1990. ** $path is a relative path, then $path is interpreted relative to $dir.
  1991. ** And the paths returned in the "name" column of the table are also
  1992. ** relative to directory $dir.
  1993. **
  1994. ** Notes on building this extension for Windows:
  1995. ** Unless linked statically with the SQLite library, a preprocessor
  1996. ** symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
  1997. ** DLL form of this extension for WIN32. See its use below for details.
  1998. */
  1999. /* #include "sqlite3ext.h" */
  2000. SQLITE_EXTENSION_INIT1
  2001. #include <stdio.h>
  2002. #include <string.h>
  2003. #include <assert.h>
  2004. #include <sys/types.h>
  2005. #include <sys/stat.h>
  2006. #include <fcntl.h>
  2007. #if !defined(_WIN32) && !defined(WIN32)
  2008. # include <unistd.h>
  2009. # include <dirent.h>
  2010. # include <utime.h>
  2011. # include <sys/time.h>
  2012. #else
  2013. # include "windows.h"
  2014. # include <io.h>
  2015. # include <direct.h>
  2016. /* # include "test_windirent.h" */
  2017. # define dirent DIRENT
  2018. # ifndef chmod
  2019. # define chmod _chmod
  2020. # endif
  2021. # ifndef stat
  2022. # define stat _stat
  2023. # endif
  2024. # define mkdir(path,mode) _mkdir(path)
  2025. # define lstat(path,buf) stat(path,buf)
  2026. #endif
  2027. #include <time.h>
  2028. #include <errno.h>
  2029. /*
  2030. ** Structure of the fsdir() table-valued function
  2031. */
  2032. /* 0 1 2 3 4 5 */
  2033. #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
  2034. #define FSDIR_COLUMN_NAME 0 /* Name of the file */
  2035. #define FSDIR_COLUMN_MODE 1 /* Access mode */
  2036. #define FSDIR_COLUMN_MTIME 2 /* Last modification time */
  2037. #define FSDIR_COLUMN_DATA 3 /* File content */
  2038. #define FSDIR_COLUMN_PATH 4 /* Path to top of search */
  2039. #define FSDIR_COLUMN_DIR 5 /* Path is relative to this directory */
  2040. /*
  2041. ** Set the result stored by context ctx to a blob containing the
  2042. ** contents of file zName. Or, leave the result unchanged (NULL)
  2043. ** if the file does not exist or is unreadable.
  2044. **
  2045. ** If the file exceeds the SQLite blob size limit, through an
  2046. ** SQLITE_TOOBIG error.
  2047. **
  2048. ** Throw an SQLITE_IOERR if there are difficulties pulling the file
  2049. ** off of disk.
  2050. */
  2051. static void readFileContents(sqlite3_context *ctx, const char *zName){
  2052. FILE *in;
  2053. sqlite3_int64 nIn;
  2054. void *pBuf;
  2055. sqlite3 *db;
  2056. int mxBlob;
  2057. in = fopen(zName, "rb");
  2058. if( in==0 ){
  2059. /* File does not exist or is unreadable. Leave the result set to NULL. */
  2060. return;
  2061. }
  2062. fseek(in, 0, SEEK_END);
  2063. nIn = ftell(in);
  2064. rewind(in);
  2065. db = sqlite3_context_db_handle(ctx);
  2066. mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
  2067. if( nIn>mxBlob ){
  2068. sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
  2069. fclose(in);
  2070. return;
  2071. }
  2072. pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
  2073. if( pBuf==0 ){
  2074. sqlite3_result_error_nomem(ctx);
  2075. fclose(in);
  2076. return;
  2077. }
  2078. if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
  2079. sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
  2080. }else{
  2081. sqlite3_result_error_code(ctx, SQLITE_IOERR);
  2082. sqlite3_free(pBuf);
  2083. }
  2084. fclose(in);
  2085. }
  2086. /*
  2087. ** Implementation of the "readfile(X)" SQL function. The entire content
  2088. ** of the file named X is read and returned as a BLOB. NULL is returned
  2089. ** if the file does not exist or is unreadable.
  2090. */
  2091. static void readfileFunc(
  2092. sqlite3_context *context,
  2093. int argc,
  2094. sqlite3_value **argv
  2095. ){
  2096. const char *zName;
  2097. (void)(argc); /* Unused parameter */
  2098. zName = (const char*)sqlite3_value_text(argv[0]);
  2099. if( zName==0 ) return;
  2100. readFileContents(context, zName);
  2101. }
  2102. /*
  2103. ** Set the error message contained in context ctx to the results of
  2104. ** vprintf(zFmt, ...).
  2105. */
  2106. static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
  2107. char *zMsg = 0;
  2108. va_list ap;
  2109. va_start(ap, zFmt);
  2110. zMsg = sqlite3_vmprintf(zFmt, ap);
  2111. sqlite3_result_error(ctx, zMsg, -1);
  2112. sqlite3_free(zMsg);
  2113. va_end(ap);
  2114. }
  2115. #if defined(_WIN32)
  2116. /*
  2117. ** This function is designed to convert a Win32 FILETIME structure into the
  2118. ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
  2119. */
  2120. static sqlite3_uint64 fileTimeToUnixTime(
  2121. LPFILETIME pFileTime
  2122. ){
  2123. SYSTEMTIME epochSystemTime;
  2124. ULARGE_INTEGER epochIntervals;
  2125. FILETIME epochFileTime;
  2126. ULARGE_INTEGER fileIntervals;
  2127. memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
  2128. epochSystemTime.wYear = 1970;
  2129. epochSystemTime.wMonth = 1;
  2130. epochSystemTime.wDay = 1;
  2131. SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
  2132. epochIntervals.LowPart = epochFileTime.dwLowDateTime;
  2133. epochIntervals.HighPart = epochFileTime.dwHighDateTime;
  2134. fileIntervals.LowPart = pFileTime->dwLowDateTime;
  2135. fileIntervals.HighPart = pFileTime->dwHighDateTime;
  2136. return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
  2137. }
  2138. #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
  2139. # /* To allow a standalone DLL, use this next replacement function: */
  2140. # undef sqlite3_win32_utf8_to_unicode
  2141. # define sqlite3_win32_utf8_to_unicode utf8_to_utf16
  2142. #
  2143. LPWSTR utf8_to_utf16(const char *z){
  2144. int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0);
  2145. LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR));
  2146. if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) )
  2147. return rv;
  2148. sqlite3_free(rv);
  2149. return 0;
  2150. }
  2151. #endif
  2152. /*
  2153. ** This function attempts to normalize the time values found in the stat()
  2154. ** buffer to UTC. This is necessary on Win32, where the runtime library
  2155. ** appears to return these values as local times.
  2156. */
  2157. static void statTimesToUtc(
  2158. const char *zPath,
  2159. struct stat *pStatBuf
  2160. ){
  2161. HANDLE hFindFile;
  2162. WIN32_FIND_DATAW fd;
  2163. LPWSTR zUnicodeName;
  2164. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
  2165. zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
  2166. if( zUnicodeName ){
  2167. memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
  2168. hFindFile = FindFirstFileW(zUnicodeName, &fd);
  2169. if( hFindFile!=NULL ){
  2170. pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
  2171. pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
  2172. pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
  2173. FindClose(hFindFile);
  2174. }
  2175. sqlite3_free(zUnicodeName);
  2176. }
  2177. }
  2178. #endif
  2179. /*
  2180. ** This function is used in place of stat(). On Windows, special handling
  2181. ** is required in order for the included time to be returned as UTC. On all
  2182. ** other systems, this function simply calls stat().
  2183. */
  2184. static int fileStat(
  2185. const char *zPath,
  2186. struct stat *pStatBuf
  2187. ){
  2188. #if defined(_WIN32)
  2189. int rc = stat(zPath, pStatBuf);
  2190. if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
  2191. return rc;
  2192. #else
  2193. return stat(zPath, pStatBuf);
  2194. #endif
  2195. }
  2196. /*
  2197. ** This function is used in place of lstat(). On Windows, special handling
  2198. ** is required in order for the included time to be returned as UTC. On all
  2199. ** other systems, this function simply calls lstat().
  2200. */
  2201. static int fileLinkStat(
  2202. const char *zPath,
  2203. struct stat *pStatBuf
  2204. ){
  2205. #if defined(_WIN32)
  2206. int rc = lstat(zPath, pStatBuf);
  2207. if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
  2208. return rc;
  2209. #else
  2210. return lstat(zPath, pStatBuf);
  2211. #endif
  2212. }
  2213. /*
  2214. ** Argument zFile is the name of a file that will be created and/or written
  2215. ** by SQL function writefile(). This function ensures that the directory
  2216. ** zFile will be written to exists, creating it if required. The permissions
  2217. ** for any path components created by this function are set in accordance
  2218. ** with the current umask.
  2219. **
  2220. ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
  2221. ** SQLITE_OK is returned if the directory is successfully created, or
  2222. ** SQLITE_ERROR otherwise.
  2223. */
  2224. static int makeDirectory(
  2225. const char *zFile
  2226. ){
  2227. char *zCopy = sqlite3_mprintf("%s", zFile);
  2228. int rc = SQLITE_OK;
  2229. if( zCopy==0 ){
  2230. rc = SQLITE_NOMEM;
  2231. }else{
  2232. int nCopy = (int)strlen(zCopy);
  2233. int i = 1;
  2234. while( rc==SQLITE_OK ){
  2235. struct stat sStat;
  2236. int rc2;
  2237. for(; zCopy[i]!='/' && i<nCopy; i++);
  2238. if( i==nCopy ) break;
  2239. zCopy[i] = '\0';
  2240. rc2 = fileStat(zCopy, &sStat);
  2241. if( rc2!=0 ){
  2242. if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
  2243. }else{
  2244. if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
  2245. }
  2246. zCopy[i] = '/';
  2247. i++;
  2248. }
  2249. sqlite3_free(zCopy);
  2250. }
  2251. return rc;
  2252. }
  2253. /*
  2254. ** This function does the work for the writefile() UDF. Refer to
  2255. ** header comments at the top of this file for details.
  2256. */
  2257. static int writeFile(
  2258. sqlite3_context *pCtx, /* Context to return bytes written in */
  2259. const char *zFile, /* File to write */
  2260. sqlite3_value *pData, /* Data to write */
  2261. mode_t mode, /* MODE parameter passed to writefile() */
  2262. sqlite3_int64 mtime /* MTIME parameter (or -1 to not set time) */
  2263. ){
  2264. if( zFile==0 ) return 1;
  2265. #if !defined(_WIN32) && !defined(WIN32)
  2266. if( S_ISLNK(mode) ){
  2267. const char *zTo = (const char*)sqlite3_value_text(pData);
  2268. if( zTo==0 || symlink(zTo, zFile)<0 ) return 1;
  2269. }else
  2270. #endif
  2271. {
  2272. if( S_ISDIR(mode) ){
  2273. if( mkdir(zFile, mode) ){
  2274. /* The mkdir() call to create the directory failed. This might not
  2275. ** be an error though - if there is already a directory at the same
  2276. ** path and either the permissions already match or can be changed
  2277. ** to do so using chmod(), it is not an error. */
  2278. struct stat sStat;
  2279. if( errno!=EEXIST
  2280. || 0!=fileStat(zFile, &sStat)
  2281. || !S_ISDIR(sStat.st_mode)
  2282. || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
  2283. ){
  2284. return 1;
  2285. }
  2286. }
  2287. }else{
  2288. sqlite3_int64 nWrite = 0;
  2289. const char *z;
  2290. int rc = 0;
  2291. FILE *out = fopen(zFile, "wb");
  2292. if( out==0 ) return 1;
  2293. z = (const char*)sqlite3_value_blob(pData);
  2294. if( z ){
  2295. sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
  2296. nWrite = sqlite3_value_bytes(pData);
  2297. if( nWrite!=n ){
  2298. rc = 1;
  2299. }
  2300. }
  2301. fclose(out);
  2302. if( rc==0 && mode && chmod(zFile, mode & 0777) ){
  2303. rc = 1;
  2304. }
  2305. if( rc ) return 2;
  2306. sqlite3_result_int64(pCtx, nWrite);
  2307. }
  2308. }
  2309. if( mtime>=0 ){
  2310. #if defined(_WIN32)
  2311. #if !SQLITE_OS_WINRT
  2312. /* Windows */
  2313. FILETIME lastAccess;
  2314. FILETIME lastWrite;
  2315. SYSTEMTIME currentTime;
  2316. LONGLONG intervals;
  2317. HANDLE hFile;
  2318. LPWSTR zUnicodeName;
  2319. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
  2320. GetSystemTime(&currentTime);
  2321. SystemTimeToFileTime(&currentTime, &lastAccess);
  2322. intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
  2323. lastWrite.dwLowDateTime = (DWORD)intervals;
  2324. lastWrite.dwHighDateTime = intervals >> 32;
  2325. zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
  2326. if( zUnicodeName==0 ){
  2327. return 1;
  2328. }
  2329. hFile = CreateFileW(
  2330. zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
  2331. FILE_FLAG_BACKUP_SEMANTICS, NULL
  2332. );
  2333. sqlite3_free(zUnicodeName);
  2334. if( hFile!=INVALID_HANDLE_VALUE ){
  2335. BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
  2336. CloseHandle(hFile);
  2337. return !bResult;
  2338. }else{
  2339. return 1;
  2340. }
  2341. #endif
  2342. #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
  2343. /* Recent unix */
  2344. struct timespec times[2];
  2345. times[0].tv_nsec = times[1].tv_nsec = 0;
  2346. times[0].tv_sec = time(0);
  2347. times[1].tv_sec = mtime;
  2348. if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
  2349. return 1;
  2350. }
  2351. #else
  2352. /* Legacy unix */
  2353. struct timeval times[2];
  2354. times[0].tv_usec = times[1].tv_usec = 0;
  2355. times[0].tv_sec = time(0);
  2356. times[1].tv_sec = mtime;
  2357. if( utimes(zFile, times) ){
  2358. return 1;
  2359. }
  2360. #endif
  2361. }
  2362. return 0;
  2363. }
  2364. /*
  2365. ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
  2366. ** Refer to header comments at the top of this file for details.
  2367. */
  2368. static void writefileFunc(
  2369. sqlite3_context *context,
  2370. int argc,
  2371. sqlite3_value **argv
  2372. ){
  2373. const char *zFile;
  2374. mode_t mode = 0;
  2375. int res;
  2376. sqlite3_int64 mtime = -1;
  2377. if( argc<2 || argc>4 ){
  2378. sqlite3_result_error(context,
  2379. "wrong number of arguments to function writefile()", -1
  2380. );
  2381. return;
  2382. }
  2383. zFile = (const char*)sqlite3_value_text(argv[0]);
  2384. if( zFile==0 ) return;
  2385. if( argc>=3 ){
  2386. mode = (mode_t)sqlite3_value_int(argv[2]);
  2387. }
  2388. if( argc==4 ){
  2389. mtime = sqlite3_value_int64(argv[3]);
  2390. }
  2391. res = writeFile(context, zFile, argv[1], mode, mtime);
  2392. if( res==1 && errno==ENOENT ){
  2393. if( makeDirectory(zFile)==SQLITE_OK ){
  2394. res = writeFile(context, zFile, argv[1], mode, mtime);
  2395. }
  2396. }
  2397. if( argc>2 && res!=0 ){
  2398. if( S_ISLNK(mode) ){
  2399. ctxErrorMsg(context, "failed to create symlink: %s", zFile);
  2400. }else if( S_ISDIR(mode) ){
  2401. ctxErrorMsg(context, "failed to create directory: %s", zFile);
  2402. }else{
  2403. ctxErrorMsg(context, "failed to write file: %s", zFile);
  2404. }
  2405. }
  2406. }
  2407. /*
  2408. ** SQL function: lsmode(MODE)
  2409. **
  2410. ** Given a numberic st_mode from stat(), convert it into a human-readable
  2411. ** text string in the style of "ls -l".
  2412. */
  2413. static void lsModeFunc(
  2414. sqlite3_context *context,
  2415. int argc,
  2416. sqlite3_value **argv
  2417. ){
  2418. int i;
  2419. int iMode = sqlite3_value_int(argv[0]);
  2420. char z[16];
  2421. (void)argc;
  2422. if( S_ISLNK(iMode) ){
  2423. z[0] = 'l';
  2424. }else if( S_ISREG(iMode) ){
  2425. z[0] = '-';
  2426. }else if( S_ISDIR(iMode) ){
  2427. z[0] = 'd';
  2428. }else{
  2429. z[0] = '?';
  2430. }
  2431. for(i=0; i<3; i++){
  2432. int m = (iMode >> ((2-i)*3));
  2433. char *a = &z[1 + i*3];
  2434. a[0] = (m & 0x4) ? 'r' : '-';
  2435. a[1] = (m & 0x2) ? 'w' : '-';
  2436. a[2] = (m & 0x1) ? 'x' : '-';
  2437. }
  2438. z[10] = '\0';
  2439. sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
  2440. }
  2441. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2442. /*
  2443. ** Cursor type for recursively iterating through a directory structure.
  2444. */
  2445. typedef struct fsdir_cursor fsdir_cursor;
  2446. typedef struct FsdirLevel FsdirLevel;
  2447. struct FsdirLevel {
  2448. DIR *pDir; /* From opendir() */
  2449. char *zDir; /* Name of directory (nul-terminated) */
  2450. };
  2451. struct fsdir_cursor {
  2452. sqlite3_vtab_cursor base; /* Base class - must be first */
  2453. int nLvl; /* Number of entries in aLvl[] array */
  2454. int iLvl; /* Index of current entry */
  2455. FsdirLevel *aLvl; /* Hierarchy of directories being traversed */
  2456. const char *zBase;
  2457. int nBase;
  2458. struct stat sStat; /* Current lstat() results */
  2459. char *zPath; /* Path to current entry */
  2460. sqlite3_int64 iRowid; /* Current rowid */
  2461. };
  2462. typedef struct fsdir_tab fsdir_tab;
  2463. struct fsdir_tab {
  2464. sqlite3_vtab base; /* Base class - must be first */
  2465. };
  2466. /*
  2467. ** Construct a new fsdir virtual table object.
  2468. */
  2469. static int fsdirConnect(
  2470. sqlite3 *db,
  2471. void *pAux,
  2472. int argc, const char *const*argv,
  2473. sqlite3_vtab **ppVtab,
  2474. char **pzErr
  2475. ){
  2476. fsdir_tab *pNew = 0;
  2477. int rc;
  2478. (void)pAux;
  2479. (void)argc;
  2480. (void)argv;
  2481. (void)pzErr;
  2482. rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
  2483. if( rc==SQLITE_OK ){
  2484. pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
  2485. if( pNew==0 ) return SQLITE_NOMEM;
  2486. memset(pNew, 0, sizeof(*pNew));
  2487. sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
  2488. }
  2489. *ppVtab = (sqlite3_vtab*)pNew;
  2490. return rc;
  2491. }
  2492. /*
  2493. ** This method is the destructor for fsdir vtab objects.
  2494. */
  2495. static int fsdirDisconnect(sqlite3_vtab *pVtab){
  2496. sqlite3_free(pVtab);
  2497. return SQLITE_OK;
  2498. }
  2499. /*
  2500. ** Constructor for a new fsdir_cursor object.
  2501. */
  2502. static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  2503. fsdir_cursor *pCur;
  2504. (void)p;
  2505. pCur = sqlite3_malloc( sizeof(*pCur) );
  2506. if( pCur==0 ) return SQLITE_NOMEM;
  2507. memset(pCur, 0, sizeof(*pCur));
  2508. pCur->iLvl = -1;
  2509. *ppCursor = &pCur->base;
  2510. return SQLITE_OK;
  2511. }
  2512. /*
  2513. ** Reset a cursor back to the state it was in when first returned
  2514. ** by fsdirOpen().
  2515. */
  2516. static void fsdirResetCursor(fsdir_cursor *pCur){
  2517. int i;
  2518. for(i=0; i<=pCur->iLvl; i++){
  2519. FsdirLevel *pLvl = &pCur->aLvl[i];
  2520. if( pLvl->pDir ) closedir(pLvl->pDir);
  2521. sqlite3_free(pLvl->zDir);
  2522. }
  2523. sqlite3_free(pCur->zPath);
  2524. sqlite3_free(pCur->aLvl);
  2525. pCur->aLvl = 0;
  2526. pCur->zPath = 0;
  2527. pCur->zBase = 0;
  2528. pCur->nBase = 0;
  2529. pCur->nLvl = 0;
  2530. pCur->iLvl = -1;
  2531. pCur->iRowid = 1;
  2532. }
  2533. /*
  2534. ** Destructor for an fsdir_cursor.
  2535. */
  2536. static int fsdirClose(sqlite3_vtab_cursor *cur){
  2537. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2538. fsdirResetCursor(pCur);
  2539. sqlite3_free(pCur);
  2540. return SQLITE_OK;
  2541. }
  2542. /*
  2543. ** Set the error message for the virtual table associated with cursor
  2544. ** pCur to the results of vprintf(zFmt, ...).
  2545. */
  2546. static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
  2547. va_list ap;
  2548. va_start(ap, zFmt);
  2549. pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
  2550. va_end(ap);
  2551. }
  2552. /*
  2553. ** Advance an fsdir_cursor to its next row of output.
  2554. */
  2555. static int fsdirNext(sqlite3_vtab_cursor *cur){
  2556. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2557. mode_t m = pCur->sStat.st_mode;
  2558. pCur->iRowid++;
  2559. if( S_ISDIR(m) ){
  2560. /* Descend into this directory */
  2561. int iNew = pCur->iLvl + 1;
  2562. FsdirLevel *pLvl;
  2563. if( iNew>=pCur->nLvl ){
  2564. int nNew = iNew+1;
  2565. sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
  2566. FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
  2567. if( aNew==0 ) return SQLITE_NOMEM;
  2568. memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
  2569. pCur->aLvl = aNew;
  2570. pCur->nLvl = nNew;
  2571. }
  2572. pCur->iLvl = iNew;
  2573. pLvl = &pCur->aLvl[iNew];
  2574. pLvl->zDir = pCur->zPath;
  2575. pCur->zPath = 0;
  2576. pLvl->pDir = opendir(pLvl->zDir);
  2577. if( pLvl->pDir==0 ){
  2578. fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
  2579. return SQLITE_ERROR;
  2580. }
  2581. }
  2582. while( pCur->iLvl>=0 ){
  2583. FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
  2584. struct dirent *pEntry = readdir(pLvl->pDir);
  2585. if( pEntry ){
  2586. if( pEntry->d_name[0]=='.' ){
  2587. if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
  2588. if( pEntry->d_name[1]=='\0' ) continue;
  2589. }
  2590. sqlite3_free(pCur->zPath);
  2591. pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
  2592. if( pCur->zPath==0 ) return SQLITE_NOMEM;
  2593. if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
  2594. fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
  2595. return SQLITE_ERROR;
  2596. }
  2597. return SQLITE_OK;
  2598. }
  2599. closedir(pLvl->pDir);
  2600. sqlite3_free(pLvl->zDir);
  2601. pLvl->pDir = 0;
  2602. pLvl->zDir = 0;
  2603. pCur->iLvl--;
  2604. }
  2605. /* EOF */
  2606. sqlite3_free(pCur->zPath);
  2607. pCur->zPath = 0;
  2608. return SQLITE_OK;
  2609. }
  2610. /*
  2611. ** Return values of columns for the row at which the series_cursor
  2612. ** is currently pointing.
  2613. */
  2614. static int fsdirColumn(
  2615. sqlite3_vtab_cursor *cur, /* The cursor */
  2616. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  2617. int i /* Which column to return */
  2618. ){
  2619. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2620. switch( i ){
  2621. case FSDIR_COLUMN_NAME: {
  2622. sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
  2623. break;
  2624. }
  2625. case FSDIR_COLUMN_MODE:
  2626. sqlite3_result_int64(ctx, pCur->sStat.st_mode);
  2627. break;
  2628. case FSDIR_COLUMN_MTIME:
  2629. sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
  2630. break;
  2631. case FSDIR_COLUMN_DATA: {
  2632. mode_t m = pCur->sStat.st_mode;
  2633. if( S_ISDIR(m) ){
  2634. sqlite3_result_null(ctx);
  2635. #if !defined(_WIN32) && !defined(WIN32)
  2636. }else if( S_ISLNK(m) ){
  2637. char aStatic[64];
  2638. char *aBuf = aStatic;
  2639. sqlite3_int64 nBuf = 64;
  2640. int n;
  2641. while( 1 ){
  2642. n = readlink(pCur->zPath, aBuf, nBuf);
  2643. if( n<nBuf ) break;
  2644. if( aBuf!=aStatic ) sqlite3_free(aBuf);
  2645. nBuf = nBuf*2;
  2646. aBuf = sqlite3_malloc64(nBuf);
  2647. if( aBuf==0 ){
  2648. sqlite3_result_error_nomem(ctx);
  2649. return SQLITE_NOMEM;
  2650. }
  2651. }
  2652. sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
  2653. if( aBuf!=aStatic ) sqlite3_free(aBuf);
  2654. #endif
  2655. }else{
  2656. readFileContents(ctx, pCur->zPath);
  2657. }
  2658. }
  2659. case FSDIR_COLUMN_PATH:
  2660. default: {
  2661. /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
  2662. ** always return their values as NULL */
  2663. break;
  2664. }
  2665. }
  2666. return SQLITE_OK;
  2667. }
  2668. /*
  2669. ** Return the rowid for the current row. In this implementation, the
  2670. ** first row returned is assigned rowid value 1, and each subsequent
  2671. ** row a value 1 more than that of the previous.
  2672. */
  2673. static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  2674. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2675. *pRowid = pCur->iRowid;
  2676. return SQLITE_OK;
  2677. }
  2678. /*
  2679. ** Return TRUE if the cursor has been moved off of the last
  2680. ** row of output.
  2681. */
  2682. static int fsdirEof(sqlite3_vtab_cursor *cur){
  2683. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2684. return (pCur->zPath==0);
  2685. }
  2686. /*
  2687. ** xFilter callback.
  2688. **
  2689. ** idxNum==1 PATH parameter only
  2690. ** idxNum==2 Both PATH and DIR supplied
  2691. */
  2692. static int fsdirFilter(
  2693. sqlite3_vtab_cursor *cur,
  2694. int idxNum, const char *idxStr,
  2695. int argc, sqlite3_value **argv
  2696. ){
  2697. const char *zDir = 0;
  2698. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2699. (void)idxStr;
  2700. fsdirResetCursor(pCur);
  2701. if( idxNum==0 ){
  2702. fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
  2703. return SQLITE_ERROR;
  2704. }
  2705. assert( argc==idxNum && (argc==1 || argc==2) );
  2706. zDir = (const char*)sqlite3_value_text(argv[0]);
  2707. if( zDir==0 ){
  2708. fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
  2709. return SQLITE_ERROR;
  2710. }
  2711. if( argc==2 ){
  2712. pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
  2713. }
  2714. if( pCur->zBase ){
  2715. pCur->nBase = (int)strlen(pCur->zBase)+1;
  2716. pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
  2717. }else{
  2718. pCur->zPath = sqlite3_mprintf("%s", zDir);
  2719. }
  2720. if( pCur->zPath==0 ){
  2721. return SQLITE_NOMEM;
  2722. }
  2723. if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
  2724. fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
  2725. return SQLITE_ERROR;
  2726. }
  2727. return SQLITE_OK;
  2728. }
  2729. /*
  2730. ** SQLite will invoke this method one or more times while planning a query
  2731. ** that uses the generate_series virtual table. This routine needs to create
  2732. ** a query plan for each invocation and compute an estimated cost for that
  2733. ** plan.
  2734. **
  2735. ** In this implementation idxNum is used to represent the
  2736. ** query plan. idxStr is unused.
  2737. **
  2738. ** The query plan is represented by values of idxNum:
  2739. **
  2740. ** (1) The path value is supplied by argv[0]
  2741. ** (2) Path is in argv[0] and dir is in argv[1]
  2742. */
  2743. static int fsdirBestIndex(
  2744. sqlite3_vtab *tab,
  2745. sqlite3_index_info *pIdxInfo
  2746. ){
  2747. int i; /* Loop over constraints */
  2748. int idxPath = -1; /* Index in pIdxInfo->aConstraint of PATH= */
  2749. int idxDir = -1; /* Index in pIdxInfo->aConstraint of DIR= */
  2750. int seenPath = 0; /* True if an unusable PATH= constraint is seen */
  2751. int seenDir = 0; /* True if an unusable DIR= constraint is seen */
  2752. const struct sqlite3_index_constraint *pConstraint;
  2753. (void)tab;
  2754. pConstraint = pIdxInfo->aConstraint;
  2755. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  2756. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  2757. switch( pConstraint->iColumn ){
  2758. case FSDIR_COLUMN_PATH: {
  2759. if( pConstraint->usable ){
  2760. idxPath = i;
  2761. seenPath = 0;
  2762. }else if( idxPath<0 ){
  2763. seenPath = 1;
  2764. }
  2765. break;
  2766. }
  2767. case FSDIR_COLUMN_DIR: {
  2768. if( pConstraint->usable ){
  2769. idxDir = i;
  2770. seenDir = 0;
  2771. }else if( idxDir<0 ){
  2772. seenDir = 1;
  2773. }
  2774. break;
  2775. }
  2776. }
  2777. }
  2778. if( seenPath || seenDir ){
  2779. /* If input parameters are unusable, disallow this plan */
  2780. return SQLITE_CONSTRAINT;
  2781. }
  2782. if( idxPath<0 ){
  2783. pIdxInfo->idxNum = 0;
  2784. /* The pIdxInfo->estimatedCost should have been initialized to a huge
  2785. ** number. Leave it unchanged. */
  2786. pIdxInfo->estimatedRows = 0x7fffffff;
  2787. }else{
  2788. pIdxInfo->aConstraintUsage[idxPath].omit = 1;
  2789. pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
  2790. if( idxDir>=0 ){
  2791. pIdxInfo->aConstraintUsage[idxDir].omit = 1;
  2792. pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
  2793. pIdxInfo->idxNum = 2;
  2794. pIdxInfo->estimatedCost = 10.0;
  2795. }else{
  2796. pIdxInfo->idxNum = 1;
  2797. pIdxInfo->estimatedCost = 100.0;
  2798. }
  2799. }
  2800. return SQLITE_OK;
  2801. }
  2802. /*
  2803. ** Register the "fsdir" virtual table.
  2804. */
  2805. static int fsdirRegister(sqlite3 *db){
  2806. static sqlite3_module fsdirModule = {
  2807. 0, /* iVersion */
  2808. 0, /* xCreate */
  2809. fsdirConnect, /* xConnect */
  2810. fsdirBestIndex, /* xBestIndex */
  2811. fsdirDisconnect, /* xDisconnect */
  2812. 0, /* xDestroy */
  2813. fsdirOpen, /* xOpen - open a cursor */
  2814. fsdirClose, /* xClose - close a cursor */
  2815. fsdirFilter, /* xFilter - configure scan constraints */
  2816. fsdirNext, /* xNext - advance a cursor */
  2817. fsdirEof, /* xEof - check for end of scan */
  2818. fsdirColumn, /* xColumn - read data */
  2819. fsdirRowid, /* xRowid - read data */
  2820. 0, /* xUpdate */
  2821. 0, /* xBegin */
  2822. 0, /* xSync */
  2823. 0, /* xCommit */
  2824. 0, /* xRollback */
  2825. 0, /* xFindMethod */
  2826. 0, /* xRename */
  2827. 0, /* xSavepoint */
  2828. 0, /* xRelease */
  2829. 0, /* xRollbackTo */
  2830. 0, /* xShadowName */
  2831. };
  2832. int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
  2833. return rc;
  2834. }
  2835. #else /* SQLITE_OMIT_VIRTUALTABLE */
  2836. # define fsdirRegister(x) SQLITE_OK
  2837. #endif
  2838. #ifdef _WIN32
  2839. #endif
  2840. int sqlite3_fileio_init(
  2841. sqlite3 *db,
  2842. char **pzErrMsg,
  2843. const sqlite3_api_routines *pApi
  2844. ){
  2845. int rc = SQLITE_OK;
  2846. SQLITE_EXTENSION_INIT2(pApi);
  2847. (void)pzErrMsg; /* Unused parameter */
  2848. rc = sqlite3_create_function(db, "readfile", 1,
  2849. SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
  2850. readfileFunc, 0, 0);
  2851. if( rc==SQLITE_OK ){
  2852. rc = sqlite3_create_function(db, "writefile", -1,
  2853. SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
  2854. writefileFunc, 0, 0);
  2855. }
  2856. if( rc==SQLITE_OK ){
  2857. rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
  2858. lsModeFunc, 0, 0);
  2859. }
  2860. if( rc==SQLITE_OK ){
  2861. rc = fsdirRegister(db);
  2862. }
  2863. return rc;
  2864. }
  2865. #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
  2866. /* To allow a standalone DLL, make test_windirent.c use the same
  2867. * redefined SQLite API calls as the above extension code does.
  2868. * Just pull in this .c to accomplish this. As a beneficial side
  2869. * effect, this extension becomes a single translation unit. */
  2870. # include "test_windirent.c"
  2871. #endif
  2872. /************************* End ../ext/misc/fileio.c ********************/
  2873. /************************* Begin ../ext/misc/completion.c ******************/
  2874. /*
  2875. ** 2017-07-10
  2876. **
  2877. ** The author disclaims copyright to this source code. In place of
  2878. ** a legal notice, here is a blessing:
  2879. **
  2880. ** May you do good and not evil.
  2881. ** May you find forgiveness for yourself and forgive others.
  2882. ** May you share freely, never taking more than you give.
  2883. **
  2884. *************************************************************************
  2885. **
  2886. ** This file implements an eponymous virtual table that returns suggested
  2887. ** completions for a partial SQL input.
  2888. **
  2889. ** Suggested usage:
  2890. **
  2891. ** SELECT DISTINCT candidate COLLATE nocase
  2892. ** FROM completion($prefix,$wholeline)
  2893. ** ORDER BY 1;
  2894. **
  2895. ** The two query parameters are optional. $prefix is the text of the
  2896. ** current word being typed and that is to be completed. $wholeline is
  2897. ** the complete input line, used for context.
  2898. **
  2899. ** The raw completion() table might return the same candidate multiple
  2900. ** times, for example if the same column name is used to two or more
  2901. ** tables. And the candidates are returned in an arbitrary order. Hence,
  2902. ** the DISTINCT and ORDER BY are recommended.
  2903. **
  2904. ** This virtual table operates at the speed of human typing, and so there
  2905. ** is no attempt to make it fast. Even a slow implementation will be much
  2906. ** faster than any human can type.
  2907. **
  2908. */
  2909. /* #include "sqlite3ext.h" */
  2910. SQLITE_EXTENSION_INIT1
  2911. #include <assert.h>
  2912. #include <string.h>
  2913. #include <ctype.h>
  2914. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2915. /* completion_vtab is a subclass of sqlite3_vtab which will
  2916. ** serve as the underlying representation of a completion virtual table
  2917. */
  2918. typedef struct completion_vtab completion_vtab;
  2919. struct completion_vtab {
  2920. sqlite3_vtab base; /* Base class - must be first */
  2921. sqlite3 *db; /* Database connection for this completion vtab */
  2922. };
  2923. /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
  2924. ** serve as the underlying representation of a cursor that scans
  2925. ** over rows of the result
  2926. */
  2927. typedef struct completion_cursor completion_cursor;
  2928. struct completion_cursor {
  2929. sqlite3_vtab_cursor base; /* Base class - must be first */
  2930. sqlite3 *db; /* Database connection for this cursor */
  2931. int nPrefix, nLine; /* Number of bytes in zPrefix and zLine */
  2932. char *zPrefix; /* The prefix for the word we want to complete */
  2933. char *zLine; /* The whole that we want to complete */
  2934. const char *zCurrentRow; /* Current output row */
  2935. int szRow; /* Length of the zCurrentRow string */
  2936. sqlite3_stmt *pStmt; /* Current statement */
  2937. sqlite3_int64 iRowid; /* The rowid */
  2938. int ePhase; /* Current phase */
  2939. int j; /* inter-phase counter */
  2940. };
  2941. /* Values for ePhase:
  2942. */
  2943. #define COMPLETION_FIRST_PHASE 1
  2944. #define COMPLETION_KEYWORDS 1
  2945. #define COMPLETION_PRAGMAS 2
  2946. #define COMPLETION_FUNCTIONS 3
  2947. #define COMPLETION_COLLATIONS 4
  2948. #define COMPLETION_INDEXES 5
  2949. #define COMPLETION_TRIGGERS 6
  2950. #define COMPLETION_DATABASES 7
  2951. #define COMPLETION_TABLES 8 /* Also VIEWs and TRIGGERs */
  2952. #define COMPLETION_COLUMNS 9
  2953. #define COMPLETION_MODULES 10
  2954. #define COMPLETION_EOF 11
  2955. /*
  2956. ** The completionConnect() method is invoked to create a new
  2957. ** completion_vtab that describes the completion virtual table.
  2958. **
  2959. ** Think of this routine as the constructor for completion_vtab objects.
  2960. **
  2961. ** All this routine needs to do is:
  2962. **
  2963. ** (1) Allocate the completion_vtab object and initialize all fields.
  2964. **
  2965. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  2966. ** result set of queries against completion will look like.
  2967. */
  2968. static int completionConnect(
  2969. sqlite3 *db,
  2970. void *pAux,
  2971. int argc, const char *const*argv,
  2972. sqlite3_vtab **ppVtab,
  2973. char **pzErr
  2974. ){
  2975. completion_vtab *pNew;
  2976. int rc;
  2977. (void)(pAux); /* Unused parameter */
  2978. (void)(argc); /* Unused parameter */
  2979. (void)(argv); /* Unused parameter */
  2980. (void)(pzErr); /* Unused parameter */
  2981. /* Column numbers */
  2982. #define COMPLETION_COLUMN_CANDIDATE 0 /* Suggested completion of the input */
  2983. #define COMPLETION_COLUMN_PREFIX 1 /* Prefix of the word to be completed */
  2984. #define COMPLETION_COLUMN_WHOLELINE 2 /* Entire line seen so far */
  2985. #define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */
  2986. sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
  2987. rc = sqlite3_declare_vtab(db,
  2988. "CREATE TABLE x("
  2989. " candidate TEXT,"
  2990. " prefix TEXT HIDDEN,"
  2991. " wholeline TEXT HIDDEN,"
  2992. " phase INT HIDDEN" /* Used for debugging only */
  2993. ")");
  2994. if( rc==SQLITE_OK ){
  2995. pNew = sqlite3_malloc( sizeof(*pNew) );
  2996. *ppVtab = (sqlite3_vtab*)pNew;
  2997. if( pNew==0 ) return SQLITE_NOMEM;
  2998. memset(pNew, 0, sizeof(*pNew));
  2999. pNew->db = db;
  3000. }
  3001. return rc;
  3002. }
  3003. /*
  3004. ** This method is the destructor for completion_cursor objects.
  3005. */
  3006. static int completionDisconnect(sqlite3_vtab *pVtab){
  3007. sqlite3_free(pVtab);
  3008. return SQLITE_OK;
  3009. }
  3010. /*
  3011. ** Constructor for a new completion_cursor object.
  3012. */
  3013. static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  3014. completion_cursor *pCur;
  3015. pCur = sqlite3_malloc( sizeof(*pCur) );
  3016. if( pCur==0 ) return SQLITE_NOMEM;
  3017. memset(pCur, 0, sizeof(*pCur));
  3018. pCur->db = ((completion_vtab*)p)->db;
  3019. *ppCursor = &pCur->base;
  3020. return SQLITE_OK;
  3021. }
  3022. /*
  3023. ** Reset the completion_cursor.
  3024. */
  3025. static void completionCursorReset(completion_cursor *pCur){
  3026. sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0;
  3027. sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0;
  3028. sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
  3029. pCur->j = 0;
  3030. }
  3031. /*
  3032. ** Destructor for a completion_cursor.
  3033. */
  3034. static int completionClose(sqlite3_vtab_cursor *cur){
  3035. completionCursorReset((completion_cursor*)cur);
  3036. sqlite3_free(cur);
  3037. return SQLITE_OK;
  3038. }
  3039. /*
  3040. ** Advance a completion_cursor to its next row of output.
  3041. **
  3042. ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
  3043. ** record the current state of the scan. This routine sets ->zCurrentRow
  3044. ** to the current row of output and then returns. If no more rows remain,
  3045. ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
  3046. ** table that has reached the end of its scan.
  3047. **
  3048. ** The current implementation just lists potential identifiers and
  3049. ** keywords and filters them by zPrefix. Future enhancements should
  3050. ** take zLine into account to try to restrict the set of identifiers and
  3051. ** keywords based on what would be legal at the current point of input.
  3052. */
  3053. static int completionNext(sqlite3_vtab_cursor *cur){
  3054. completion_cursor *pCur = (completion_cursor*)cur;
  3055. int eNextPhase = 0; /* Next phase to try if current phase reaches end */
  3056. int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */
  3057. pCur->iRowid++;
  3058. while( pCur->ePhase!=COMPLETION_EOF ){
  3059. switch( pCur->ePhase ){
  3060. case COMPLETION_KEYWORDS: {
  3061. if( pCur->j >= sqlite3_keyword_count() ){
  3062. pCur->zCurrentRow = 0;
  3063. pCur->ePhase = COMPLETION_DATABASES;
  3064. }else{
  3065. sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
  3066. }
  3067. iCol = -1;
  3068. break;
  3069. }
  3070. case COMPLETION_DATABASES: {
  3071. if( pCur->pStmt==0 ){
  3072. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
  3073. &pCur->pStmt, 0);
  3074. }
  3075. iCol = 1;
  3076. eNextPhase = COMPLETION_TABLES;
  3077. break;
  3078. }
  3079. case COMPLETION_TABLES: {
  3080. if( pCur->pStmt==0 ){
  3081. sqlite3_stmt *pS2;
  3082. char *zSql = 0;
  3083. const char *zSep = "";
  3084. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
  3085. while( sqlite3_step(pS2)==SQLITE_ROW ){
  3086. const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
  3087. zSql = sqlite3_mprintf(
  3088. "%z%s"
  3089. "SELECT name FROM \"%w\".sqlite_schema",
  3090. zSql, zSep, zDb
  3091. );
  3092. if( zSql==0 ) return SQLITE_NOMEM;
  3093. zSep = " UNION ";
  3094. }
  3095. sqlite3_finalize(pS2);
  3096. sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
  3097. sqlite3_free(zSql);
  3098. }
  3099. iCol = 0;
  3100. eNextPhase = COMPLETION_COLUMNS;
  3101. break;
  3102. }
  3103. case COMPLETION_COLUMNS: {
  3104. if( pCur->pStmt==0 ){
  3105. sqlite3_stmt *pS2;
  3106. char *zSql = 0;
  3107. const char *zSep = "";
  3108. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
  3109. while( sqlite3_step(pS2)==SQLITE_ROW ){
  3110. const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
  3111. zSql = sqlite3_mprintf(
  3112. "%z%s"
  3113. "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
  3114. " JOIN pragma_table_info(sm.name,%Q) AS pti"
  3115. " WHERE sm.type='table'",
  3116. zSql, zSep, zDb, zDb
  3117. );
  3118. if( zSql==0 ) return SQLITE_NOMEM;
  3119. zSep = " UNION ";
  3120. }
  3121. sqlite3_finalize(pS2);
  3122. sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
  3123. sqlite3_free(zSql);
  3124. }
  3125. iCol = 0;
  3126. eNextPhase = COMPLETION_EOF;
  3127. break;
  3128. }
  3129. }
  3130. if( iCol<0 ){
  3131. /* This case is when the phase presets zCurrentRow */
  3132. if( pCur->zCurrentRow==0 ) continue;
  3133. }else{
  3134. if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
  3135. /* Extract the next row of content */
  3136. pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
  3137. pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
  3138. }else{
  3139. /* When all rows are finished, advance to the next phase */
  3140. sqlite3_finalize(pCur->pStmt);
  3141. pCur->pStmt = 0;
  3142. pCur->ePhase = eNextPhase;
  3143. continue;
  3144. }
  3145. }
  3146. if( pCur->nPrefix==0 ) break;
  3147. if( pCur->nPrefix<=pCur->szRow
  3148. && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
  3149. ){
  3150. break;
  3151. }
  3152. }
  3153. return SQLITE_OK;
  3154. }
  3155. /*
  3156. ** Return values of columns for the row at which the completion_cursor
  3157. ** is currently pointing.
  3158. */
  3159. static int completionColumn(
  3160. sqlite3_vtab_cursor *cur, /* The cursor */
  3161. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  3162. int i /* Which column to return */
  3163. ){
  3164. completion_cursor *pCur = (completion_cursor*)cur;
  3165. switch( i ){
  3166. case COMPLETION_COLUMN_CANDIDATE: {
  3167. sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
  3168. break;
  3169. }
  3170. case COMPLETION_COLUMN_PREFIX: {
  3171. sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
  3172. break;
  3173. }
  3174. case COMPLETION_COLUMN_WHOLELINE: {
  3175. sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
  3176. break;
  3177. }
  3178. case COMPLETION_COLUMN_PHASE: {
  3179. sqlite3_result_int(ctx, pCur->ePhase);
  3180. break;
  3181. }
  3182. }
  3183. return SQLITE_OK;
  3184. }
  3185. /*
  3186. ** Return the rowid for the current row. In this implementation, the
  3187. ** rowid is the same as the output value.
  3188. */
  3189. static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  3190. completion_cursor *pCur = (completion_cursor*)cur;
  3191. *pRowid = pCur->iRowid;
  3192. return SQLITE_OK;
  3193. }
  3194. /*
  3195. ** Return TRUE if the cursor has been moved off of the last
  3196. ** row of output.
  3197. */
  3198. static int completionEof(sqlite3_vtab_cursor *cur){
  3199. completion_cursor *pCur = (completion_cursor*)cur;
  3200. return pCur->ePhase >= COMPLETION_EOF;
  3201. }
  3202. /*
  3203. ** This method is called to "rewind" the completion_cursor object back
  3204. ** to the first row of output. This method is always called at least
  3205. ** once prior to any call to completionColumn() or completionRowid() or
  3206. ** completionEof().
  3207. */
  3208. static int completionFilter(
  3209. sqlite3_vtab_cursor *pVtabCursor,
  3210. int idxNum, const char *idxStr,
  3211. int argc, sqlite3_value **argv
  3212. ){
  3213. completion_cursor *pCur = (completion_cursor *)pVtabCursor;
  3214. int iArg = 0;
  3215. (void)(idxStr); /* Unused parameter */
  3216. (void)(argc); /* Unused parameter */
  3217. completionCursorReset(pCur);
  3218. if( idxNum & 1 ){
  3219. pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
  3220. if( pCur->nPrefix>0 ){
  3221. pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
  3222. if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
  3223. }
  3224. iArg = 1;
  3225. }
  3226. if( idxNum & 2 ){
  3227. pCur->nLine = sqlite3_value_bytes(argv[iArg]);
  3228. if( pCur->nLine>0 ){
  3229. pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
  3230. if( pCur->zLine==0 ) return SQLITE_NOMEM;
  3231. }
  3232. }
  3233. if( pCur->zLine!=0 && pCur->zPrefix==0 ){
  3234. int i = pCur->nLine;
  3235. while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
  3236. i--;
  3237. }
  3238. pCur->nPrefix = pCur->nLine - i;
  3239. if( pCur->nPrefix>0 ){
  3240. pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
  3241. if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
  3242. }
  3243. }
  3244. pCur->iRowid = 0;
  3245. pCur->ePhase = COMPLETION_FIRST_PHASE;
  3246. return completionNext(pVtabCursor);
  3247. }
  3248. /*
  3249. ** SQLite will invoke this method one or more times while planning a query
  3250. ** that uses the completion virtual table. This routine needs to create
  3251. ** a query plan for each invocation and compute an estimated cost for that
  3252. ** plan.
  3253. **
  3254. ** There are two hidden parameters that act as arguments to the table-valued
  3255. ** function: "prefix" and "wholeline". Bit 0 of idxNum is set if "prefix"
  3256. ** is available and bit 1 is set if "wholeline" is available.
  3257. */
  3258. static int completionBestIndex(
  3259. sqlite3_vtab *tab,
  3260. sqlite3_index_info *pIdxInfo
  3261. ){
  3262. int i; /* Loop over constraints */
  3263. int idxNum = 0; /* The query plan bitmask */
  3264. int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */
  3265. int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
  3266. int nArg = 0; /* Number of arguments that completeFilter() expects */
  3267. const struct sqlite3_index_constraint *pConstraint;
  3268. (void)(tab); /* Unused parameter */
  3269. pConstraint = pIdxInfo->aConstraint;
  3270. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  3271. if( pConstraint->usable==0 ) continue;
  3272. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  3273. switch( pConstraint->iColumn ){
  3274. case COMPLETION_COLUMN_PREFIX:
  3275. prefixIdx = i;
  3276. idxNum |= 1;
  3277. break;
  3278. case COMPLETION_COLUMN_WHOLELINE:
  3279. wholelineIdx = i;
  3280. idxNum |= 2;
  3281. break;
  3282. }
  3283. }
  3284. if( prefixIdx>=0 ){
  3285. pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
  3286. pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
  3287. }
  3288. if( wholelineIdx>=0 ){
  3289. pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
  3290. pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
  3291. }
  3292. pIdxInfo->idxNum = idxNum;
  3293. pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
  3294. pIdxInfo->estimatedRows = 500 - 100*nArg;
  3295. return SQLITE_OK;
  3296. }
  3297. /*
  3298. ** This following structure defines all the methods for the
  3299. ** completion virtual table.
  3300. */
  3301. static sqlite3_module completionModule = {
  3302. 0, /* iVersion */
  3303. 0, /* xCreate */
  3304. completionConnect, /* xConnect */
  3305. completionBestIndex, /* xBestIndex */
  3306. completionDisconnect, /* xDisconnect */
  3307. 0, /* xDestroy */
  3308. completionOpen, /* xOpen - open a cursor */
  3309. completionClose, /* xClose - close a cursor */
  3310. completionFilter, /* xFilter - configure scan constraints */
  3311. completionNext, /* xNext - advance a cursor */
  3312. completionEof, /* xEof - check for end of scan */
  3313. completionColumn, /* xColumn - read data */
  3314. completionRowid, /* xRowid - read data */
  3315. 0, /* xUpdate */
  3316. 0, /* xBegin */
  3317. 0, /* xSync */
  3318. 0, /* xCommit */
  3319. 0, /* xRollback */
  3320. 0, /* xFindMethod */
  3321. 0, /* xRename */
  3322. 0, /* xSavepoint */
  3323. 0, /* xRelease */
  3324. 0, /* xRollbackTo */
  3325. 0 /* xShadowName */
  3326. };
  3327. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  3328. int sqlite3CompletionVtabInit(sqlite3 *db){
  3329. int rc = SQLITE_OK;
  3330. #ifndef SQLITE_OMIT_VIRTUALTABLE
  3331. rc = sqlite3_create_module(db, "completion", &completionModule, 0);
  3332. #endif
  3333. return rc;
  3334. }
  3335. #ifdef _WIN32
  3336. #endif
  3337. int sqlite3_completion_init(
  3338. sqlite3 *db,
  3339. char **pzErrMsg,
  3340. const sqlite3_api_routines *pApi
  3341. ){
  3342. int rc = SQLITE_OK;
  3343. SQLITE_EXTENSION_INIT2(pApi);
  3344. (void)(pzErrMsg); /* Unused parameter */
  3345. #ifndef SQLITE_OMIT_VIRTUALTABLE
  3346. rc = sqlite3CompletionVtabInit(db);
  3347. #endif
  3348. return rc;
  3349. }
  3350. /************************* End ../ext/misc/completion.c ********************/
  3351. /************************* Begin ../ext/misc/appendvfs.c ******************/
  3352. /*
  3353. ** 2017-10-20
  3354. **
  3355. ** The author disclaims copyright to this source code. In place of
  3356. ** a legal notice, here is a blessing:
  3357. **
  3358. ** May you do good and not evil.
  3359. ** May you find forgiveness for yourself and forgive others.
  3360. ** May you share freely, never taking more than you give.
  3361. **
  3362. ******************************************************************************
  3363. **
  3364. ** This file implements a VFS shim that allows an SQLite database to be
  3365. ** appended onto the end of some other file, such as an executable.
  3366. **
  3367. ** A special record must appear at the end of the file that identifies the
  3368. ** file as an appended database and provides the offset to the first page
  3369. ** of the exposed content. (Or, it is the length of the content prefix.)
  3370. ** For best performance page 1 should be located at a disk page boundary,
  3371. ** though that is not required.
  3372. **
  3373. ** When opening a database using this VFS, the connection might treat
  3374. ** the file as an ordinary SQLite database, or it might treat it as a
  3375. ** database appended onto some other file. The decision is made by
  3376. ** applying the following rules in order:
  3377. **
  3378. ** (1) An empty file is an ordinary database.
  3379. **
  3380. ** (2) If the file ends with the appendvfs trailer string
  3381. ** "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
  3382. **
  3383. ** (3) If the file begins with the standard SQLite prefix string
  3384. ** "SQLite format 3", that file is an ordinary database.
  3385. **
  3386. ** (4) If none of the above apply and the SQLITE_OPEN_CREATE flag is
  3387. ** set, then a new database is appended to the already existing file.
  3388. **
  3389. ** (5) Otherwise, SQLITE_CANTOPEN is returned.
  3390. **
  3391. ** To avoid unnecessary complications with the PENDING_BYTE, the size of
  3392. ** the file containing the database is limited to 1GiB. (1073741824 bytes)
  3393. ** This VFS will not read or write past the 1GiB mark. This restriction
  3394. ** might be lifted in future versions. For now, if you need a larger
  3395. ** database, then keep it in a separate file.
  3396. **
  3397. ** If the file being opened is a plain database (not an appended one), then
  3398. ** this shim is a pass-through into the default underlying VFS. (rule 3)
  3399. **/
  3400. /* #include "sqlite3ext.h" */
  3401. SQLITE_EXTENSION_INIT1
  3402. #include <string.h>
  3403. #include <assert.h>
  3404. /* The append mark at the end of the database is:
  3405. **
  3406. ** Start-Of-SQLite3-NNNNNNNN
  3407. ** 123456789 123456789 12345
  3408. **
  3409. ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
  3410. ** the offset to page 1, and also the length of the prefix content.
  3411. */
  3412. #define APND_MARK_PREFIX "Start-Of-SQLite3-"
  3413. #define APND_MARK_PREFIX_SZ 17
  3414. #define APND_MARK_FOS_SZ 8
  3415. #define APND_MARK_SIZE (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
  3416. /*
  3417. ** Maximum size of the combined prefix + database + append-mark. This
  3418. ** must be less than 0x40000000 to avoid locking issues on Windows.
  3419. */
  3420. #define APND_MAX_SIZE (0x40000000)
  3421. /*
  3422. ** Try to align the database to an even multiple of APND_ROUNDUP bytes.
  3423. */
  3424. #ifndef APND_ROUNDUP
  3425. #define APND_ROUNDUP 4096
  3426. #endif
  3427. #define APND_ALIGN_MASK ((sqlite3_int64)(APND_ROUNDUP-1))
  3428. #define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
  3429. /*
  3430. ** Forward declaration of objects used by this utility
  3431. */
  3432. typedef struct sqlite3_vfs ApndVfs;
  3433. typedef struct ApndFile ApndFile;
  3434. /* Access to a lower-level VFS that (might) implement dynamic loading,
  3435. ** access to randomness, etc.
  3436. */
  3437. #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
  3438. #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
  3439. /* An open appendvfs file
  3440. **
  3441. ** An instance of this structure describes the appended database file.
  3442. ** A separate sqlite3_file object is always appended. The appended
  3443. ** sqlite3_file object (which can be accessed using ORIGFILE()) describes
  3444. ** the entire file, including the prefix, the database, and the
  3445. ** append-mark.
  3446. **
  3447. ** The structure of an AppendVFS database is like this:
  3448. **
  3449. ** +-------------+---------+----------+-------------+
  3450. ** | prefix-file | padding | database | append-mark |
  3451. ** +-------------+---------+----------+-------------+
  3452. ** ^ ^
  3453. ** | |
  3454. ** iPgOne iMark
  3455. **
  3456. **
  3457. ** "prefix file" - file onto which the database has been appended.
  3458. ** "padding" - zero or more bytes inserted so that "database"
  3459. ** starts on an APND_ROUNDUP boundary
  3460. ** "database" - The SQLite database file
  3461. ** "append-mark" - The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
  3462. ** the offset from the start of prefix-file to the start
  3463. ** of "database".
  3464. **
  3465. ** The size of the database is iMark - iPgOne.
  3466. **
  3467. ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
  3468. ** of iPgOne stored as a big-ending 64-bit integer.
  3469. **
  3470. ** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
  3471. ** Or, iMark is -1 to indicate that it has not yet been written.
  3472. */
  3473. struct ApndFile {
  3474. sqlite3_file base; /* Subclass. MUST BE FIRST! */
  3475. sqlite3_int64 iPgOne; /* Offset to the start of the database */
  3476. sqlite3_int64 iMark; /* Offset of the append mark. -1 if unwritten */
  3477. /* Always followed by another sqlite3_file that describes the whole file */
  3478. };
  3479. /*
  3480. ** Methods for ApndFile
  3481. */
  3482. static int apndClose(sqlite3_file*);
  3483. static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  3484. static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
  3485. static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
  3486. static int apndSync(sqlite3_file*, int flags);
  3487. static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
  3488. static int apndLock(sqlite3_file*, int);
  3489. static int apndUnlock(sqlite3_file*, int);
  3490. static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
  3491. static int apndFileControl(sqlite3_file*, int op, void *pArg);
  3492. static int apndSectorSize(sqlite3_file*);
  3493. static int apndDeviceCharacteristics(sqlite3_file*);
  3494. static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  3495. static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
  3496. static void apndShmBarrier(sqlite3_file*);
  3497. static int apndShmUnmap(sqlite3_file*, int deleteFlag);
  3498. static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  3499. static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  3500. /*
  3501. ** Methods for ApndVfs
  3502. */
  3503. static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
  3504. static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
  3505. static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
  3506. static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
  3507. static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
  3508. static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
  3509. static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
  3510. static void apndDlClose(sqlite3_vfs*, void*);
  3511. static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
  3512. static int apndSleep(sqlite3_vfs*, int microseconds);
  3513. static int apndCurrentTime(sqlite3_vfs*, double*);
  3514. static int apndGetLastError(sqlite3_vfs*, int, char *);
  3515. static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
  3516. static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
  3517. static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
  3518. static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
  3519. static sqlite3_vfs apnd_vfs = {
  3520. 3, /* iVersion (set when registered) */
  3521. 0, /* szOsFile (set when registered) */
  3522. 1024, /* mxPathname */
  3523. 0, /* pNext */
  3524. "apndvfs", /* zName */
  3525. 0, /* pAppData (set when registered) */
  3526. apndOpen, /* xOpen */
  3527. apndDelete, /* xDelete */
  3528. apndAccess, /* xAccess */
  3529. apndFullPathname, /* xFullPathname */
  3530. apndDlOpen, /* xDlOpen */
  3531. apndDlError, /* xDlError */
  3532. apndDlSym, /* xDlSym */
  3533. apndDlClose, /* xDlClose */
  3534. apndRandomness, /* xRandomness */
  3535. apndSleep, /* xSleep */
  3536. apndCurrentTime, /* xCurrentTime */
  3537. apndGetLastError, /* xGetLastError */
  3538. apndCurrentTimeInt64, /* xCurrentTimeInt64 */
  3539. apndSetSystemCall, /* xSetSystemCall */
  3540. apndGetSystemCall, /* xGetSystemCall */
  3541. apndNextSystemCall /* xNextSystemCall */
  3542. };
  3543. static const sqlite3_io_methods apnd_io_methods = {
  3544. 3, /* iVersion */
  3545. apndClose, /* xClose */
  3546. apndRead, /* xRead */
  3547. apndWrite, /* xWrite */
  3548. apndTruncate, /* xTruncate */
  3549. apndSync, /* xSync */
  3550. apndFileSize, /* xFileSize */
  3551. apndLock, /* xLock */
  3552. apndUnlock, /* xUnlock */
  3553. apndCheckReservedLock, /* xCheckReservedLock */
  3554. apndFileControl, /* xFileControl */
  3555. apndSectorSize, /* xSectorSize */
  3556. apndDeviceCharacteristics, /* xDeviceCharacteristics */
  3557. apndShmMap, /* xShmMap */
  3558. apndShmLock, /* xShmLock */
  3559. apndShmBarrier, /* xShmBarrier */
  3560. apndShmUnmap, /* xShmUnmap */
  3561. apndFetch, /* xFetch */
  3562. apndUnfetch /* xUnfetch */
  3563. };
  3564. /*
  3565. ** Close an apnd-file.
  3566. */
  3567. static int apndClose(sqlite3_file *pFile){
  3568. pFile = ORIGFILE(pFile);
  3569. return pFile->pMethods->xClose(pFile);
  3570. }
  3571. /*
  3572. ** Read data from an apnd-file.
  3573. */
  3574. static int apndRead(
  3575. sqlite3_file *pFile,
  3576. void *zBuf,
  3577. int iAmt,
  3578. sqlite_int64 iOfst
  3579. ){
  3580. ApndFile *paf = (ApndFile *)pFile;
  3581. pFile = ORIGFILE(pFile);
  3582. return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
  3583. }
  3584. /*
  3585. ** Add the append-mark onto what should become the end of the file.
  3586. * If and only if this succeeds, internal ApndFile.iMark is updated.
  3587. * Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
  3588. */
  3589. static int apndWriteMark(
  3590. ApndFile *paf,
  3591. sqlite3_file *pFile,
  3592. sqlite_int64 iWriteEnd
  3593. ){
  3594. sqlite_int64 iPgOne = paf->iPgOne;
  3595. unsigned char a[APND_MARK_SIZE];
  3596. int i = APND_MARK_FOS_SZ;
  3597. int rc;
  3598. assert(pFile == ORIGFILE(paf));
  3599. memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
  3600. while( --i >= 0 ){
  3601. a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
  3602. iPgOne >>= 8;
  3603. }
  3604. iWriteEnd += paf->iPgOne;
  3605. if( SQLITE_OK==(rc = pFile->pMethods->xWrite
  3606. (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
  3607. paf->iMark = iWriteEnd;
  3608. }
  3609. return rc;
  3610. }
  3611. /*
  3612. ** Write data to an apnd-file.
  3613. */
  3614. static int apndWrite(
  3615. sqlite3_file *pFile,
  3616. const void *zBuf,
  3617. int iAmt,
  3618. sqlite_int64 iOfst
  3619. ){
  3620. ApndFile *paf = (ApndFile *)pFile;
  3621. sqlite_int64 iWriteEnd = iOfst + iAmt;
  3622. if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
  3623. pFile = ORIGFILE(pFile);
  3624. /* If append-mark is absent or will be overwritten, write it. */
  3625. if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
  3626. int rc = apndWriteMark(paf, pFile, iWriteEnd);
  3627. if( SQLITE_OK!=rc ) return rc;
  3628. }
  3629. return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
  3630. }
  3631. /*
  3632. ** Truncate an apnd-file.
  3633. */
  3634. static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
  3635. ApndFile *paf = (ApndFile *)pFile;
  3636. pFile = ORIGFILE(pFile);
  3637. /* The append mark goes out first so truncate failure does not lose it. */
  3638. if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
  3639. /* Truncate underlying file just past append mark */
  3640. return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
  3641. }
  3642. /*
  3643. ** Sync an apnd-file.
  3644. */
  3645. static int apndSync(sqlite3_file *pFile, int flags){
  3646. pFile = ORIGFILE(pFile);
  3647. return pFile->pMethods->xSync(pFile, flags);
  3648. }
  3649. /*
  3650. ** Return the current file-size of an apnd-file.
  3651. ** If the append mark is not yet there, the file-size is 0.
  3652. */
  3653. static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  3654. ApndFile *paf = (ApndFile *)pFile;
  3655. *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
  3656. return SQLITE_OK;
  3657. }
  3658. /*
  3659. ** Lock an apnd-file.
  3660. */
  3661. static int apndLock(sqlite3_file *pFile, int eLock){
  3662. pFile = ORIGFILE(pFile);
  3663. return pFile->pMethods->xLock(pFile, eLock);
  3664. }
  3665. /*
  3666. ** Unlock an apnd-file.
  3667. */
  3668. static int apndUnlock(sqlite3_file *pFile, int eLock){
  3669. pFile = ORIGFILE(pFile);
  3670. return pFile->pMethods->xUnlock(pFile, eLock);
  3671. }
  3672. /*
  3673. ** Check if another file-handle holds a RESERVED lock on an apnd-file.
  3674. */
  3675. static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  3676. pFile = ORIGFILE(pFile);
  3677. return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
  3678. }
  3679. /*
  3680. ** File control method. For custom operations on an apnd-file.
  3681. */
  3682. static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
  3683. ApndFile *paf = (ApndFile *)pFile;
  3684. int rc;
  3685. pFile = ORIGFILE(pFile);
  3686. if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
  3687. rc = pFile->pMethods->xFileControl(pFile, op, pArg);
  3688. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  3689. *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
  3690. }
  3691. return rc;
  3692. }
  3693. /*
  3694. ** Return the sector-size in bytes for an apnd-file.
  3695. */
  3696. static int apndSectorSize(sqlite3_file *pFile){
  3697. pFile = ORIGFILE(pFile);
  3698. return pFile->pMethods->xSectorSize(pFile);
  3699. }
  3700. /*
  3701. ** Return the device characteristic flags supported by an apnd-file.
  3702. */
  3703. static int apndDeviceCharacteristics(sqlite3_file *pFile){
  3704. pFile = ORIGFILE(pFile);
  3705. return pFile->pMethods->xDeviceCharacteristics(pFile);
  3706. }
  3707. /* Create a shared memory file mapping */
  3708. static int apndShmMap(
  3709. sqlite3_file *pFile,
  3710. int iPg,
  3711. int pgsz,
  3712. int bExtend,
  3713. void volatile **pp
  3714. ){
  3715. pFile = ORIGFILE(pFile);
  3716. return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
  3717. }
  3718. /* Perform locking on a shared-memory segment */
  3719. static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
  3720. pFile = ORIGFILE(pFile);
  3721. return pFile->pMethods->xShmLock(pFile,offset,n,flags);
  3722. }
  3723. /* Memory barrier operation on shared memory */
  3724. static void apndShmBarrier(sqlite3_file *pFile){
  3725. pFile = ORIGFILE(pFile);
  3726. pFile->pMethods->xShmBarrier(pFile);
  3727. }
  3728. /* Unmap a shared memory segment */
  3729. static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
  3730. pFile = ORIGFILE(pFile);
  3731. return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
  3732. }
  3733. /* Fetch a page of a memory-mapped file */
  3734. static int apndFetch(
  3735. sqlite3_file *pFile,
  3736. sqlite3_int64 iOfst,
  3737. int iAmt,
  3738. void **pp
  3739. ){
  3740. ApndFile *p = (ApndFile *)pFile;
  3741. if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
  3742. return SQLITE_IOERR; /* Cannot read what is not yet there. */
  3743. }
  3744. pFile = ORIGFILE(pFile);
  3745. return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
  3746. }
  3747. /* Release a memory-mapped page */
  3748. static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
  3749. ApndFile *p = (ApndFile *)pFile;
  3750. pFile = ORIGFILE(pFile);
  3751. return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
  3752. }
  3753. /*
  3754. ** Try to read the append-mark off the end of a file. Return the
  3755. ** start of the appended database if the append-mark is present.
  3756. ** If there is no valid append-mark, return -1;
  3757. **
  3758. ** An append-mark is only valid if the NNNNNNNN start-of-database offset
  3759. ** indicates that the appended database contains at least one page. The
  3760. ** start-of-database value must be a multiple of 512.
  3761. */
  3762. static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
  3763. int rc, i;
  3764. sqlite3_int64 iMark;
  3765. int msbs = 8 * (APND_MARK_FOS_SZ-1);
  3766. unsigned char a[APND_MARK_SIZE];
  3767. if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
  3768. rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
  3769. if( rc ) return -1;
  3770. if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
  3771. iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
  3772. for(i=1; i<8; i++){
  3773. msbs -= 8;
  3774. iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
  3775. }
  3776. if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
  3777. if( iMark & 0x1ff ) return -1;
  3778. return iMark;
  3779. }
  3780. static const char apvfsSqliteHdr[] = "SQLite format 3";
  3781. /*
  3782. ** Check to see if the file is an appendvfs SQLite database file.
  3783. ** Return true iff it is such. Parameter sz is the file's size.
  3784. */
  3785. static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
  3786. int rc;
  3787. char zHdr[16];
  3788. sqlite3_int64 iMark = apndReadMark(sz, pFile);
  3789. if( iMark>=0 ){
  3790. /* If file has the correct end-marker, the expected odd size, and the
  3791. ** SQLite DB type marker where the end-marker puts it, then it
  3792. ** is an appendvfs database.
  3793. */
  3794. rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
  3795. if( SQLITE_OK==rc
  3796. && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
  3797. && (sz & 0x1ff) == APND_MARK_SIZE
  3798. && sz>=512+APND_MARK_SIZE
  3799. ){
  3800. return 1; /* It's an appendvfs database */
  3801. }
  3802. }
  3803. return 0;
  3804. }
  3805. /*
  3806. ** Check to see if the file is an ordinary SQLite database file.
  3807. ** Return true iff so. Parameter sz is the file's size.
  3808. */
  3809. static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
  3810. char zHdr[16];
  3811. if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
  3812. || (sz & 0x1ff) != 0
  3813. || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
  3814. || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
  3815. ){
  3816. return 0;
  3817. }else{
  3818. return 1;
  3819. }
  3820. }
  3821. /*
  3822. ** Open an apnd file handle.
  3823. */
  3824. static int apndOpen(
  3825. sqlite3_vfs *pApndVfs,
  3826. const char *zName,
  3827. sqlite3_file *pFile,
  3828. int flags,
  3829. int *pOutFlags
  3830. ){
  3831. ApndFile *pApndFile = (ApndFile*)pFile;
  3832. sqlite3_file *pBaseFile = ORIGFILE(pFile);
  3833. sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
  3834. int rc;
  3835. sqlite3_int64 sz = 0;
  3836. if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
  3837. /* The appendvfs is not to be used for transient or temporary databases.
  3838. ** Just use the base VFS open to initialize the given file object and
  3839. ** open the underlying file. (Appendvfs is then unused for this file.)
  3840. */
  3841. return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
  3842. }
  3843. memset(pApndFile, 0, sizeof(ApndFile));
  3844. pFile->pMethods = &apnd_io_methods;
  3845. pApndFile->iMark = -1; /* Append mark not yet written */
  3846. rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
  3847. if( rc==SQLITE_OK ){
  3848. rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
  3849. if( rc ){
  3850. pBaseFile->pMethods->xClose(pBaseFile);
  3851. }
  3852. }
  3853. if( rc ){
  3854. pFile->pMethods = 0;
  3855. return rc;
  3856. }
  3857. if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
  3858. /* The file being opened appears to be just an ordinary DB. Copy
  3859. ** the base dispatch-table so this instance mimics the base VFS.
  3860. */
  3861. memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
  3862. return SQLITE_OK;
  3863. }
  3864. pApndFile->iPgOne = apndReadMark(sz, pFile);
  3865. if( pApndFile->iPgOne>=0 ){
  3866. pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
  3867. return SQLITE_OK;
  3868. }
  3869. if( (flags & SQLITE_OPEN_CREATE)==0 ){
  3870. pBaseFile->pMethods->xClose(pBaseFile);
  3871. rc = SQLITE_CANTOPEN;
  3872. pFile->pMethods = 0;
  3873. }else{
  3874. /* Round newly added appendvfs location to #define'd page boundary.
  3875. ** Note that nothing has yet been written to the underlying file.
  3876. ** The append mark will be written along with first content write.
  3877. ** Until then, paf->iMark value indicates it is not yet written.
  3878. */
  3879. pApndFile->iPgOne = APND_START_ROUNDUP(sz);
  3880. }
  3881. return rc;
  3882. }
  3883. /*
  3884. ** Delete an apnd file.
  3885. ** For an appendvfs, this could mean delete the appendvfs portion,
  3886. ** leaving the appendee as it was before it gained an appendvfs.
  3887. ** For now, this code deletes the underlying file too.
  3888. */
  3889. static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  3890. return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
  3891. }
  3892. /*
  3893. ** All other VFS methods are pass-thrus.
  3894. */
  3895. static int apndAccess(
  3896. sqlite3_vfs *pVfs,
  3897. const char *zPath,
  3898. int flags,
  3899. int *pResOut
  3900. ){
  3901. return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
  3902. }
  3903. static int apndFullPathname(
  3904. sqlite3_vfs *pVfs,
  3905. const char *zPath,
  3906. int nOut,
  3907. char *zOut
  3908. ){
  3909. return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
  3910. }
  3911. static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  3912. return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
  3913. }
  3914. static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  3915. ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
  3916. }
  3917. static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
  3918. return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
  3919. }
  3920. static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
  3921. ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
  3922. }
  3923. static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  3924. return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
  3925. }
  3926. static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
  3927. return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
  3928. }
  3929. static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  3930. return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
  3931. }
  3932. static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  3933. return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
  3934. }
  3935. static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
  3936. return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
  3937. }
  3938. static int apndSetSystemCall(
  3939. sqlite3_vfs *pVfs,
  3940. const char *zName,
  3941. sqlite3_syscall_ptr pCall
  3942. ){
  3943. return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
  3944. }
  3945. static sqlite3_syscall_ptr apndGetSystemCall(
  3946. sqlite3_vfs *pVfs,
  3947. const char *zName
  3948. ){
  3949. return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
  3950. }
  3951. static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
  3952. return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
  3953. }
  3954. #ifdef _WIN32
  3955. #endif
  3956. /*
  3957. ** This routine is called when the extension is loaded.
  3958. ** Register the new VFS.
  3959. */
  3960. int sqlite3_appendvfs_init(
  3961. sqlite3 *db,
  3962. char **pzErrMsg,
  3963. const sqlite3_api_routines *pApi
  3964. ){
  3965. int rc = SQLITE_OK;
  3966. sqlite3_vfs *pOrig;
  3967. SQLITE_EXTENSION_INIT2(pApi);
  3968. (void)pzErrMsg;
  3969. (void)db;
  3970. pOrig = sqlite3_vfs_find(0);
  3971. if( pOrig==0 ) return SQLITE_ERROR;
  3972. apnd_vfs.iVersion = pOrig->iVersion;
  3973. apnd_vfs.pAppData = pOrig;
  3974. apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
  3975. rc = sqlite3_vfs_register(&apnd_vfs, 0);
  3976. #ifdef APPENDVFS_TEST
  3977. if( rc==SQLITE_OK ){
  3978. rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
  3979. }
  3980. #endif
  3981. if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
  3982. return rc;
  3983. }
  3984. /************************* End ../ext/misc/appendvfs.c ********************/
  3985. /************************* Begin ../ext/misc/memtrace.c ******************/
  3986. /*
  3987. ** 2019-01-21
  3988. **
  3989. ** The author disclaims copyright to this source code. In place of
  3990. ** a legal notice, here is a blessing:
  3991. **
  3992. ** May you do good and not evil.
  3993. ** May you find forgiveness for yourself and forgive others.
  3994. ** May you share freely, never taking more than you give.
  3995. **
  3996. *************************************************************************
  3997. **
  3998. ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
  3999. ** mechanism to add a tracing layer on top of SQLite. If this extension
  4000. ** is registered prior to sqlite3_initialize(), it will cause all memory
  4001. ** allocation activities to be logged on standard output, or to some other
  4002. ** FILE specified by the initializer.
  4003. **
  4004. ** This file needs to be compiled into the application that uses it.
  4005. **
  4006. ** This extension is used to implement the --memtrace option of the
  4007. ** command-line shell.
  4008. */
  4009. #include <assert.h>
  4010. #include <string.h>
  4011. #include <stdio.h>
  4012. /* The original memory allocation routines */
  4013. static sqlite3_mem_methods memtraceBase;
  4014. static FILE *memtraceOut;
  4015. /* Methods that trace memory allocations */
  4016. static void *memtraceMalloc(int n){
  4017. if( memtraceOut ){
  4018. fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
  4019. memtraceBase.xRoundup(n));
  4020. }
  4021. return memtraceBase.xMalloc(n);
  4022. }
  4023. static void memtraceFree(void *p){
  4024. if( p==0 ) return;
  4025. if( memtraceOut ){
  4026. fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
  4027. }
  4028. memtraceBase.xFree(p);
  4029. }
  4030. static void *memtraceRealloc(void *p, int n){
  4031. if( p==0 ) return memtraceMalloc(n);
  4032. if( n==0 ){
  4033. memtraceFree(p);
  4034. return 0;
  4035. }
  4036. if( memtraceOut ){
  4037. fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
  4038. memtraceBase.xSize(p), memtraceBase.xRoundup(n));
  4039. }
  4040. return memtraceBase.xRealloc(p, n);
  4041. }
  4042. static int memtraceSize(void *p){
  4043. return memtraceBase.xSize(p);
  4044. }
  4045. static int memtraceRoundup(int n){
  4046. return memtraceBase.xRoundup(n);
  4047. }
  4048. static int memtraceInit(void *p){
  4049. return memtraceBase.xInit(p);
  4050. }
  4051. static void memtraceShutdown(void *p){
  4052. memtraceBase.xShutdown(p);
  4053. }
  4054. /* The substitute memory allocator */
  4055. static sqlite3_mem_methods ersaztMethods = {
  4056. memtraceMalloc,
  4057. memtraceFree,
  4058. memtraceRealloc,
  4059. memtraceSize,
  4060. memtraceRoundup,
  4061. memtraceInit,
  4062. memtraceShutdown,
  4063. 0
  4064. };
  4065. /* Begin tracing memory allocations to out. */
  4066. int sqlite3MemTraceActivate(FILE *out){
  4067. int rc = SQLITE_OK;
  4068. if( memtraceBase.xMalloc==0 ){
  4069. rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
  4070. if( rc==SQLITE_OK ){
  4071. rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
  4072. }
  4073. }
  4074. memtraceOut = out;
  4075. return rc;
  4076. }
  4077. /* Deactivate memory tracing */
  4078. int sqlite3MemTraceDeactivate(void){
  4079. int rc = SQLITE_OK;
  4080. if( memtraceBase.xMalloc!=0 ){
  4081. rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
  4082. if( rc==SQLITE_OK ){
  4083. memset(&memtraceBase, 0, sizeof(memtraceBase));
  4084. }
  4085. }
  4086. memtraceOut = 0;
  4087. return rc;
  4088. }
  4089. /************************* End ../ext/misc/memtrace.c ********************/
  4090. /************************* Begin ../ext/misc/uint.c ******************/
  4091. /*
  4092. ** 2020-04-14
  4093. **
  4094. ** The author disclaims copyright to this source code. In place of
  4095. ** a legal notice, here is a blessing:
  4096. **
  4097. ** May you do good and not evil.
  4098. ** May you find forgiveness for yourself and forgive others.
  4099. ** May you share freely, never taking more than you give.
  4100. **
  4101. ******************************************************************************
  4102. **
  4103. ** This SQLite extension implements the UINT collating sequence.
  4104. **
  4105. ** UINT works like BINARY for text, except that embedded strings
  4106. ** of digits compare in numeric order.
  4107. **
  4108. ** * Leading zeros are handled properly, in the sense that
  4109. ** they do not mess of the maginitude comparison of embedded
  4110. ** strings of digits. "x00123y" is equal to "x123y".
  4111. **
  4112. ** * Only unsigned integers are recognized. Plus and minus
  4113. ** signs are ignored. Decimal points and exponential notation
  4114. ** are ignored.
  4115. **
  4116. ** * Embedded integers can be of arbitrary length. Comparison
  4117. ** is *not* limited integers that can be expressed as a
  4118. ** 64-bit machine integer.
  4119. */
  4120. /* #include "sqlite3ext.h" */
  4121. SQLITE_EXTENSION_INIT1
  4122. #include <assert.h>
  4123. #include <string.h>
  4124. #include <ctype.h>
  4125. /*
  4126. ** Compare text in lexicographic order, except strings of digits
  4127. ** compare in numeric order.
  4128. */
  4129. static int uintCollFunc(
  4130. void *notUsed,
  4131. int nKey1, const void *pKey1,
  4132. int nKey2, const void *pKey2
  4133. ){
  4134. const unsigned char *zA = (const unsigned char*)pKey1;
  4135. const unsigned char *zB = (const unsigned char*)pKey2;
  4136. int i=0, j=0, x;
  4137. (void)notUsed;
  4138. while( i<nKey1 && j<nKey2 ){
  4139. x = zA[i] - zB[j];
  4140. if( isdigit(zA[i]) ){
  4141. int k;
  4142. if( !isdigit(zB[j]) ) return x;
  4143. while( i<nKey1 && zA[i]=='0' ){ i++; }
  4144. while( j<nKey2 && zB[j]=='0' ){ j++; }
  4145. k = 0;
  4146. while( i+k<nKey1 && isdigit(zA[i+k])
  4147. && j+k<nKey2 && isdigit(zB[j+k]) ){
  4148. k++;
  4149. }
  4150. if( i+k<nKey1 && isdigit(zA[i+k]) ){
  4151. return +1;
  4152. }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
  4153. return -1;
  4154. }else{
  4155. x = memcmp(zA+i, zB+j, k);
  4156. if( x ) return x;
  4157. i += k;
  4158. j += k;
  4159. }
  4160. }else if( x ){
  4161. return x;
  4162. }else{
  4163. i++;
  4164. j++;
  4165. }
  4166. }
  4167. return (nKey1 - i) - (nKey2 - j);
  4168. }
  4169. #ifdef _WIN32
  4170. #endif
  4171. int sqlite3_uint_init(
  4172. sqlite3 *db,
  4173. char **pzErrMsg,
  4174. const sqlite3_api_routines *pApi
  4175. ){
  4176. SQLITE_EXTENSION_INIT2(pApi);
  4177. (void)pzErrMsg; /* Unused parameter */
  4178. return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
  4179. }
  4180. /************************* End ../ext/misc/uint.c ********************/
  4181. /************************* Begin ../ext/misc/decimal.c ******************/
  4182. /*
  4183. ** 2020-06-22
  4184. **
  4185. ** The author disclaims copyright to this source code. In place of
  4186. ** a legal notice, here is a blessing:
  4187. **
  4188. ** May you do good and not evil.
  4189. ** May you find forgiveness for yourself and forgive others.
  4190. ** May you share freely, never taking more than you give.
  4191. **
  4192. ******************************************************************************
  4193. **
  4194. ** Routines to implement arbitrary-precision decimal math.
  4195. **
  4196. ** The focus here is on simplicity and correctness, not performance.
  4197. */
  4198. /* #include "sqlite3ext.h" */
  4199. SQLITE_EXTENSION_INIT1
  4200. #include <assert.h>
  4201. #include <string.h>
  4202. #include <ctype.h>
  4203. #include <stdlib.h>
  4204. /* Mark a function parameter as unused, to suppress nuisance compiler
  4205. ** warnings. */
  4206. #ifndef UNUSED_PARAMETER
  4207. # define UNUSED_PARAMETER(X) (void)(X)
  4208. #endif
  4209. /* A decimal object */
  4210. typedef struct Decimal Decimal;
  4211. struct Decimal {
  4212. char sign; /* 0 for positive, 1 for negative */
  4213. char oom; /* True if an OOM is encountered */
  4214. char isNull; /* True if holds a NULL rather than a number */
  4215. char isInit; /* True upon initialization */
  4216. int nDigit; /* Total number of digits */
  4217. int nFrac; /* Number of digits to the right of the decimal point */
  4218. signed char *a; /* Array of digits. Most significant first. */
  4219. };
  4220. /*
  4221. ** Release memory held by a Decimal, but do not free the object itself.
  4222. */
  4223. static void decimal_clear(Decimal *p){
  4224. sqlite3_free(p->a);
  4225. }
  4226. /*
  4227. ** Destroy a Decimal object
  4228. */
  4229. static void decimal_free(Decimal *p){
  4230. if( p ){
  4231. decimal_clear(p);
  4232. sqlite3_free(p);
  4233. }
  4234. }
  4235. /*
  4236. ** Allocate a new Decimal object. Initialize it to the number given
  4237. ** by the input string.
  4238. */
  4239. static Decimal *decimal_new(
  4240. sqlite3_context *pCtx,
  4241. sqlite3_value *pIn,
  4242. int nAlt,
  4243. const unsigned char *zAlt
  4244. ){
  4245. Decimal *p;
  4246. int n, i;
  4247. const unsigned char *zIn;
  4248. int iExp = 0;
  4249. p = sqlite3_malloc( sizeof(*p) );
  4250. if( p==0 ) goto new_no_mem;
  4251. p->sign = 0;
  4252. p->oom = 0;
  4253. p->isInit = 1;
  4254. p->isNull = 0;
  4255. p->nDigit = 0;
  4256. p->nFrac = 0;
  4257. if( zAlt ){
  4258. n = nAlt,
  4259. zIn = zAlt;
  4260. }else{
  4261. if( sqlite3_value_type(pIn)==SQLITE_NULL ){
  4262. p->a = 0;
  4263. p->isNull = 1;
  4264. return p;
  4265. }
  4266. n = sqlite3_value_bytes(pIn);
  4267. zIn = sqlite3_value_text(pIn);
  4268. }
  4269. p->a = sqlite3_malloc64( n+1 );
  4270. if( p->a==0 ) goto new_no_mem;
  4271. for(i=0; isspace(zIn[i]); i++){}
  4272. if( zIn[i]=='-' ){
  4273. p->sign = 1;
  4274. i++;
  4275. }else if( zIn[i]=='+' ){
  4276. i++;
  4277. }
  4278. while( i<n && zIn[i]=='0' ) i++;
  4279. while( i<n ){
  4280. char c = zIn[i];
  4281. if( c>='0' && c<='9' ){
  4282. p->a[p->nDigit++] = c - '0';
  4283. }else if( c=='.' ){
  4284. p->nFrac = p->nDigit + 1;
  4285. }else if( c=='e' || c=='E' ){
  4286. int j = i+1;
  4287. int neg = 0;
  4288. if( j>=n ) break;
  4289. if( zIn[j]=='-' ){
  4290. neg = 1;
  4291. j++;
  4292. }else if( zIn[j]=='+' ){
  4293. j++;
  4294. }
  4295. while( j<n && iExp<1000000 ){
  4296. if( zIn[j]>='0' && zIn[j]<='9' ){
  4297. iExp = iExp*10 + zIn[j] - '0';
  4298. }
  4299. j++;
  4300. }
  4301. if( neg ) iExp = -iExp;
  4302. break;
  4303. }
  4304. i++;
  4305. }
  4306. if( p->nFrac ){
  4307. p->nFrac = p->nDigit - (p->nFrac - 1);
  4308. }
  4309. if( iExp>0 ){
  4310. if( p->nFrac>0 ){
  4311. if( iExp<=p->nFrac ){
  4312. p->nFrac -= iExp;
  4313. iExp = 0;
  4314. }else{
  4315. iExp -= p->nFrac;
  4316. p->nFrac = 0;
  4317. }
  4318. }
  4319. if( iExp>0 ){
  4320. p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
  4321. if( p->a==0 ) goto new_no_mem;
  4322. memset(p->a+p->nDigit, 0, iExp);
  4323. p->nDigit += iExp;
  4324. }
  4325. }else if( iExp<0 ){
  4326. int nExtra;
  4327. iExp = -iExp;
  4328. nExtra = p->nDigit - p->nFrac - 1;
  4329. if( nExtra ){
  4330. if( nExtra>=iExp ){
  4331. p->nFrac += iExp;
  4332. iExp = 0;
  4333. }else{
  4334. iExp -= nExtra;
  4335. p->nFrac = p->nDigit - 1;
  4336. }
  4337. }
  4338. if( iExp>0 ){
  4339. p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
  4340. if( p->a==0 ) goto new_no_mem;
  4341. memmove(p->a+iExp, p->a, p->nDigit);
  4342. memset(p->a, 0, iExp);
  4343. p->nDigit += iExp;
  4344. p->nFrac += iExp;
  4345. }
  4346. }
  4347. return p;
  4348. new_no_mem:
  4349. if( pCtx ) sqlite3_result_error_nomem(pCtx);
  4350. sqlite3_free(p);
  4351. return 0;
  4352. }
  4353. /*
  4354. ** Make the given Decimal the result.
  4355. */
  4356. static void decimal_result(sqlite3_context *pCtx, Decimal *p){
  4357. char *z;
  4358. int i, j;
  4359. int n;
  4360. if( p==0 || p->oom ){
  4361. sqlite3_result_error_nomem(pCtx);
  4362. return;
  4363. }
  4364. if( p->isNull ){
  4365. sqlite3_result_null(pCtx);
  4366. return;
  4367. }
  4368. z = sqlite3_malloc( p->nDigit+4 );
  4369. if( z==0 ){
  4370. sqlite3_result_error_nomem(pCtx);
  4371. return;
  4372. }
  4373. i = 0;
  4374. if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
  4375. p->sign = 0;
  4376. }
  4377. if( p->sign ){
  4378. z[0] = '-';
  4379. i = 1;
  4380. }
  4381. n = p->nDigit - p->nFrac;
  4382. if( n<=0 ){
  4383. z[i++] = '0';
  4384. }
  4385. j = 0;
  4386. while( n>1 && p->a[j]==0 ){
  4387. j++;
  4388. n--;
  4389. }
  4390. while( n>0 ){
  4391. z[i++] = p->a[j] + '0';
  4392. j++;
  4393. n--;
  4394. }
  4395. if( p->nFrac ){
  4396. z[i++] = '.';
  4397. do{
  4398. z[i++] = p->a[j] + '0';
  4399. j++;
  4400. }while( j<p->nDigit );
  4401. }
  4402. z[i] = 0;
  4403. sqlite3_result_text(pCtx, z, i, sqlite3_free);
  4404. }
  4405. /*
  4406. ** SQL Function: decimal(X)
  4407. **
  4408. ** Convert input X into decimal and then back into text
  4409. */
  4410. static void decimalFunc(
  4411. sqlite3_context *context,
  4412. int argc,
  4413. sqlite3_value **argv
  4414. ){
  4415. Decimal *p = decimal_new(context, argv[0], 0, 0);
  4416. UNUSED_PARAMETER(argc);
  4417. decimal_result(context, p);
  4418. decimal_free(p);
  4419. }
  4420. /*
  4421. ** Compare to Decimal objects. Return negative, 0, or positive if the
  4422. ** first object is less than, equal to, or greater than the second.
  4423. **
  4424. ** Preconditions for this routine:
  4425. **
  4426. ** pA!=0
  4427. ** pA->isNull==0
  4428. ** pB!=0
  4429. ** pB->isNull==0
  4430. */
  4431. static int decimal_cmp(const Decimal *pA, const Decimal *pB){
  4432. int nASig, nBSig, rc, n;
  4433. if( pA->sign!=pB->sign ){
  4434. return pA->sign ? -1 : +1;
  4435. }
  4436. if( pA->sign ){
  4437. const Decimal *pTemp = pA;
  4438. pA = pB;
  4439. pB = pTemp;
  4440. }
  4441. nASig = pA->nDigit - pA->nFrac;
  4442. nBSig = pB->nDigit - pB->nFrac;
  4443. if( nASig!=nBSig ){
  4444. return nASig - nBSig;
  4445. }
  4446. n = pA->nDigit;
  4447. if( n>pB->nDigit ) n = pB->nDigit;
  4448. rc = memcmp(pA->a, pB->a, n);
  4449. if( rc==0 ){
  4450. rc = pA->nDigit - pB->nDigit;
  4451. }
  4452. return rc;
  4453. }
  4454. /*
  4455. ** SQL Function: decimal_cmp(X, Y)
  4456. **
  4457. ** Return negative, zero, or positive if X is less then, equal to, or
  4458. ** greater than Y.
  4459. */
  4460. static void decimalCmpFunc(
  4461. sqlite3_context *context,
  4462. int argc,
  4463. sqlite3_value **argv
  4464. ){
  4465. Decimal *pA = 0, *pB = 0;
  4466. int rc;
  4467. UNUSED_PARAMETER(argc);
  4468. pA = decimal_new(context, argv[0], 0, 0);
  4469. if( pA==0 || pA->isNull ) goto cmp_done;
  4470. pB = decimal_new(context, argv[1], 0, 0);
  4471. if( pB==0 || pB->isNull ) goto cmp_done;
  4472. rc = decimal_cmp(pA, pB);
  4473. if( rc<0 ) rc = -1;
  4474. else if( rc>0 ) rc = +1;
  4475. sqlite3_result_int(context, rc);
  4476. cmp_done:
  4477. decimal_free(pA);
  4478. decimal_free(pB);
  4479. }
  4480. /*
  4481. ** Expand the Decimal so that it has a least nDigit digits and nFrac
  4482. ** digits to the right of the decimal point.
  4483. */
  4484. static void decimal_expand(Decimal *p, int nDigit, int nFrac){
  4485. int nAddSig;
  4486. int nAddFrac;
  4487. if( p==0 ) return;
  4488. nAddFrac = nFrac - p->nFrac;
  4489. nAddSig = (nDigit - p->nDigit) - nAddFrac;
  4490. if( nAddFrac==0 && nAddSig==0 ) return;
  4491. p->a = sqlite3_realloc64(p->a, nDigit+1);
  4492. if( p->a==0 ){
  4493. p->oom = 1;
  4494. return;
  4495. }
  4496. if( nAddSig ){
  4497. memmove(p->a+nAddSig, p->a, p->nDigit);
  4498. memset(p->a, 0, nAddSig);
  4499. p->nDigit += nAddSig;
  4500. }
  4501. if( nAddFrac ){
  4502. memset(p->a+p->nDigit, 0, nAddFrac);
  4503. p->nDigit += nAddFrac;
  4504. p->nFrac += nAddFrac;
  4505. }
  4506. }
  4507. /*
  4508. ** Add the value pB into pA.
  4509. **
  4510. ** Both pA and pB might become denormalized by this routine.
  4511. */
  4512. static void decimal_add(Decimal *pA, Decimal *pB){
  4513. int nSig, nFrac, nDigit;
  4514. int i, rc;
  4515. if( pA==0 ){
  4516. return;
  4517. }
  4518. if( pA->oom || pB==0 || pB->oom ){
  4519. pA->oom = 1;
  4520. return;
  4521. }
  4522. if( pA->isNull || pB->isNull ){
  4523. pA->isNull = 1;
  4524. return;
  4525. }
  4526. nSig = pA->nDigit - pA->nFrac;
  4527. if( nSig && pA->a[0]==0 ) nSig--;
  4528. if( nSig<pB->nDigit-pB->nFrac ){
  4529. nSig = pB->nDigit - pB->nFrac;
  4530. }
  4531. nFrac = pA->nFrac;
  4532. if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
  4533. nDigit = nSig + nFrac + 1;
  4534. decimal_expand(pA, nDigit, nFrac);
  4535. decimal_expand(pB, nDigit, nFrac);
  4536. if( pA->oom || pB->oom ){
  4537. pA->oom = 1;
  4538. }else{
  4539. if( pA->sign==pB->sign ){
  4540. int carry = 0;
  4541. for(i=nDigit-1; i>=0; i--){
  4542. int x = pA->a[i] + pB->a[i] + carry;
  4543. if( x>=10 ){
  4544. carry = 1;
  4545. pA->a[i] = x - 10;
  4546. }else{
  4547. carry = 0;
  4548. pA->a[i] = x;
  4549. }
  4550. }
  4551. }else{
  4552. signed char *aA, *aB;
  4553. int borrow = 0;
  4554. rc = memcmp(pA->a, pB->a, nDigit);
  4555. if( rc<0 ){
  4556. aA = pB->a;
  4557. aB = pA->a;
  4558. pA->sign = !pA->sign;
  4559. }else{
  4560. aA = pA->a;
  4561. aB = pB->a;
  4562. }
  4563. for(i=nDigit-1; i>=0; i--){
  4564. int x = aA[i] - aB[i] - borrow;
  4565. if( x<0 ){
  4566. pA->a[i] = x+10;
  4567. borrow = 1;
  4568. }else{
  4569. pA->a[i] = x;
  4570. borrow = 0;
  4571. }
  4572. }
  4573. }
  4574. }
  4575. }
  4576. /*
  4577. ** Compare text in decimal order.
  4578. */
  4579. static int decimalCollFunc(
  4580. void *notUsed,
  4581. int nKey1, const void *pKey1,
  4582. int nKey2, const void *pKey2
  4583. ){
  4584. const unsigned char *zA = (const unsigned char*)pKey1;
  4585. const unsigned char *zB = (const unsigned char*)pKey2;
  4586. Decimal *pA = decimal_new(0, 0, nKey1, zA);
  4587. Decimal *pB = decimal_new(0, 0, nKey2, zB);
  4588. int rc;
  4589. UNUSED_PARAMETER(notUsed);
  4590. if( pA==0 || pB==0 ){
  4591. rc = 0;
  4592. }else{
  4593. rc = decimal_cmp(pA, pB);
  4594. }
  4595. decimal_free(pA);
  4596. decimal_free(pB);
  4597. return rc;
  4598. }
  4599. /*
  4600. ** SQL Function: decimal_add(X, Y)
  4601. ** decimal_sub(X, Y)
  4602. **
  4603. ** Return the sum or difference of X and Y.
  4604. */
  4605. static void decimalAddFunc(
  4606. sqlite3_context *context,
  4607. int argc,
  4608. sqlite3_value **argv
  4609. ){
  4610. Decimal *pA = decimal_new(context, argv[0], 0, 0);
  4611. Decimal *pB = decimal_new(context, argv[1], 0, 0);
  4612. UNUSED_PARAMETER(argc);
  4613. decimal_add(pA, pB);
  4614. decimal_result(context, pA);
  4615. decimal_free(pA);
  4616. decimal_free(pB);
  4617. }
  4618. static void decimalSubFunc(
  4619. sqlite3_context *context,
  4620. int argc,
  4621. sqlite3_value **argv
  4622. ){
  4623. Decimal *pA = decimal_new(context, argv[0], 0, 0);
  4624. Decimal *pB = decimal_new(context, argv[1], 0, 0);
  4625. UNUSED_PARAMETER(argc);
  4626. if( pB ){
  4627. pB->sign = !pB->sign;
  4628. decimal_add(pA, pB);
  4629. decimal_result(context, pA);
  4630. }
  4631. decimal_free(pA);
  4632. decimal_free(pB);
  4633. }
  4634. /* Aggregate funcion: decimal_sum(X)
  4635. **
  4636. ** Works like sum() except that it uses decimal arithmetic for unlimited
  4637. ** precision.
  4638. */
  4639. static void decimalSumStep(
  4640. sqlite3_context *context,
  4641. int argc,
  4642. sqlite3_value **argv
  4643. ){
  4644. Decimal *p;
  4645. Decimal *pArg;
  4646. UNUSED_PARAMETER(argc);
  4647. p = sqlite3_aggregate_context(context, sizeof(*p));
  4648. if( p==0 ) return;
  4649. if( !p->isInit ){
  4650. p->isInit = 1;
  4651. p->a = sqlite3_malloc(2);
  4652. if( p->a==0 ){
  4653. p->oom = 1;
  4654. }else{
  4655. p->a[0] = 0;
  4656. }
  4657. p->nDigit = 1;
  4658. p->nFrac = 0;
  4659. }
  4660. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  4661. pArg = decimal_new(context, argv[0], 0, 0);
  4662. decimal_add(p, pArg);
  4663. decimal_free(pArg);
  4664. }
  4665. static void decimalSumInverse(
  4666. sqlite3_context *context,
  4667. int argc,
  4668. sqlite3_value **argv
  4669. ){
  4670. Decimal *p;
  4671. Decimal *pArg;
  4672. UNUSED_PARAMETER(argc);
  4673. p = sqlite3_aggregate_context(context, sizeof(*p));
  4674. if( p==0 ) return;
  4675. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  4676. pArg = decimal_new(context, argv[0], 0, 0);
  4677. if( pArg ) pArg->sign = !pArg->sign;
  4678. decimal_add(p, pArg);
  4679. decimal_free(pArg);
  4680. }
  4681. static void decimalSumValue(sqlite3_context *context){
  4682. Decimal *p = sqlite3_aggregate_context(context, 0);
  4683. if( p==0 ) return;
  4684. decimal_result(context, p);
  4685. }
  4686. static void decimalSumFinalize(sqlite3_context *context){
  4687. Decimal *p = sqlite3_aggregate_context(context, 0);
  4688. if( p==0 ) return;
  4689. decimal_result(context, p);
  4690. decimal_clear(p);
  4691. }
  4692. /*
  4693. ** SQL Function: decimal_mul(X, Y)
  4694. **
  4695. ** Return the product of X and Y.
  4696. **
  4697. ** All significant digits after the decimal point are retained.
  4698. ** Trailing zeros after the decimal point are omitted as long as
  4699. ** the number of digits after the decimal point is no less than
  4700. ** either the number of digits in either input.
  4701. */
  4702. static void decimalMulFunc(
  4703. sqlite3_context *context,
  4704. int argc,
  4705. sqlite3_value **argv
  4706. ){
  4707. Decimal *pA = decimal_new(context, argv[0], 0, 0);
  4708. Decimal *pB = decimal_new(context, argv[1], 0, 0);
  4709. signed char *acc = 0;
  4710. int i, j, k;
  4711. int minFrac;
  4712. UNUSED_PARAMETER(argc);
  4713. if( pA==0 || pA->oom || pA->isNull
  4714. || pB==0 || pB->oom || pB->isNull
  4715. ){
  4716. goto mul_end;
  4717. }
  4718. acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
  4719. if( acc==0 ){
  4720. sqlite3_result_error_nomem(context);
  4721. goto mul_end;
  4722. }
  4723. memset(acc, 0, pA->nDigit + pB->nDigit + 2);
  4724. minFrac = pA->nFrac;
  4725. if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
  4726. for(i=pA->nDigit-1; i>=0; i--){
  4727. signed char f = pA->a[i];
  4728. int carry = 0, x;
  4729. for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
  4730. x = acc[k] + f*pB->a[j] + carry;
  4731. acc[k] = x%10;
  4732. carry = x/10;
  4733. }
  4734. x = acc[k] + carry;
  4735. acc[k] = x%10;
  4736. acc[k-1] += x/10;
  4737. }
  4738. sqlite3_free(pA->a);
  4739. pA->a = acc;
  4740. acc = 0;
  4741. pA->nDigit += pB->nDigit + 2;
  4742. pA->nFrac += pB->nFrac;
  4743. pA->sign ^= pB->sign;
  4744. while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
  4745. pA->nFrac--;
  4746. pA->nDigit--;
  4747. }
  4748. decimal_result(context, pA);
  4749. mul_end:
  4750. sqlite3_free(acc);
  4751. decimal_free(pA);
  4752. decimal_free(pB);
  4753. }
  4754. #ifdef _WIN32
  4755. #endif
  4756. int sqlite3_decimal_init(
  4757. sqlite3 *db,
  4758. char **pzErrMsg,
  4759. const sqlite3_api_routines *pApi
  4760. ){
  4761. int rc = SQLITE_OK;
  4762. static const struct {
  4763. const char *zFuncName;
  4764. int nArg;
  4765. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  4766. } aFunc[] = {
  4767. { "decimal", 1, decimalFunc },
  4768. { "decimal_cmp", 2, decimalCmpFunc },
  4769. { "decimal_add", 2, decimalAddFunc },
  4770. { "decimal_sub", 2, decimalSubFunc },
  4771. { "decimal_mul", 2, decimalMulFunc },
  4772. };
  4773. unsigned int i;
  4774. (void)pzErrMsg; /* Unused parameter */
  4775. SQLITE_EXTENSION_INIT2(pApi);
  4776. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  4777. rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
  4778. SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
  4779. 0, aFunc[i].xFunc, 0, 0);
  4780. }
  4781. if( rc==SQLITE_OK ){
  4782. rc = sqlite3_create_window_function(db, "decimal_sum", 1,
  4783. SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
  4784. decimalSumStep, decimalSumFinalize,
  4785. decimalSumValue, decimalSumInverse, 0);
  4786. }
  4787. if( rc==SQLITE_OK ){
  4788. rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
  4789. 0, decimalCollFunc);
  4790. }
  4791. return rc;
  4792. }
  4793. /************************* End ../ext/misc/decimal.c ********************/
  4794. /************************* Begin ../ext/misc/ieee754.c ******************/
  4795. /*
  4796. ** 2013-04-17
  4797. **
  4798. ** The author disclaims copyright to this source code. In place of
  4799. ** a legal notice, here is a blessing:
  4800. **
  4801. ** May you do good and not evil.
  4802. ** May you find forgiveness for yourself and forgive others.
  4803. ** May you share freely, never taking more than you give.
  4804. **
  4805. ******************************************************************************
  4806. **
  4807. ** This SQLite extension implements functions for the exact display
  4808. ** and input of IEEE754 Binary64 floating-point numbers.
  4809. **
  4810. ** ieee754(X)
  4811. ** ieee754(Y,Z)
  4812. **
  4813. ** In the first form, the value X should be a floating-point number.
  4814. ** The function will return a string of the form 'ieee754(Y,Z)' where
  4815. ** Y and Z are integers such that X==Y*pow(2,Z).
  4816. **
  4817. ** In the second form, Y and Z are integers which are the mantissa and
  4818. ** base-2 exponent of a new floating point number. The function returns
  4819. ** a floating-point value equal to Y*pow(2,Z).
  4820. **
  4821. ** Examples:
  4822. **
  4823. ** ieee754(2.0) -> 'ieee754(2,0)'
  4824. ** ieee754(45.25) -> 'ieee754(181,-2)'
  4825. ** ieee754(2, 0) -> 2.0
  4826. ** ieee754(181, -2) -> 45.25
  4827. **
  4828. ** Two additional functions break apart the one-argument ieee754()
  4829. ** result into separate integer values:
  4830. **
  4831. ** ieee754_mantissa(45.25) -> 181
  4832. ** ieee754_exponent(45.25) -> -2
  4833. **
  4834. ** These functions convert binary64 numbers into blobs and back again.
  4835. **
  4836. ** ieee754_from_blob(x'3ff0000000000000') -> 1.0
  4837. ** ieee754_to_blob(1.0) -> x'3ff0000000000000'
  4838. **
  4839. ** In all single-argument functions, if the argument is an 8-byte blob
  4840. ** then that blob is interpreted as a big-endian binary64 value.
  4841. **
  4842. **
  4843. ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
  4844. ** -----------------------------------------------
  4845. **
  4846. ** This extension in combination with the separate 'decimal' extension
  4847. ** can be used to compute the exact decimal representation of binary64
  4848. ** values. To begin, first compute a table of exponent values:
  4849. **
  4850. ** CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
  4851. ** WITH RECURSIVE c(x,v) AS (
  4852. ** VALUES(0,'1')
  4853. ** UNION ALL
  4854. ** SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
  4855. ** ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
  4856. ** WITH RECURSIVE c(x,v) AS (
  4857. ** VALUES(-1,'0.5')
  4858. ** UNION ALL
  4859. ** SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
  4860. ** ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
  4861. **
  4862. ** Then, to compute the exact decimal representation of a floating
  4863. ** point value (the value 47.49 is used in the example) do:
  4864. **
  4865. ** WITH c(n) AS (VALUES(47.49))
  4866. ** ---------------^^^^^---- Replace with whatever you want
  4867. ** SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
  4868. ** FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
  4869. **
  4870. ** Here is a query to show various boundry values for the binary64
  4871. ** number format:
  4872. **
  4873. ** WITH c(name,bin) AS (VALUES
  4874. ** ('minimum positive value', x'0000000000000001'),
  4875. ** ('maximum subnormal value', x'000fffffffffffff'),
  4876. ** ('mininum positive nornal value', x'0010000000000000'),
  4877. ** ('maximum value', x'7fefffffffffffff'))
  4878. ** SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
  4879. ** FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
  4880. **
  4881. */
  4882. /* #include "sqlite3ext.h" */
  4883. SQLITE_EXTENSION_INIT1
  4884. #include <assert.h>
  4885. #include <string.h>
  4886. /* Mark a function parameter as unused, to suppress nuisance compiler
  4887. ** warnings. */
  4888. #ifndef UNUSED_PARAMETER
  4889. # define UNUSED_PARAMETER(X) (void)(X)
  4890. #endif
  4891. /*
  4892. ** Implementation of the ieee754() function
  4893. */
  4894. static void ieee754func(
  4895. sqlite3_context *context,
  4896. int argc,
  4897. sqlite3_value **argv
  4898. ){
  4899. if( argc==1 ){
  4900. sqlite3_int64 m, a;
  4901. double r;
  4902. int e;
  4903. int isNeg;
  4904. char zResult[100];
  4905. assert( sizeof(m)==sizeof(r) );
  4906. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  4907. && sqlite3_value_bytes(argv[0])==sizeof(r)
  4908. ){
  4909. const unsigned char *x = sqlite3_value_blob(argv[0]);
  4910. unsigned int i;
  4911. sqlite3_uint64 v = 0;
  4912. for(i=0; i<sizeof(r); i++){
  4913. v = (v<<8) | x[i];
  4914. }
  4915. memcpy(&r, &v, sizeof(r));
  4916. }else{
  4917. r = sqlite3_value_double(argv[0]);
  4918. }
  4919. if( r<0.0 ){
  4920. isNeg = 1;
  4921. r = -r;
  4922. }else{
  4923. isNeg = 0;
  4924. }
  4925. memcpy(&a,&r,sizeof(a));
  4926. if( a==0 ){
  4927. e = 0;
  4928. m = 0;
  4929. }else{
  4930. e = a>>52;
  4931. m = a & ((((sqlite3_int64)1)<<52)-1);
  4932. if( e==0 ){
  4933. m <<= 1;
  4934. }else{
  4935. m |= ((sqlite3_int64)1)<<52;
  4936. }
  4937. while( e<1075 && m>0 && (m&1)==0 ){
  4938. m >>= 1;
  4939. e++;
  4940. }
  4941. if( isNeg ) m = -m;
  4942. }
  4943. switch( *(int*)sqlite3_user_data(context) ){
  4944. case 0:
  4945. sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
  4946. m, e-1075);
  4947. sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
  4948. break;
  4949. case 1:
  4950. sqlite3_result_int64(context, m);
  4951. break;
  4952. case 2:
  4953. sqlite3_result_int(context, e-1075);
  4954. break;
  4955. }
  4956. }else{
  4957. sqlite3_int64 m, e, a;
  4958. double r;
  4959. int isNeg = 0;
  4960. m = sqlite3_value_int64(argv[0]);
  4961. e = sqlite3_value_int64(argv[1]);
  4962. /* Limit the range of e. Ticket 22dea1cfdb9151e4 2021-03-02 */
  4963. if( e>10000 ){
  4964. e = 10000;
  4965. }else if( e<-10000 ){
  4966. e = -10000;
  4967. }
  4968. if( m<0 ){
  4969. isNeg = 1;
  4970. m = -m;
  4971. if( m<0 ) return;
  4972. }else if( m==0 && e>-1000 && e<1000 ){
  4973. sqlite3_result_double(context, 0.0);
  4974. return;
  4975. }
  4976. while( (m>>32)&0xffe00000 ){
  4977. m >>= 1;
  4978. e++;
  4979. }
  4980. while( m!=0 && ((m>>32)&0xfff00000)==0 ){
  4981. m <<= 1;
  4982. e--;
  4983. }
  4984. e += 1075;
  4985. if( e<=0 ){
  4986. /* Subnormal */
  4987. if( 1-e >= 64 ){
  4988. m = 0;
  4989. }else{
  4990. m >>= 1-e;
  4991. }
  4992. e = 0;
  4993. }else if( e>0x7ff ){
  4994. e = 0x7ff;
  4995. }
  4996. a = m & ((((sqlite3_int64)1)<<52)-1);
  4997. a |= e<<52;
  4998. if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
  4999. memcpy(&r, &a, sizeof(r));
  5000. sqlite3_result_double(context, r);
  5001. }
  5002. }
  5003. /*
  5004. ** Functions to convert between blobs and floats.
  5005. */
  5006. static void ieee754func_from_blob(
  5007. sqlite3_context *context,
  5008. int argc,
  5009. sqlite3_value **argv
  5010. ){
  5011. UNUSED_PARAMETER(argc);
  5012. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  5013. && sqlite3_value_bytes(argv[0])==sizeof(double)
  5014. ){
  5015. double r;
  5016. const unsigned char *x = sqlite3_value_blob(argv[0]);
  5017. unsigned int i;
  5018. sqlite3_uint64 v = 0;
  5019. for(i=0; i<sizeof(r); i++){
  5020. v = (v<<8) | x[i];
  5021. }
  5022. memcpy(&r, &v, sizeof(r));
  5023. sqlite3_result_double(context, r);
  5024. }
  5025. }
  5026. static void ieee754func_to_blob(
  5027. sqlite3_context *context,
  5028. int argc,
  5029. sqlite3_value **argv
  5030. ){
  5031. UNUSED_PARAMETER(argc);
  5032. if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
  5033. || sqlite3_value_type(argv[0])==SQLITE_INTEGER
  5034. ){
  5035. double r = sqlite3_value_double(argv[0]);
  5036. sqlite3_uint64 v;
  5037. unsigned char a[sizeof(r)];
  5038. unsigned int i;
  5039. memcpy(&v, &r, sizeof(r));
  5040. for(i=1; i<=sizeof(r); i++){
  5041. a[sizeof(r)-i] = v&0xff;
  5042. v >>= 8;
  5043. }
  5044. sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
  5045. }
  5046. }
  5047. #ifdef _WIN32
  5048. #endif
  5049. int sqlite3_ieee_init(
  5050. sqlite3 *db,
  5051. char **pzErrMsg,
  5052. const sqlite3_api_routines *pApi
  5053. ){
  5054. static const struct {
  5055. char *zFName;
  5056. int nArg;
  5057. int iAux;
  5058. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  5059. } aFunc[] = {
  5060. { "ieee754", 1, 0, ieee754func },
  5061. { "ieee754", 2, 0, ieee754func },
  5062. { "ieee754_mantissa", 1, 1, ieee754func },
  5063. { "ieee754_exponent", 1, 2, ieee754func },
  5064. { "ieee754_to_blob", 1, 0, ieee754func_to_blob },
  5065. { "ieee754_from_blob", 1, 0, ieee754func_from_blob },
  5066. };
  5067. unsigned int i;
  5068. int rc = SQLITE_OK;
  5069. SQLITE_EXTENSION_INIT2(pApi);
  5070. (void)pzErrMsg; /* Unused parameter */
  5071. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  5072. rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
  5073. SQLITE_UTF8|SQLITE_INNOCUOUS,
  5074. (void*)&aFunc[i].iAux,
  5075. aFunc[i].xFunc, 0, 0);
  5076. }
  5077. return rc;
  5078. }
  5079. /************************* End ../ext/misc/ieee754.c ********************/
  5080. /************************* Begin ../ext/misc/series.c ******************/
  5081. /*
  5082. ** 2015-08-18
  5083. **
  5084. ** The author disclaims copyright to this source code. In place of
  5085. ** a legal notice, here is a blessing:
  5086. **
  5087. ** May you do good and not evil.
  5088. ** May you find forgiveness for yourself and forgive others.
  5089. ** May you share freely, never taking more than you give.
  5090. **
  5091. *************************************************************************
  5092. **
  5093. ** This file demonstrates how to create a table-valued-function using
  5094. ** a virtual table. This demo implements the generate_series() function
  5095. ** which gives similar results to the eponymous function in PostgreSQL.
  5096. ** Examples:
  5097. **
  5098. ** SELECT * FROM generate_series(0,100,5);
  5099. **
  5100. ** The query above returns integers from 0 through 100 counting by steps
  5101. ** of 5.
  5102. **
  5103. ** SELECT * FROM generate_series(0,100);
  5104. **
  5105. ** Integers from 0 through 100 with a step size of 1.
  5106. **
  5107. ** SELECT * FROM generate_series(20) LIMIT 10;
  5108. **
  5109. ** Integers 20 through 29.
  5110. **
  5111. ** HOW IT WORKS
  5112. **
  5113. ** The generate_series "function" is really a virtual table with the
  5114. ** following schema:
  5115. **
  5116. ** CREATE TABLE generate_series(
  5117. ** value,
  5118. ** start HIDDEN,
  5119. ** stop HIDDEN,
  5120. ** step HIDDEN
  5121. ** );
  5122. **
  5123. ** Function arguments in queries against this virtual table are translated
  5124. ** into equality constraints against successive hidden columns. In other
  5125. ** words, the following pairs of queries are equivalent to each other:
  5126. **
  5127. ** SELECT * FROM generate_series(0,100,5);
  5128. ** SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
  5129. **
  5130. ** SELECT * FROM generate_series(0,100);
  5131. ** SELECT * FROM generate_series WHERE start=0 AND stop=100;
  5132. **
  5133. ** SELECT * FROM generate_series(20) LIMIT 10;
  5134. ** SELECT * FROM generate_series WHERE start=20 LIMIT 10;
  5135. **
  5136. ** The generate_series virtual table implementation leaves the xCreate method
  5137. ** set to NULL. This means that it is not possible to do a CREATE VIRTUAL
  5138. ** TABLE command with "generate_series" as the USING argument. Instead, there
  5139. ** is a single generate_series virtual table that is always available without
  5140. ** having to be created first.
  5141. **
  5142. ** The xBestIndex method looks for equality constraints against the hidden
  5143. ** start, stop, and step columns, and if present, it uses those constraints
  5144. ** to bound the sequence of generated values. If the equality constraints
  5145. ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
  5146. ** xBestIndex returns a small cost when both start and stop are available,
  5147. ** and a very large cost if either start or stop are unavailable. This
  5148. ** encourages the query planner to order joins such that the bounds of the
  5149. ** series are well-defined.
  5150. */
  5151. /* #include "sqlite3ext.h" */
  5152. SQLITE_EXTENSION_INIT1
  5153. #include <assert.h>
  5154. #include <string.h>
  5155. #ifndef SQLITE_OMIT_VIRTUALTABLE
  5156. /* series_cursor is a subclass of sqlite3_vtab_cursor which will
  5157. ** serve as the underlying representation of a cursor that scans
  5158. ** over rows of the result
  5159. */
  5160. typedef struct series_cursor series_cursor;
  5161. struct series_cursor {
  5162. sqlite3_vtab_cursor base; /* Base class - must be first */
  5163. int isDesc; /* True to count down rather than up */
  5164. sqlite3_int64 iRowid; /* The rowid */
  5165. sqlite3_int64 iValue; /* Current value ("value") */
  5166. sqlite3_int64 mnValue; /* Mimimum value ("start") */
  5167. sqlite3_int64 mxValue; /* Maximum value ("stop") */
  5168. sqlite3_int64 iStep; /* Increment ("step") */
  5169. };
  5170. /*
  5171. ** The seriesConnect() method is invoked to create a new
  5172. ** series_vtab that describes the generate_series virtual table.
  5173. **
  5174. ** Think of this routine as the constructor for series_vtab objects.
  5175. **
  5176. ** All this routine needs to do is:
  5177. **
  5178. ** (1) Allocate the series_vtab object and initialize all fields.
  5179. **
  5180. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  5181. ** result set of queries against generate_series will look like.
  5182. */
  5183. static int seriesConnect(
  5184. sqlite3 *db,
  5185. void *pUnused,
  5186. int argcUnused, const char *const*argvUnused,
  5187. sqlite3_vtab **ppVtab,
  5188. char **pzErrUnused
  5189. ){
  5190. sqlite3_vtab *pNew;
  5191. int rc;
  5192. /* Column numbers */
  5193. #define SERIES_COLUMN_VALUE 0
  5194. #define SERIES_COLUMN_START 1
  5195. #define SERIES_COLUMN_STOP 2
  5196. #define SERIES_COLUMN_STEP 3
  5197. (void)pUnused;
  5198. (void)argcUnused;
  5199. (void)argvUnused;
  5200. (void)pzErrUnused;
  5201. rc = sqlite3_declare_vtab(db,
  5202. "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
  5203. if( rc==SQLITE_OK ){
  5204. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  5205. if( pNew==0 ) return SQLITE_NOMEM;
  5206. memset(pNew, 0, sizeof(*pNew));
  5207. sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
  5208. }
  5209. return rc;
  5210. }
  5211. /*
  5212. ** This method is the destructor for series_cursor objects.
  5213. */
  5214. static int seriesDisconnect(sqlite3_vtab *pVtab){
  5215. sqlite3_free(pVtab);
  5216. return SQLITE_OK;
  5217. }
  5218. /*
  5219. ** Constructor for a new series_cursor object.
  5220. */
  5221. static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
  5222. series_cursor *pCur;
  5223. (void)pUnused;
  5224. pCur = sqlite3_malloc( sizeof(*pCur) );
  5225. if( pCur==0 ) return SQLITE_NOMEM;
  5226. memset(pCur, 0, sizeof(*pCur));
  5227. *ppCursor = &pCur->base;
  5228. return SQLITE_OK;
  5229. }
  5230. /*
  5231. ** Destructor for a series_cursor.
  5232. */
  5233. static int seriesClose(sqlite3_vtab_cursor *cur){
  5234. sqlite3_free(cur);
  5235. return SQLITE_OK;
  5236. }
  5237. /*
  5238. ** Advance a series_cursor to its next row of output.
  5239. */
  5240. static int seriesNext(sqlite3_vtab_cursor *cur){
  5241. series_cursor *pCur = (series_cursor*)cur;
  5242. if( pCur->isDesc ){
  5243. pCur->iValue -= pCur->iStep;
  5244. }else{
  5245. pCur->iValue += pCur->iStep;
  5246. }
  5247. pCur->iRowid++;
  5248. return SQLITE_OK;
  5249. }
  5250. /*
  5251. ** Return values of columns for the row at which the series_cursor
  5252. ** is currently pointing.
  5253. */
  5254. static int seriesColumn(
  5255. sqlite3_vtab_cursor *cur, /* The cursor */
  5256. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  5257. int i /* Which column to return */
  5258. ){
  5259. series_cursor *pCur = (series_cursor*)cur;
  5260. sqlite3_int64 x = 0;
  5261. switch( i ){
  5262. case SERIES_COLUMN_START: x = pCur->mnValue; break;
  5263. case SERIES_COLUMN_STOP: x = pCur->mxValue; break;
  5264. case SERIES_COLUMN_STEP: x = pCur->iStep; break;
  5265. default: x = pCur->iValue; break;
  5266. }
  5267. sqlite3_result_int64(ctx, x);
  5268. return SQLITE_OK;
  5269. }
  5270. /*
  5271. ** Return the rowid for the current row. In this implementation, the
  5272. ** first row returned is assigned rowid value 1, and each subsequent
  5273. ** row a value 1 more than that of the previous.
  5274. */
  5275. static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  5276. series_cursor *pCur = (series_cursor*)cur;
  5277. *pRowid = pCur->iRowid;
  5278. return SQLITE_OK;
  5279. }
  5280. /*
  5281. ** Return TRUE if the cursor has been moved off of the last
  5282. ** row of output.
  5283. */
  5284. static int seriesEof(sqlite3_vtab_cursor *cur){
  5285. series_cursor *pCur = (series_cursor*)cur;
  5286. if( pCur->isDesc ){
  5287. return pCur->iValue < pCur->mnValue;
  5288. }else{
  5289. return pCur->iValue > pCur->mxValue;
  5290. }
  5291. }
  5292. /* True to cause run-time checking of the start=, stop=, and/or step=
  5293. ** parameters. The only reason to do this is for testing the
  5294. ** constraint checking logic for virtual tables in the SQLite core.
  5295. */
  5296. #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
  5297. # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
  5298. #endif
  5299. /*
  5300. ** This method is called to "rewind" the series_cursor object back
  5301. ** to the first row of output. This method is always called at least
  5302. ** once prior to any call to seriesColumn() or seriesRowid() or
  5303. ** seriesEof().
  5304. **
  5305. ** The query plan selected by seriesBestIndex is passed in the idxNum
  5306. ** parameter. (idxStr is not used in this implementation.) idxNum
  5307. ** is a bitmask showing which constraints are available:
  5308. **
  5309. ** 1: start=VALUE
  5310. ** 2: stop=VALUE
  5311. ** 4: step=VALUE
  5312. **
  5313. ** Also, if bit 8 is set, that means that the series should be output
  5314. ** in descending order rather than in ascending order. If bit 16 is
  5315. ** set, then output must appear in ascending order.
  5316. **
  5317. ** This routine should initialize the cursor and position it so that it
  5318. ** is pointing at the first row, or pointing off the end of the table
  5319. ** (so that seriesEof() will return true) if the table is empty.
  5320. */
  5321. static int seriesFilter(
  5322. sqlite3_vtab_cursor *pVtabCursor,
  5323. int idxNum, const char *idxStrUnused,
  5324. int argc, sqlite3_value **argv
  5325. ){
  5326. series_cursor *pCur = (series_cursor *)pVtabCursor;
  5327. int i = 0;
  5328. (void)idxStrUnused;
  5329. if( idxNum & 1 ){
  5330. pCur->mnValue = sqlite3_value_int64(argv[i++]);
  5331. }else{
  5332. pCur->mnValue = 0;
  5333. }
  5334. if( idxNum & 2 ){
  5335. pCur->mxValue = sqlite3_value_int64(argv[i++]);
  5336. }else{
  5337. pCur->mxValue = 0xffffffff;
  5338. }
  5339. if( idxNum & 4 ){
  5340. pCur->iStep = sqlite3_value_int64(argv[i++]);
  5341. if( pCur->iStep==0 ){
  5342. pCur->iStep = 1;
  5343. }else if( pCur->iStep<0 ){
  5344. pCur->iStep = -pCur->iStep;
  5345. if( (idxNum & 16)==0 ) idxNum |= 8;
  5346. }
  5347. }else{
  5348. pCur->iStep = 1;
  5349. }
  5350. for(i=0; i<argc; i++){
  5351. if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
  5352. /* If any of the constraints have a NULL value, then return no rows.
  5353. ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
  5354. pCur->mnValue = 1;
  5355. pCur->mxValue = 0;
  5356. break;
  5357. }
  5358. }
  5359. if( idxNum & 8 ){
  5360. pCur->isDesc = 1;
  5361. pCur->iValue = pCur->mxValue;
  5362. if( pCur->iStep>0 ){
  5363. pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
  5364. }
  5365. }else{
  5366. pCur->isDesc = 0;
  5367. pCur->iValue = pCur->mnValue;
  5368. }
  5369. pCur->iRowid = 1;
  5370. return SQLITE_OK;
  5371. }
  5372. /*
  5373. ** SQLite will invoke this method one or more times while planning a query
  5374. ** that uses the generate_series virtual table. This routine needs to create
  5375. ** a query plan for each invocation and compute an estimated cost for that
  5376. ** plan.
  5377. **
  5378. ** In this implementation idxNum is used to represent the
  5379. ** query plan. idxStr is unused.
  5380. **
  5381. ** The query plan is represented by bits in idxNum:
  5382. **
  5383. ** (1) start = $value -- constraint exists
  5384. ** (2) stop = $value -- constraint exists
  5385. ** (4) step = $value -- constraint exists
  5386. ** (8) output in descending order
  5387. */
  5388. static int seriesBestIndex(
  5389. sqlite3_vtab *pVTab,
  5390. sqlite3_index_info *pIdxInfo
  5391. ){
  5392. int i, j; /* Loop over constraints */
  5393. int idxNum = 0; /* The query plan bitmask */
  5394. int bStartSeen = 0; /* EQ constraint seen on the START column */
  5395. int unusableMask = 0; /* Mask of unusable constraints */
  5396. int nArg = 0; /* Number of arguments that seriesFilter() expects */
  5397. int aIdx[3]; /* Constraints on start, stop, and step */
  5398. const struct sqlite3_index_constraint *pConstraint;
  5399. /* This implementation assumes that the start, stop, and step columns
  5400. ** are the last three columns in the virtual table. */
  5401. assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
  5402. assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
  5403. aIdx[0] = aIdx[1] = aIdx[2] = -1;
  5404. pConstraint = pIdxInfo->aConstraint;
  5405. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  5406. int iCol; /* 0 for start, 1 for stop, 2 for step */
  5407. int iMask; /* bitmask for those column */
  5408. if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
  5409. iCol = pConstraint->iColumn - SERIES_COLUMN_START;
  5410. assert( iCol>=0 && iCol<=2 );
  5411. iMask = 1 << iCol;
  5412. if( iCol==0 ) bStartSeen = 1;
  5413. if( pConstraint->usable==0 ){
  5414. unusableMask |= iMask;
  5415. continue;
  5416. }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  5417. idxNum |= iMask;
  5418. aIdx[iCol] = i;
  5419. }
  5420. }
  5421. for(i=0; i<3; i++){
  5422. if( (j = aIdx[i])>=0 ){
  5423. pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
  5424. pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
  5425. }
  5426. }
  5427. /* The current generate_column() implementation requires at least one
  5428. ** argument (the START value). Legacy versions assumed START=0 if the
  5429. ** first argument was omitted. Compile with -DZERO_ARGUMENT_GENERATE_SERIES
  5430. ** to obtain the legacy behavior */
  5431. #ifndef ZERO_ARGUMENT_GENERATE_SERIES
  5432. if( !bStartSeen ){
  5433. sqlite3_free(pVTab->zErrMsg);
  5434. pVTab->zErrMsg = sqlite3_mprintf(
  5435. "first argument to \"generate_series()\" missing or unusable");
  5436. return SQLITE_ERROR;
  5437. }
  5438. #endif
  5439. if( (unusableMask & ~idxNum)!=0 ){
  5440. /* The start, stop, and step columns are inputs. Therefore if there
  5441. ** are unusable constraints on any of start, stop, or step then
  5442. ** this plan is unusable */
  5443. return SQLITE_CONSTRAINT;
  5444. }
  5445. if( (idxNum & 3)==3 ){
  5446. /* Both start= and stop= boundaries are available. This is the
  5447. ** the preferred case */
  5448. pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
  5449. pIdxInfo->estimatedRows = 1000;
  5450. if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
  5451. if( pIdxInfo->aOrderBy[0].desc ){
  5452. idxNum |= 8;
  5453. }else{
  5454. idxNum |= 16;
  5455. }
  5456. pIdxInfo->orderByConsumed = 1;
  5457. }
  5458. }else{
  5459. /* If either boundary is missing, we have to generate a huge span
  5460. ** of numbers. Make this case very expensive so that the query
  5461. ** planner will work hard to avoid it. */
  5462. pIdxInfo->estimatedRows = 2147483647;
  5463. }
  5464. pIdxInfo->idxNum = idxNum;
  5465. return SQLITE_OK;
  5466. }
  5467. /*
  5468. ** This following structure defines all the methods for the
  5469. ** generate_series virtual table.
  5470. */
  5471. static sqlite3_module seriesModule = {
  5472. 0, /* iVersion */
  5473. 0, /* xCreate */
  5474. seriesConnect, /* xConnect */
  5475. seriesBestIndex, /* xBestIndex */
  5476. seriesDisconnect, /* xDisconnect */
  5477. 0, /* xDestroy */
  5478. seriesOpen, /* xOpen - open a cursor */
  5479. seriesClose, /* xClose - close a cursor */
  5480. seriesFilter, /* xFilter - configure scan constraints */
  5481. seriesNext, /* xNext - advance a cursor */
  5482. seriesEof, /* xEof - check for end of scan */
  5483. seriesColumn, /* xColumn - read data */
  5484. seriesRowid, /* xRowid - read data */
  5485. 0, /* xUpdate */
  5486. 0, /* xBegin */
  5487. 0, /* xSync */
  5488. 0, /* xCommit */
  5489. 0, /* xRollback */
  5490. 0, /* xFindMethod */
  5491. 0, /* xRename */
  5492. 0, /* xSavepoint */
  5493. 0, /* xRelease */
  5494. 0, /* xRollbackTo */
  5495. 0 /* xShadowName */
  5496. };
  5497. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  5498. #ifdef _WIN32
  5499. #endif
  5500. int sqlite3_series_init(
  5501. sqlite3 *db,
  5502. char **pzErrMsg,
  5503. const sqlite3_api_routines *pApi
  5504. ){
  5505. int rc = SQLITE_OK;
  5506. SQLITE_EXTENSION_INIT2(pApi);
  5507. #ifndef SQLITE_OMIT_VIRTUALTABLE
  5508. if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
  5509. *pzErrMsg = sqlite3_mprintf(
  5510. "generate_series() requires SQLite 3.8.12 or later");
  5511. return SQLITE_ERROR;
  5512. }
  5513. rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
  5514. #endif
  5515. return rc;
  5516. }
  5517. /************************* End ../ext/misc/series.c ********************/
  5518. /************************* Begin ../ext/misc/regexp.c ******************/
  5519. /*
  5520. ** 2012-11-13
  5521. **
  5522. ** The author disclaims copyright to this source code. In place of
  5523. ** a legal notice, here is a blessing:
  5524. **
  5525. ** May you do good and not evil.
  5526. ** May you find forgiveness for yourself and forgive others.
  5527. ** May you share freely, never taking more than you give.
  5528. **
  5529. ******************************************************************************
  5530. **
  5531. ** The code in this file implements a compact but reasonably
  5532. ** efficient regular-expression matcher for posix extended regular
  5533. ** expressions against UTF8 text.
  5534. **
  5535. ** This file is an SQLite extension. It registers a single function
  5536. ** named "regexp(A,B)" where A is the regular expression and B is the
  5537. ** string to be matched. By registering this function, SQLite will also
  5538. ** then implement the "B regexp A" operator. Note that with the function
  5539. ** the regular expression comes first, but with the operator it comes
  5540. ** second.
  5541. **
  5542. ** The following regular expression syntax is supported:
  5543. **
  5544. ** X* zero or more occurrences of X
  5545. ** X+ one or more occurrences of X
  5546. ** X? zero or one occurrences of X
  5547. ** X{p,q} between p and q occurrences of X
  5548. ** (X) match X
  5549. ** X|Y X or Y
  5550. ** ^X X occurring at the beginning of the string
  5551. ** X$ X occurring at the end of the string
  5552. ** . Match any single character
  5553. ** \c Character c where c is one of \{}()[]|*+?.
  5554. ** \c C-language escapes for c in afnrtv. ex: \t or \n
  5555. ** \uXXXX Where XXXX is exactly 4 hex digits, unicode value XXXX
  5556. ** \xXX Where XX is exactly 2 hex digits, unicode value XX
  5557. ** [abc] Any single character from the set abc
  5558. ** [^abc] Any single character not in the set abc
  5559. ** [a-z] Any single character in the range a-z
  5560. ** [^a-z] Any single character not in the range a-z
  5561. ** \b Word boundary
  5562. ** \w Word character. [A-Za-z0-9_]
  5563. ** \W Non-word character
  5564. ** \d Digit
  5565. ** \D Non-digit
  5566. ** \s Whitespace character
  5567. ** \S Non-whitespace character
  5568. **
  5569. ** A nondeterministic finite automaton (NFA) is used for matching, so the
  5570. ** performance is bounded by O(N*M) where N is the size of the regular
  5571. ** expression and M is the size of the input string. The matcher never
  5572. ** exhibits exponential behavior. Note that the X{p,q} operator expands
  5573. ** to p copies of X following by q-p copies of X? and that the size of the
  5574. ** regular expression in the O(N*M) performance bound is computed after
  5575. ** this expansion.
  5576. */
  5577. #include <string.h>
  5578. #include <stdlib.h>
  5579. /* #include "sqlite3ext.h" */
  5580. SQLITE_EXTENSION_INIT1
  5581. /*
  5582. ** The following #defines change the names of some functions implemented in
  5583. ** this file to prevent name collisions with C-library functions of the
  5584. ** same name.
  5585. */
  5586. #define re_match sqlite3re_match
  5587. #define re_compile sqlite3re_compile
  5588. #define re_free sqlite3re_free
  5589. /* The end-of-input character */
  5590. #define RE_EOF 0 /* End of input */
  5591. /* The NFA is implemented as sequence of opcodes taken from the following
  5592. ** set. Each opcode has a single integer argument.
  5593. */
  5594. #define RE_OP_MATCH 1 /* Match the one character in the argument */
  5595. #define RE_OP_ANY 2 /* Match any one character. (Implements ".") */
  5596. #define RE_OP_ANYSTAR 3 /* Special optimized version of .* */
  5597. #define RE_OP_FORK 4 /* Continue to both next and opcode at iArg */
  5598. #define RE_OP_GOTO 5 /* Jump to opcode at iArg */
  5599. #define RE_OP_ACCEPT 6 /* Halt and indicate a successful match */
  5600. #define RE_OP_CC_INC 7 /* Beginning of a [...] character class */
  5601. #define RE_OP_CC_EXC 8 /* Beginning of a [^...] character class */
  5602. #define RE_OP_CC_VALUE 9 /* Single value in a character class */
  5603. #define RE_OP_CC_RANGE 10 /* Range of values in a character class */
  5604. #define RE_OP_WORD 11 /* Perl word character [A-Za-z0-9_] */
  5605. #define RE_OP_NOTWORD 12 /* Not a perl word character */
  5606. #define RE_OP_DIGIT 13 /* digit: [0-9] */
  5607. #define RE_OP_NOTDIGIT 14 /* Not a digit */
  5608. #define RE_OP_SPACE 15 /* space: [ \t\n\r\v\f] */
  5609. #define RE_OP_NOTSPACE 16 /* Not a digit */
  5610. #define RE_OP_BOUNDARY 17 /* Boundary between word and non-word */
  5611. /* Each opcode is a "state" in the NFA */
  5612. typedef unsigned short ReStateNumber;
  5613. /* Because this is an NFA and not a DFA, multiple states can be active at
  5614. ** once. An instance of the following object records all active states in
  5615. ** the NFA. The implementation is optimized for the common case where the
  5616. ** number of actives states is small.
  5617. */
  5618. typedef struct ReStateSet {
  5619. unsigned nState; /* Number of current states */
  5620. ReStateNumber *aState; /* Current states */
  5621. } ReStateSet;
  5622. /* An input string read one character at a time.
  5623. */
  5624. typedef struct ReInput ReInput;
  5625. struct ReInput {
  5626. const unsigned char *z; /* All text */
  5627. int i; /* Next byte to read */
  5628. int mx; /* EOF when i>=mx */
  5629. };
  5630. /* A compiled NFA (or an NFA that is in the process of being compiled) is
  5631. ** an instance of the following object.
  5632. */
  5633. typedef struct ReCompiled ReCompiled;
  5634. struct ReCompiled {
  5635. ReInput sIn; /* Regular expression text */
  5636. const char *zErr; /* Error message to return */
  5637. char *aOp; /* Operators for the virtual machine */
  5638. int *aArg; /* Arguments to each operator */
  5639. unsigned (*xNextChar)(ReInput*); /* Next character function */
  5640. unsigned char zInit[12]; /* Initial text to match */
  5641. int nInit; /* Number of characters in zInit */
  5642. unsigned nState; /* Number of entries in aOp[] and aArg[] */
  5643. unsigned nAlloc; /* Slots allocated for aOp[] and aArg[] */
  5644. };
  5645. /* Add a state to the given state set if it is not already there */
  5646. static void re_add_state(ReStateSet *pSet, int newState){
  5647. unsigned i;
  5648. for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
  5649. pSet->aState[pSet->nState++] = (ReStateNumber)newState;
  5650. }
  5651. /* Extract the next unicode character from *pzIn and return it. Advance
  5652. ** *pzIn to the first byte past the end of the character returned. To
  5653. ** be clear: this routine converts utf8 to unicode. This routine is
  5654. ** optimized for the common case where the next character is a single byte.
  5655. */
  5656. static unsigned re_next_char(ReInput *p){
  5657. unsigned c;
  5658. if( p->i>=p->mx ) return 0;
  5659. c = p->z[p->i++];
  5660. if( c>=0x80 ){
  5661. if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
  5662. c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
  5663. if( c<0x80 ) c = 0xfffd;
  5664. }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
  5665. && (p->z[p->i+1]&0xc0)==0x80 ){
  5666. c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
  5667. p->i += 2;
  5668. if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
  5669. }else if( (c&0xf8)==0xf0 && p->i+3<p->mx && (p->z[p->i]&0xc0)==0x80
  5670. && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
  5671. c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
  5672. | (p->z[p->i+2]&0x3f);
  5673. p->i += 3;
  5674. if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
  5675. }else{
  5676. c = 0xfffd;
  5677. }
  5678. }
  5679. return c;
  5680. }
  5681. static unsigned re_next_char_nocase(ReInput *p){
  5682. unsigned c = re_next_char(p);
  5683. if( c>='A' && c<='Z' ) c += 'a' - 'A';
  5684. return c;
  5685. }
  5686. /* Return true if c is a perl "word" character: [A-Za-z0-9_] */
  5687. static int re_word_char(int c){
  5688. return (c>='0' && c<='9') || (c>='a' && c<='z')
  5689. || (c>='A' && c<='Z') || c=='_';
  5690. }
  5691. /* Return true if c is a "digit" character: [0-9] */
  5692. static int re_digit_char(int c){
  5693. return (c>='0' && c<='9');
  5694. }
  5695. /* Return true if c is a perl "space" character: [ \t\r\n\v\f] */
  5696. static int re_space_char(int c){
  5697. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  5698. }
  5699. /* Run a compiled regular expression on the zero-terminated input
  5700. ** string zIn[]. Return true on a match and false if there is no match.
  5701. */
  5702. static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
  5703. ReStateSet aStateSet[2], *pThis, *pNext;
  5704. ReStateNumber aSpace[100];
  5705. ReStateNumber *pToFree;
  5706. unsigned int i = 0;
  5707. unsigned int iSwap = 0;
  5708. int c = RE_EOF+1;
  5709. int cPrev = 0;
  5710. int rc = 0;
  5711. ReInput in;
  5712. in.z = zIn;
  5713. in.i = 0;
  5714. in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
  5715. /* Look for the initial prefix match, if there is one. */
  5716. if( pRe->nInit ){
  5717. unsigned char x = pRe->zInit[0];
  5718. while( in.i+pRe->nInit<=in.mx
  5719. && (zIn[in.i]!=x ||
  5720. strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
  5721. ){
  5722. in.i++;
  5723. }
  5724. if( in.i+pRe->nInit>in.mx ) return 0;
  5725. }
  5726. if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
  5727. pToFree = 0;
  5728. aStateSet[0].aState = aSpace;
  5729. }else{
  5730. pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
  5731. if( pToFree==0 ) return -1;
  5732. aStateSet[0].aState = pToFree;
  5733. }
  5734. aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
  5735. pNext = &aStateSet[1];
  5736. pNext->nState = 0;
  5737. re_add_state(pNext, 0);
  5738. while( c!=RE_EOF && pNext->nState>0 ){
  5739. cPrev = c;
  5740. c = pRe->xNextChar(&in);
  5741. pThis = pNext;
  5742. pNext = &aStateSet[iSwap];
  5743. iSwap = 1 - iSwap;
  5744. pNext->nState = 0;
  5745. for(i=0; i<pThis->nState; i++){
  5746. int x = pThis->aState[i];
  5747. switch( pRe->aOp[x] ){
  5748. case RE_OP_MATCH: {
  5749. if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
  5750. break;
  5751. }
  5752. case RE_OP_ANY: {
  5753. if( c!=0 ) re_add_state(pNext, x+1);
  5754. break;
  5755. }
  5756. case RE_OP_WORD: {
  5757. if( re_word_char(c) ) re_add_state(pNext, x+1);
  5758. break;
  5759. }
  5760. case RE_OP_NOTWORD: {
  5761. if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
  5762. break;
  5763. }
  5764. case RE_OP_DIGIT: {
  5765. if( re_digit_char(c) ) re_add_state(pNext, x+1);
  5766. break;
  5767. }
  5768. case RE_OP_NOTDIGIT: {
  5769. if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
  5770. break;
  5771. }
  5772. case RE_OP_SPACE: {
  5773. if( re_space_char(c) ) re_add_state(pNext, x+1);
  5774. break;
  5775. }
  5776. case RE_OP_NOTSPACE: {
  5777. if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
  5778. break;
  5779. }
  5780. case RE_OP_BOUNDARY: {
  5781. if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
  5782. break;
  5783. }
  5784. case RE_OP_ANYSTAR: {
  5785. re_add_state(pNext, x);
  5786. re_add_state(pThis, x+1);
  5787. break;
  5788. }
  5789. case RE_OP_FORK: {
  5790. re_add_state(pThis, x+pRe->aArg[x]);
  5791. re_add_state(pThis, x+1);
  5792. break;
  5793. }
  5794. case RE_OP_GOTO: {
  5795. re_add_state(pThis, x+pRe->aArg[x]);
  5796. break;
  5797. }
  5798. case RE_OP_ACCEPT: {
  5799. rc = 1;
  5800. goto re_match_end;
  5801. }
  5802. case RE_OP_CC_EXC: {
  5803. if( c==0 ) break;
  5804. /* fall-through */ goto re_op_cc_inc;
  5805. }
  5806. case RE_OP_CC_INC: re_op_cc_inc: {
  5807. int j = 1;
  5808. int n = pRe->aArg[x];
  5809. int hit = 0;
  5810. for(j=1; j>0 && j<n; j++){
  5811. if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
  5812. if( pRe->aArg[x+j]==c ){
  5813. hit = 1;
  5814. j = -1;
  5815. }
  5816. }else{
  5817. if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
  5818. hit = 1;
  5819. j = -1;
  5820. }else{
  5821. j++;
  5822. }
  5823. }
  5824. }
  5825. if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
  5826. if( hit ) re_add_state(pNext, x+n);
  5827. break;
  5828. }
  5829. }
  5830. }
  5831. }
  5832. for(i=0; i<pNext->nState; i++){
  5833. if( pRe->aOp[pNext->aState[i]]==RE_OP_ACCEPT ){ rc = 1; break; }
  5834. }
  5835. re_match_end:
  5836. sqlite3_free(pToFree);
  5837. return rc;
  5838. }
  5839. /* Resize the opcode and argument arrays for an RE under construction.
  5840. */
  5841. static int re_resize(ReCompiled *p, int N){
  5842. char *aOp;
  5843. int *aArg;
  5844. aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
  5845. if( aOp==0 ) return 1;
  5846. p->aOp = aOp;
  5847. aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
  5848. if( aArg==0 ) return 1;
  5849. p->aArg = aArg;
  5850. p->nAlloc = N;
  5851. return 0;
  5852. }
  5853. /* Insert a new opcode and argument into an RE under construction. The
  5854. ** insertion point is just prior to existing opcode iBefore.
  5855. */
  5856. static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
  5857. int i;
  5858. if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
  5859. for(i=p->nState; i>iBefore; i--){
  5860. p->aOp[i] = p->aOp[i-1];
  5861. p->aArg[i] = p->aArg[i-1];
  5862. }
  5863. p->nState++;
  5864. p->aOp[iBefore] = (char)op;
  5865. p->aArg[iBefore] = arg;
  5866. return iBefore;
  5867. }
  5868. /* Append a new opcode and argument to the end of the RE under construction.
  5869. */
  5870. static int re_append(ReCompiled *p, int op, int arg){
  5871. return re_insert(p, p->nState, op, arg);
  5872. }
  5873. /* Make a copy of N opcodes starting at iStart onto the end of the RE
  5874. ** under construction.
  5875. */
  5876. static void re_copy(ReCompiled *p, int iStart, int N){
  5877. if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
  5878. memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
  5879. memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
  5880. p->nState += N;
  5881. }
  5882. /* Return true if c is a hexadecimal digit character: [0-9a-fA-F]
  5883. ** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c). If
  5884. ** c is not a hex digit *pV is unchanged.
  5885. */
  5886. static int re_hex(int c, int *pV){
  5887. if( c>='0' && c<='9' ){
  5888. c -= '0';
  5889. }else if( c>='a' && c<='f' ){
  5890. c -= 'a' - 10;
  5891. }else if( c>='A' && c<='F' ){
  5892. c -= 'A' - 10;
  5893. }else{
  5894. return 0;
  5895. }
  5896. *pV = (*pV)*16 + (c & 0xff);
  5897. return 1;
  5898. }
  5899. /* A backslash character has been seen, read the next character and
  5900. ** return its interpretation.
  5901. */
  5902. static unsigned re_esc_char(ReCompiled *p){
  5903. static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
  5904. static const char zTrans[] = "\a\f\n\r\t\v";
  5905. int i, v = 0;
  5906. char c;
  5907. if( p->sIn.i>=p->sIn.mx ) return 0;
  5908. c = p->sIn.z[p->sIn.i];
  5909. if( c=='u' && p->sIn.i+4<p->sIn.mx ){
  5910. const unsigned char *zIn = p->sIn.z + p->sIn.i;
  5911. if( re_hex(zIn[1],&v)
  5912. && re_hex(zIn[2],&v)
  5913. && re_hex(zIn[3],&v)
  5914. && re_hex(zIn[4],&v)
  5915. ){
  5916. p->sIn.i += 5;
  5917. return v;
  5918. }
  5919. }
  5920. if( c=='x' && p->sIn.i+2<p->sIn.mx ){
  5921. const unsigned char *zIn = p->sIn.z + p->sIn.i;
  5922. if( re_hex(zIn[1],&v)
  5923. && re_hex(zIn[2],&v)
  5924. ){
  5925. p->sIn.i += 3;
  5926. return v;
  5927. }
  5928. }
  5929. for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
  5930. if( zEsc[i] ){
  5931. if( i<6 ) c = zTrans[i];
  5932. p->sIn.i++;
  5933. }else{
  5934. p->zErr = "unknown \\ escape";
  5935. }
  5936. return c;
  5937. }
  5938. /* Forward declaration */
  5939. static const char *re_subcompile_string(ReCompiled*);
  5940. /* Peek at the next byte of input */
  5941. static unsigned char rePeek(ReCompiled *p){
  5942. return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
  5943. }
  5944. /* Compile RE text into a sequence of opcodes. Continue up to the
  5945. ** first unmatched ")" character, then return. If an error is found,
  5946. ** return a pointer to the error message string.
  5947. */
  5948. static const char *re_subcompile_re(ReCompiled *p){
  5949. const char *zErr;
  5950. int iStart, iEnd, iGoto;
  5951. iStart = p->nState;
  5952. zErr = re_subcompile_string(p);
  5953. if( zErr ) return zErr;
  5954. while( rePeek(p)=='|' ){
  5955. iEnd = p->nState;
  5956. re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
  5957. iGoto = re_append(p, RE_OP_GOTO, 0);
  5958. p->sIn.i++;
  5959. zErr = re_subcompile_string(p);
  5960. if( zErr ) return zErr;
  5961. p->aArg[iGoto] = p->nState - iGoto;
  5962. }
  5963. return 0;
  5964. }
  5965. /* Compile an element of regular expression text (anything that can be
  5966. ** an operand to the "|" operator). Return NULL on success or a pointer
  5967. ** to the error message if there is a problem.
  5968. */
  5969. static const char *re_subcompile_string(ReCompiled *p){
  5970. int iPrev = -1;
  5971. int iStart;
  5972. unsigned c;
  5973. const char *zErr;
  5974. while( (c = p->xNextChar(&p->sIn))!=0 ){
  5975. iStart = p->nState;
  5976. switch( c ){
  5977. case '|':
  5978. case '$':
  5979. case ')': {
  5980. p->sIn.i--;
  5981. return 0;
  5982. }
  5983. case '(': {
  5984. zErr = re_subcompile_re(p);
  5985. if( zErr ) return zErr;
  5986. if( rePeek(p)!=')' ) return "unmatched '('";
  5987. p->sIn.i++;
  5988. break;
  5989. }
  5990. case '.': {
  5991. if( rePeek(p)=='*' ){
  5992. re_append(p, RE_OP_ANYSTAR, 0);
  5993. p->sIn.i++;
  5994. }else{
  5995. re_append(p, RE_OP_ANY, 0);
  5996. }
  5997. break;
  5998. }
  5999. case '*': {
  6000. if( iPrev<0 ) return "'*' without operand";
  6001. re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
  6002. re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
  6003. break;
  6004. }
  6005. case '+': {
  6006. if( iPrev<0 ) return "'+' without operand";
  6007. re_append(p, RE_OP_FORK, iPrev - p->nState);
  6008. break;
  6009. }
  6010. case '?': {
  6011. if( iPrev<0 ) return "'?' without operand";
  6012. re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
  6013. break;
  6014. }
  6015. case '{': {
  6016. int m = 0, n = 0;
  6017. int sz, j;
  6018. if( iPrev<0 ) return "'{m,n}' without operand";
  6019. while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
  6020. n = m;
  6021. if( c==',' ){
  6022. p->sIn.i++;
  6023. n = 0;
  6024. while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
  6025. }
  6026. if( c!='}' ) return "unmatched '{'";
  6027. if( n>0 && n<m ) return "n less than m in '{m,n}'";
  6028. p->sIn.i++;
  6029. sz = p->nState - iPrev;
  6030. if( m==0 ){
  6031. if( n==0 ) return "both m and n are zero in '{m,n}'";
  6032. re_insert(p, iPrev, RE_OP_FORK, sz+1);
  6033. n--;
  6034. }else{
  6035. for(j=1; j<m; j++) re_copy(p, iPrev, sz);
  6036. }
  6037. for(j=m; j<n; j++){
  6038. re_append(p, RE_OP_FORK, sz+1);
  6039. re_copy(p, iPrev, sz);
  6040. }
  6041. if( n==0 && m>0 ){
  6042. re_append(p, RE_OP_FORK, -sz);
  6043. }
  6044. break;
  6045. }
  6046. case '[': {
  6047. int iFirst = p->nState;
  6048. if( rePeek(p)=='^' ){
  6049. re_append(p, RE_OP_CC_EXC, 0);
  6050. p->sIn.i++;
  6051. }else{
  6052. re_append(p, RE_OP_CC_INC, 0);
  6053. }
  6054. while( (c = p->xNextChar(&p->sIn))!=0 ){
  6055. if( c=='[' && rePeek(p)==':' ){
  6056. return "POSIX character classes not supported";
  6057. }
  6058. if( c=='\\' ) c = re_esc_char(p);
  6059. if( rePeek(p)=='-' ){
  6060. re_append(p, RE_OP_CC_RANGE, c);
  6061. p->sIn.i++;
  6062. c = p->xNextChar(&p->sIn);
  6063. if( c=='\\' ) c = re_esc_char(p);
  6064. re_append(p, RE_OP_CC_RANGE, c);
  6065. }else{
  6066. re_append(p, RE_OP_CC_VALUE, c);
  6067. }
  6068. if( rePeek(p)==']' ){ p->sIn.i++; break; }
  6069. }
  6070. if( c==0 ) return "unclosed '['";
  6071. p->aArg[iFirst] = p->nState - iFirst;
  6072. break;
  6073. }
  6074. case '\\': {
  6075. int specialOp = 0;
  6076. switch( rePeek(p) ){
  6077. case 'b': specialOp = RE_OP_BOUNDARY; break;
  6078. case 'd': specialOp = RE_OP_DIGIT; break;
  6079. case 'D': specialOp = RE_OP_NOTDIGIT; break;
  6080. case 's': specialOp = RE_OP_SPACE; break;
  6081. case 'S': specialOp = RE_OP_NOTSPACE; break;
  6082. case 'w': specialOp = RE_OP_WORD; break;
  6083. case 'W': specialOp = RE_OP_NOTWORD; break;
  6084. }
  6085. if( specialOp ){
  6086. p->sIn.i++;
  6087. re_append(p, specialOp, 0);
  6088. }else{
  6089. c = re_esc_char(p);
  6090. re_append(p, RE_OP_MATCH, c);
  6091. }
  6092. break;
  6093. }
  6094. default: {
  6095. re_append(p, RE_OP_MATCH, c);
  6096. break;
  6097. }
  6098. }
  6099. iPrev = iStart;
  6100. }
  6101. return 0;
  6102. }
  6103. /* Free and reclaim all the memory used by a previously compiled
  6104. ** regular expression. Applications should invoke this routine once
  6105. ** for every call to re_compile() to avoid memory leaks.
  6106. */
  6107. static void re_free(ReCompiled *pRe){
  6108. if( pRe ){
  6109. sqlite3_free(pRe->aOp);
  6110. sqlite3_free(pRe->aArg);
  6111. sqlite3_free(pRe);
  6112. }
  6113. }
  6114. /*
  6115. ** Compile a textual regular expression in zIn[] into a compiled regular
  6116. ** expression suitable for us by re_match() and return a pointer to the
  6117. ** compiled regular expression in *ppRe. Return NULL on success or an
  6118. ** error message if something goes wrong.
  6119. */
  6120. static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
  6121. ReCompiled *pRe;
  6122. const char *zErr;
  6123. int i, j;
  6124. *ppRe = 0;
  6125. pRe = sqlite3_malloc( sizeof(*pRe) );
  6126. if( pRe==0 ){
  6127. return "out of memory";
  6128. }
  6129. memset(pRe, 0, sizeof(*pRe));
  6130. pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
  6131. if( re_resize(pRe, 30) ){
  6132. re_free(pRe);
  6133. return "out of memory";
  6134. }
  6135. if( zIn[0]=='^' ){
  6136. zIn++;
  6137. }else{
  6138. re_append(pRe, RE_OP_ANYSTAR, 0);
  6139. }
  6140. pRe->sIn.z = (unsigned char*)zIn;
  6141. pRe->sIn.i = 0;
  6142. pRe->sIn.mx = (int)strlen(zIn);
  6143. zErr = re_subcompile_re(pRe);
  6144. if( zErr ){
  6145. re_free(pRe);
  6146. return zErr;
  6147. }
  6148. if( rePeek(pRe)=='$' && pRe->sIn.i+1>=pRe->sIn.mx ){
  6149. re_append(pRe, RE_OP_MATCH, RE_EOF);
  6150. re_append(pRe, RE_OP_ACCEPT, 0);
  6151. *ppRe = pRe;
  6152. }else if( pRe->sIn.i>=pRe->sIn.mx ){
  6153. re_append(pRe, RE_OP_ACCEPT, 0);
  6154. *ppRe = pRe;
  6155. }else{
  6156. re_free(pRe);
  6157. return "unrecognized character";
  6158. }
  6159. /* The following is a performance optimization. If the regex begins with
  6160. ** ".*" (if the input regex lacks an initial "^") and afterwards there are
  6161. ** one or more matching characters, enter those matching characters into
  6162. ** zInit[]. The re_match() routine can then search ahead in the input
  6163. ** string looking for the initial match without having to run the whole
  6164. ** regex engine over the string. Do not worry able trying to match
  6165. ** unicode characters beyond plane 0 - those are very rare and this is
  6166. ** just an optimization. */
  6167. if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
  6168. for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
  6169. unsigned x = pRe->aArg[i];
  6170. if( x<=127 ){
  6171. pRe->zInit[j++] = (unsigned char)x;
  6172. }else if( x<=0xfff ){
  6173. pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
  6174. pRe->zInit[j++] = 0x80 | (x&0x3f);
  6175. }else if( x<=0xffff ){
  6176. pRe->zInit[j++] = (unsigned char)(0xd0 | (x>>12));
  6177. pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
  6178. pRe->zInit[j++] = 0x80 | (x&0x3f);
  6179. }else{
  6180. break;
  6181. }
  6182. }
  6183. if( j>0 && pRe->zInit[j-1]==0 ) j--;
  6184. pRe->nInit = j;
  6185. }
  6186. return pRe->zErr;
  6187. }
  6188. /*
  6189. ** Implementation of the regexp() SQL function. This function implements
  6190. ** the build-in REGEXP operator. The first argument to the function is the
  6191. ** pattern and the second argument is the string. So, the SQL statements:
  6192. **
  6193. ** A REGEXP B
  6194. **
  6195. ** is implemented as regexp(B,A).
  6196. */
  6197. static void re_sql_func(
  6198. sqlite3_context *context,
  6199. int argc,
  6200. sqlite3_value **argv
  6201. ){
  6202. ReCompiled *pRe; /* Compiled regular expression */
  6203. const char *zPattern; /* The regular expression */
  6204. const unsigned char *zStr;/* String being searched */
  6205. const char *zErr; /* Compile error message */
  6206. int setAux = 0; /* True to invoke sqlite3_set_auxdata() */
  6207. (void)argc; /* Unused */
  6208. pRe = sqlite3_get_auxdata(context, 0);
  6209. if( pRe==0 ){
  6210. zPattern = (const char*)sqlite3_value_text(argv[0]);
  6211. if( zPattern==0 ) return;
  6212. zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
  6213. if( zErr ){
  6214. re_free(pRe);
  6215. sqlite3_result_error(context, zErr, -1);
  6216. return;
  6217. }
  6218. if( pRe==0 ){
  6219. sqlite3_result_error_nomem(context);
  6220. return;
  6221. }
  6222. setAux = 1;
  6223. }
  6224. zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
  6225. if( zStr!=0 ){
  6226. sqlite3_result_int(context, re_match(pRe, zStr, -1));
  6227. }
  6228. if( setAux ){
  6229. sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free);
  6230. }
  6231. }
  6232. /*
  6233. ** Invoke this routine to register the regexp() function with the
  6234. ** SQLite database connection.
  6235. */
  6236. #ifdef _WIN32
  6237. #endif
  6238. int sqlite3_regexp_init(
  6239. sqlite3 *db,
  6240. char **pzErrMsg,
  6241. const sqlite3_api_routines *pApi
  6242. ){
  6243. int rc = SQLITE_OK;
  6244. SQLITE_EXTENSION_INIT2(pApi);
  6245. (void)pzErrMsg; /* Unused */
  6246. rc = sqlite3_create_function(db, "regexp", 2,
  6247. SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
  6248. 0, re_sql_func, 0, 0);
  6249. if( rc==SQLITE_OK ){
  6250. /* The regexpi(PATTERN,STRING) function is a case-insensitive version
  6251. ** of regexp(PATTERN,STRING). */
  6252. rc = sqlite3_create_function(db, "regexpi", 2,
  6253. SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
  6254. (void*)db, re_sql_func, 0, 0);
  6255. }
  6256. return rc;
  6257. }
  6258. /************************* End ../ext/misc/regexp.c ********************/
  6259. #ifdef SQLITE_HAVE_ZLIB
  6260. /************************* Begin ../ext/misc/zipfile.c ******************/
  6261. /*
  6262. ** 2017-12-26
  6263. **
  6264. ** The author disclaims copyright to this source code. In place of
  6265. ** a legal notice, here is a blessing:
  6266. **
  6267. ** May you do good and not evil.
  6268. ** May you find forgiveness for yourself and forgive others.
  6269. ** May you share freely, never taking more than you give.
  6270. **
  6271. ******************************************************************************
  6272. **
  6273. ** This file implements a virtual table for reading and writing ZIP archive
  6274. ** files.
  6275. **
  6276. ** Usage example:
  6277. **
  6278. ** SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
  6279. **
  6280. ** Current limitations:
  6281. **
  6282. ** * No support for encryption
  6283. ** * No support for ZIP archives spanning multiple files
  6284. ** * No support for zip64 extensions
  6285. ** * Only the "inflate/deflate" (zlib) compression method is supported
  6286. */
  6287. /* #include "sqlite3ext.h" */
  6288. SQLITE_EXTENSION_INIT1
  6289. #include <stdio.h>
  6290. #include <string.h>
  6291. #include <assert.h>
  6292. #include <zlib.h>
  6293. #ifndef SQLITE_OMIT_VIRTUALTABLE
  6294. #ifndef SQLITE_AMALGAMATION
  6295. #ifndef UINT32_TYPE
  6296. # ifdef HAVE_UINT32_T
  6297. # define UINT32_TYPE uint32_t
  6298. # else
  6299. # define UINT32_TYPE unsigned int
  6300. # endif
  6301. #endif
  6302. #ifndef UINT16_TYPE
  6303. # ifdef HAVE_UINT16_T
  6304. # define UINT16_TYPE uint16_t
  6305. # else
  6306. # define UINT16_TYPE unsigned short int
  6307. # endif
  6308. #endif
  6309. /* typedef sqlite3_int64 i64; */
  6310. /* typedef unsigned char u8; */
  6311. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  6312. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  6313. #define MIN(a,b) ((a)<(b) ? (a) : (b))
  6314. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  6315. # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
  6316. #endif
  6317. #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
  6318. # define ALWAYS(X) (1)
  6319. # define NEVER(X) (0)
  6320. #elif !defined(NDEBUG)
  6321. # define ALWAYS(X) ((X)?1:(assert(0),0))
  6322. # define NEVER(X) ((X)?(assert(0),1):0)
  6323. #else
  6324. # define ALWAYS(X) (X)
  6325. # define NEVER(X) (X)
  6326. #endif
  6327. #endif /* SQLITE_AMALGAMATION */
  6328. /*
  6329. ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
  6330. **
  6331. ** In some ways it would be better to obtain these values from system
  6332. ** header files. But, the dependency is undesirable and (a) these
  6333. ** have been stable for decades, (b) the values are part of POSIX and
  6334. ** are also made explicit in [man stat], and (c) are part of the
  6335. ** file format for zip archives.
  6336. */
  6337. #ifndef S_IFDIR
  6338. # define S_IFDIR 0040000
  6339. #endif
  6340. #ifndef S_IFREG
  6341. # define S_IFREG 0100000
  6342. #endif
  6343. #ifndef S_IFLNK
  6344. # define S_IFLNK 0120000
  6345. #endif
  6346. static const char ZIPFILE_SCHEMA[] =
  6347. "CREATE TABLE y("
  6348. "name PRIMARY KEY," /* 0: Name of file in zip archive */
  6349. "mode," /* 1: POSIX mode for file */
  6350. "mtime," /* 2: Last modification time (secs since 1970)*/
  6351. "sz," /* 3: Size of object */
  6352. "rawdata," /* 4: Raw data */
  6353. "data," /* 5: Uncompressed data */
  6354. "method," /* 6: Compression method (integer) */
  6355. "z HIDDEN" /* 7: Name of zip file */
  6356. ") WITHOUT ROWID;";
  6357. #define ZIPFILE_F_COLUMN_IDX 7 /* Index of column "file" in the above */
  6358. #define ZIPFILE_BUFFER_SIZE (64*1024)
  6359. /*
  6360. ** Magic numbers used to read and write zip files.
  6361. **
  6362. ** ZIPFILE_NEWENTRY_MADEBY:
  6363. ** Use this value for the "version-made-by" field in new zip file
  6364. ** entries. The upper byte indicates "unix", and the lower byte
  6365. ** indicates that the zip file matches pkzip specification 3.0.
  6366. ** This is what info-zip seems to do.
  6367. **
  6368. ** ZIPFILE_NEWENTRY_REQUIRED:
  6369. ** Value for "version-required-to-extract" field of new entries.
  6370. ** Version 2.0 is required to support folders and deflate compression.
  6371. **
  6372. ** ZIPFILE_NEWENTRY_FLAGS:
  6373. ** Value for "general-purpose-bit-flags" field of new entries. Bit
  6374. ** 11 means "utf-8 filename and comment".
  6375. **
  6376. ** ZIPFILE_SIGNATURE_CDS:
  6377. ** First 4 bytes of a valid CDS record.
  6378. **
  6379. ** ZIPFILE_SIGNATURE_LFH:
  6380. ** First 4 bytes of a valid LFH record.
  6381. **
  6382. ** ZIPFILE_SIGNATURE_EOCD
  6383. ** First 4 bytes of a valid EOCD record.
  6384. */
  6385. #define ZIPFILE_EXTRA_TIMESTAMP 0x5455
  6386. #define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30)
  6387. #define ZIPFILE_NEWENTRY_REQUIRED 20
  6388. #define ZIPFILE_NEWENTRY_FLAGS 0x800
  6389. #define ZIPFILE_SIGNATURE_CDS 0x02014b50
  6390. #define ZIPFILE_SIGNATURE_LFH 0x04034b50
  6391. #define ZIPFILE_SIGNATURE_EOCD 0x06054b50
  6392. /*
  6393. ** The sizes of the fixed-size part of each of the three main data
  6394. ** structures in a zip archive.
  6395. */
  6396. #define ZIPFILE_LFH_FIXED_SZ 30
  6397. #define ZIPFILE_EOCD_FIXED_SZ 22
  6398. #define ZIPFILE_CDS_FIXED_SZ 46
  6399. /*
  6400. *** 4.3.16 End of central directory record:
  6401. ***
  6402. *** end of central dir signature 4 bytes (0x06054b50)
  6403. *** number of this disk 2 bytes
  6404. *** number of the disk with the
  6405. *** start of the central directory 2 bytes
  6406. *** total number of entries in the
  6407. *** central directory on this disk 2 bytes
  6408. *** total number of entries in
  6409. *** the central directory 2 bytes
  6410. *** size of the central directory 4 bytes
  6411. *** offset of start of central
  6412. *** directory with respect to
  6413. *** the starting disk number 4 bytes
  6414. *** .ZIP file comment length 2 bytes
  6415. *** .ZIP file comment (variable size)
  6416. */
  6417. typedef struct ZipfileEOCD ZipfileEOCD;
  6418. struct ZipfileEOCD {
  6419. u16 iDisk;
  6420. u16 iFirstDisk;
  6421. u16 nEntry;
  6422. u16 nEntryTotal;
  6423. u32 nSize;
  6424. u32 iOffset;
  6425. };
  6426. /*
  6427. *** 4.3.12 Central directory structure:
  6428. ***
  6429. *** ...
  6430. ***
  6431. *** central file header signature 4 bytes (0x02014b50)
  6432. *** version made by 2 bytes
  6433. *** version needed to extract 2 bytes
  6434. *** general purpose bit flag 2 bytes
  6435. *** compression method 2 bytes
  6436. *** last mod file time 2 bytes
  6437. *** last mod file date 2 bytes
  6438. *** crc-32 4 bytes
  6439. *** compressed size 4 bytes
  6440. *** uncompressed size 4 bytes
  6441. *** file name length 2 bytes
  6442. *** extra field length 2 bytes
  6443. *** file comment length 2 bytes
  6444. *** disk number start 2 bytes
  6445. *** internal file attributes 2 bytes
  6446. *** external file attributes 4 bytes
  6447. *** relative offset of local header 4 bytes
  6448. */
  6449. typedef struct ZipfileCDS ZipfileCDS;
  6450. struct ZipfileCDS {
  6451. u16 iVersionMadeBy;
  6452. u16 iVersionExtract;
  6453. u16 flags;
  6454. u16 iCompression;
  6455. u16 mTime;
  6456. u16 mDate;
  6457. u32 crc32;
  6458. u32 szCompressed;
  6459. u32 szUncompressed;
  6460. u16 nFile;
  6461. u16 nExtra;
  6462. u16 nComment;
  6463. u16 iDiskStart;
  6464. u16 iInternalAttr;
  6465. u32 iExternalAttr;
  6466. u32 iOffset;
  6467. char *zFile; /* Filename (sqlite3_malloc()) */
  6468. };
  6469. /*
  6470. *** 4.3.7 Local file header:
  6471. ***
  6472. *** local file header signature 4 bytes (0x04034b50)
  6473. *** version needed to extract 2 bytes
  6474. *** general purpose bit flag 2 bytes
  6475. *** compression method 2 bytes
  6476. *** last mod file time 2 bytes
  6477. *** last mod file date 2 bytes
  6478. *** crc-32 4 bytes
  6479. *** compressed size 4 bytes
  6480. *** uncompressed size 4 bytes
  6481. *** file name length 2 bytes
  6482. *** extra field length 2 bytes
  6483. ***
  6484. */
  6485. typedef struct ZipfileLFH ZipfileLFH;
  6486. struct ZipfileLFH {
  6487. u16 iVersionExtract;
  6488. u16 flags;
  6489. u16 iCompression;
  6490. u16 mTime;
  6491. u16 mDate;
  6492. u32 crc32;
  6493. u32 szCompressed;
  6494. u32 szUncompressed;
  6495. u16 nFile;
  6496. u16 nExtra;
  6497. };
  6498. typedef struct ZipfileEntry ZipfileEntry;
  6499. struct ZipfileEntry {
  6500. ZipfileCDS cds; /* Parsed CDS record */
  6501. u32 mUnixTime; /* Modification time, in UNIX format */
  6502. u8 *aExtra; /* cds.nExtra+cds.nComment bytes of extra data */
  6503. i64 iDataOff; /* Offset to data in file (if aData==0) */
  6504. u8 *aData; /* cds.szCompressed bytes of compressed data */
  6505. ZipfileEntry *pNext; /* Next element in in-memory CDS */
  6506. };
  6507. /*
  6508. ** Cursor type for zipfile tables.
  6509. */
  6510. typedef struct ZipfileCsr ZipfileCsr;
  6511. struct ZipfileCsr {
  6512. sqlite3_vtab_cursor base; /* Base class - must be first */
  6513. i64 iId; /* Cursor ID */
  6514. u8 bEof; /* True when at EOF */
  6515. u8 bNoop; /* If next xNext() call is no-op */
  6516. /* Used outside of write transactions */
  6517. FILE *pFile; /* Zip file */
  6518. i64 iNextOff; /* Offset of next record in central directory */
  6519. ZipfileEOCD eocd; /* Parse of central directory record */
  6520. ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */
  6521. ZipfileEntry *pCurrent; /* Current entry */
  6522. ZipfileCsr *pCsrNext; /* Next cursor on same virtual table */
  6523. };
  6524. typedef struct ZipfileTab ZipfileTab;
  6525. struct ZipfileTab {
  6526. sqlite3_vtab base; /* Base class - must be first */
  6527. char *zFile; /* Zip file this table accesses (may be NULL) */
  6528. sqlite3 *db; /* Host database connection */
  6529. u8 *aBuffer; /* Temporary buffer used for various tasks */
  6530. ZipfileCsr *pCsrList; /* List of cursors */
  6531. i64 iNextCsrid;
  6532. /* The following are used by write transactions only */
  6533. ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
  6534. ZipfileEntry *pLastEntry; /* Last element in pFirstEntry list */
  6535. FILE *pWriteFd; /* File handle open on zip archive */
  6536. i64 szCurrent; /* Current size of zip archive */
  6537. i64 szOrig; /* Size of archive at start of transaction */
  6538. };
  6539. /*
  6540. ** Set the error message contained in context ctx to the results of
  6541. ** vprintf(zFmt, ...).
  6542. */
  6543. static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
  6544. char *zMsg = 0;
  6545. va_list ap;
  6546. va_start(ap, zFmt);
  6547. zMsg = sqlite3_vmprintf(zFmt, ap);
  6548. sqlite3_result_error(ctx, zMsg, -1);
  6549. sqlite3_free(zMsg);
  6550. va_end(ap);
  6551. }
  6552. /*
  6553. ** If string zIn is quoted, dequote it in place. Otherwise, if the string
  6554. ** is not quoted, do nothing.
  6555. */
  6556. static void zipfileDequote(char *zIn){
  6557. char q = zIn[0];
  6558. if( q=='"' || q=='\'' || q=='`' || q=='[' ){
  6559. int iIn = 1;
  6560. int iOut = 0;
  6561. if( q=='[' ) q = ']';
  6562. while( ALWAYS(zIn[iIn]) ){
  6563. char c = zIn[iIn++];
  6564. if( c==q && zIn[iIn++]!=q ) break;
  6565. zIn[iOut++] = c;
  6566. }
  6567. zIn[iOut] = '\0';
  6568. }
  6569. }
  6570. /*
  6571. ** Construct a new ZipfileTab virtual table object.
  6572. **
  6573. ** argv[0] -> module name ("zipfile")
  6574. ** argv[1] -> database name
  6575. ** argv[2] -> table name
  6576. ** argv[...] -> "column name" and other module argument fields.
  6577. */
  6578. static int zipfileConnect(
  6579. sqlite3 *db,
  6580. void *pAux,
  6581. int argc, const char *const*argv,
  6582. sqlite3_vtab **ppVtab,
  6583. char **pzErr
  6584. ){
  6585. int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
  6586. int nFile = 0;
  6587. const char *zFile = 0;
  6588. ZipfileTab *pNew = 0;
  6589. int rc;
  6590. /* If the table name is not "zipfile", require that the argument be
  6591. ** specified. This stops zipfile tables from being created as:
  6592. **
  6593. ** CREATE VIRTUAL TABLE zzz USING zipfile();
  6594. **
  6595. ** It does not prevent:
  6596. **
  6597. ** CREATE VIRTUAL TABLE zipfile USING zipfile();
  6598. */
  6599. assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
  6600. if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
  6601. *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
  6602. return SQLITE_ERROR;
  6603. }
  6604. if( argc>3 ){
  6605. zFile = argv[3];
  6606. nFile = (int)strlen(zFile)+1;
  6607. }
  6608. rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
  6609. if( rc==SQLITE_OK ){
  6610. pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
  6611. if( pNew==0 ) return SQLITE_NOMEM;
  6612. memset(pNew, 0, nByte+nFile);
  6613. pNew->db = db;
  6614. pNew->aBuffer = (u8*)&pNew[1];
  6615. if( zFile ){
  6616. pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
  6617. memcpy(pNew->zFile, zFile, nFile);
  6618. zipfileDequote(pNew->zFile);
  6619. }
  6620. }
  6621. sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
  6622. *ppVtab = (sqlite3_vtab*)pNew;
  6623. return rc;
  6624. }
  6625. /*
  6626. ** Free the ZipfileEntry structure indicated by the only argument.
  6627. */
  6628. static void zipfileEntryFree(ZipfileEntry *p){
  6629. if( p ){
  6630. sqlite3_free(p->cds.zFile);
  6631. sqlite3_free(p);
  6632. }
  6633. }
  6634. /*
  6635. ** Release resources that should be freed at the end of a write
  6636. ** transaction.
  6637. */
  6638. static void zipfileCleanupTransaction(ZipfileTab *pTab){
  6639. ZipfileEntry *pEntry;
  6640. ZipfileEntry *pNext;
  6641. if( pTab->pWriteFd ){
  6642. fclose(pTab->pWriteFd);
  6643. pTab->pWriteFd = 0;
  6644. }
  6645. for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
  6646. pNext = pEntry->pNext;
  6647. zipfileEntryFree(pEntry);
  6648. }
  6649. pTab->pFirstEntry = 0;
  6650. pTab->pLastEntry = 0;
  6651. pTab->szCurrent = 0;
  6652. pTab->szOrig = 0;
  6653. }
  6654. /*
  6655. ** This method is the destructor for zipfile vtab objects.
  6656. */
  6657. static int zipfileDisconnect(sqlite3_vtab *pVtab){
  6658. zipfileCleanupTransaction((ZipfileTab*)pVtab);
  6659. sqlite3_free(pVtab);
  6660. return SQLITE_OK;
  6661. }
  6662. /*
  6663. ** Constructor for a new ZipfileCsr object.
  6664. */
  6665. static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
  6666. ZipfileTab *pTab = (ZipfileTab*)p;
  6667. ZipfileCsr *pCsr;
  6668. pCsr = sqlite3_malloc(sizeof(*pCsr));
  6669. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  6670. if( pCsr==0 ){
  6671. return SQLITE_NOMEM;
  6672. }
  6673. memset(pCsr, 0, sizeof(*pCsr));
  6674. pCsr->iId = ++pTab->iNextCsrid;
  6675. pCsr->pCsrNext = pTab->pCsrList;
  6676. pTab->pCsrList = pCsr;
  6677. return SQLITE_OK;
  6678. }
  6679. /*
  6680. ** Reset a cursor back to the state it was in when first returned
  6681. ** by zipfileOpen().
  6682. */
  6683. static void zipfileResetCursor(ZipfileCsr *pCsr){
  6684. ZipfileEntry *p;
  6685. ZipfileEntry *pNext;
  6686. pCsr->bEof = 0;
  6687. if( pCsr->pFile ){
  6688. fclose(pCsr->pFile);
  6689. pCsr->pFile = 0;
  6690. zipfileEntryFree(pCsr->pCurrent);
  6691. pCsr->pCurrent = 0;
  6692. }
  6693. for(p=pCsr->pFreeEntry; p; p=pNext){
  6694. pNext = p->pNext;
  6695. zipfileEntryFree(p);
  6696. }
  6697. }
  6698. /*
  6699. ** Destructor for an ZipfileCsr.
  6700. */
  6701. static int zipfileClose(sqlite3_vtab_cursor *cur){
  6702. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  6703. ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
  6704. ZipfileCsr **pp;
  6705. zipfileResetCursor(pCsr);
  6706. /* Remove this cursor from the ZipfileTab.pCsrList list. */
  6707. for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
  6708. *pp = pCsr->pCsrNext;
  6709. sqlite3_free(pCsr);
  6710. return SQLITE_OK;
  6711. }
  6712. /*
  6713. ** Set the error message for the virtual table associated with cursor
  6714. ** pCsr to the results of vprintf(zFmt, ...).
  6715. */
  6716. static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
  6717. va_list ap;
  6718. va_start(ap, zFmt);
  6719. sqlite3_free(pTab->base.zErrMsg);
  6720. pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
  6721. va_end(ap);
  6722. }
  6723. static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
  6724. va_list ap;
  6725. va_start(ap, zFmt);
  6726. sqlite3_free(pCsr->base.pVtab->zErrMsg);
  6727. pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
  6728. va_end(ap);
  6729. }
  6730. /*
  6731. ** Read nRead bytes of data from offset iOff of file pFile into buffer
  6732. ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
  6733. ** otherwise.
  6734. **
  6735. ** If an error does occur, output variable (*pzErrmsg) may be set to point
  6736. ** to an English language error message. It is the responsibility of the
  6737. ** caller to eventually free this buffer using
  6738. ** sqlite3_free().
  6739. */
  6740. static int zipfileReadData(
  6741. FILE *pFile, /* Read from this file */
  6742. u8 *aRead, /* Read into this buffer */
  6743. int nRead, /* Number of bytes to read */
  6744. i64 iOff, /* Offset to read from */
  6745. char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */
  6746. ){
  6747. size_t n;
  6748. fseek(pFile, (long)iOff, SEEK_SET);
  6749. n = fread(aRead, 1, nRead, pFile);
  6750. if( (int)n!=nRead ){
  6751. *pzErrmsg = sqlite3_mprintf("error in fread()");
  6752. return SQLITE_ERROR;
  6753. }
  6754. return SQLITE_OK;
  6755. }
  6756. static int zipfileAppendData(
  6757. ZipfileTab *pTab,
  6758. const u8 *aWrite,
  6759. int nWrite
  6760. ){
  6761. if( nWrite>0 ){
  6762. size_t n = nWrite;
  6763. fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
  6764. n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
  6765. if( (int)n!=nWrite ){
  6766. pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
  6767. return SQLITE_ERROR;
  6768. }
  6769. pTab->szCurrent += nWrite;
  6770. }
  6771. return SQLITE_OK;
  6772. }
  6773. /*
  6774. ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
  6775. */
  6776. static u16 zipfileGetU16(const u8 *aBuf){
  6777. return (aBuf[1] << 8) + aBuf[0];
  6778. }
  6779. /*
  6780. ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
  6781. */
  6782. static u32 zipfileGetU32(const u8 *aBuf){
  6783. if( aBuf==0 ) return 0;
  6784. return ((u32)(aBuf[3]) << 24)
  6785. + ((u32)(aBuf[2]) << 16)
  6786. + ((u32)(aBuf[1]) << 8)
  6787. + ((u32)(aBuf[0]) << 0);
  6788. }
  6789. /*
  6790. ** Write a 16-bit little endiate integer into buffer aBuf.
  6791. */
  6792. static void zipfilePutU16(u8 *aBuf, u16 val){
  6793. aBuf[0] = val & 0xFF;
  6794. aBuf[1] = (val>>8) & 0xFF;
  6795. }
  6796. /*
  6797. ** Write a 32-bit little endiate integer into buffer aBuf.
  6798. */
  6799. static void zipfilePutU32(u8 *aBuf, u32 val){
  6800. aBuf[0] = val & 0xFF;
  6801. aBuf[1] = (val>>8) & 0xFF;
  6802. aBuf[2] = (val>>16) & 0xFF;
  6803. aBuf[3] = (val>>24) & 0xFF;
  6804. }
  6805. #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
  6806. #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
  6807. #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
  6808. #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
  6809. /*
  6810. ** Magic numbers used to read CDS records.
  6811. */
  6812. #define ZIPFILE_CDS_NFILE_OFF 28
  6813. #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
  6814. /*
  6815. ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
  6816. ** if the record is not well-formed, or SQLITE_OK otherwise.
  6817. */
  6818. static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
  6819. u8 *aRead = aBuf;
  6820. u32 sig = zipfileRead32(aRead);
  6821. int rc = SQLITE_OK;
  6822. if( sig!=ZIPFILE_SIGNATURE_CDS ){
  6823. rc = SQLITE_ERROR;
  6824. }else{
  6825. pCDS->iVersionMadeBy = zipfileRead16(aRead);
  6826. pCDS->iVersionExtract = zipfileRead16(aRead);
  6827. pCDS->flags = zipfileRead16(aRead);
  6828. pCDS->iCompression = zipfileRead16(aRead);
  6829. pCDS->mTime = zipfileRead16(aRead);
  6830. pCDS->mDate = zipfileRead16(aRead);
  6831. pCDS->crc32 = zipfileRead32(aRead);
  6832. pCDS->szCompressed = zipfileRead32(aRead);
  6833. pCDS->szUncompressed = zipfileRead32(aRead);
  6834. assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
  6835. pCDS->nFile = zipfileRead16(aRead);
  6836. pCDS->nExtra = zipfileRead16(aRead);
  6837. pCDS->nComment = zipfileRead16(aRead);
  6838. pCDS->iDiskStart = zipfileRead16(aRead);
  6839. pCDS->iInternalAttr = zipfileRead16(aRead);
  6840. pCDS->iExternalAttr = zipfileRead32(aRead);
  6841. pCDS->iOffset = zipfileRead32(aRead);
  6842. assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
  6843. }
  6844. return rc;
  6845. }
  6846. /*
  6847. ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
  6848. ** if the record is not well-formed, or SQLITE_OK otherwise.
  6849. */
  6850. static int zipfileReadLFH(
  6851. u8 *aBuffer,
  6852. ZipfileLFH *pLFH
  6853. ){
  6854. u8 *aRead = aBuffer;
  6855. int rc = SQLITE_OK;
  6856. u32 sig = zipfileRead32(aRead);
  6857. if( sig!=ZIPFILE_SIGNATURE_LFH ){
  6858. rc = SQLITE_ERROR;
  6859. }else{
  6860. pLFH->iVersionExtract = zipfileRead16(aRead);
  6861. pLFH->flags = zipfileRead16(aRead);
  6862. pLFH->iCompression = zipfileRead16(aRead);
  6863. pLFH->mTime = zipfileRead16(aRead);
  6864. pLFH->mDate = zipfileRead16(aRead);
  6865. pLFH->crc32 = zipfileRead32(aRead);
  6866. pLFH->szCompressed = zipfileRead32(aRead);
  6867. pLFH->szUncompressed = zipfileRead32(aRead);
  6868. pLFH->nFile = zipfileRead16(aRead);
  6869. pLFH->nExtra = zipfileRead16(aRead);
  6870. }
  6871. return rc;
  6872. }
  6873. /*
  6874. ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
  6875. ** Scan through this buffer to find an "extra-timestamp" field. If one
  6876. ** exists, extract the 32-bit modification-timestamp from it and store
  6877. ** the value in output parameter *pmTime.
  6878. **
  6879. ** Zero is returned if no extra-timestamp record could be found (and so
  6880. ** *pmTime is left unchanged), or non-zero otherwise.
  6881. **
  6882. ** The general format of an extra field is:
  6883. **
  6884. ** Header ID 2 bytes
  6885. ** Data Size 2 bytes
  6886. ** Data N bytes
  6887. */
  6888. static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
  6889. int ret = 0;
  6890. u8 *p = aExtra;
  6891. u8 *pEnd = &aExtra[nExtra];
  6892. while( p<pEnd ){
  6893. u16 id = zipfileRead16(p);
  6894. u16 nByte = zipfileRead16(p);
  6895. switch( id ){
  6896. case ZIPFILE_EXTRA_TIMESTAMP: {
  6897. u8 b = p[0];
  6898. if( b & 0x01 ){ /* 0x01 -> modtime is present */
  6899. *pmTime = zipfileGetU32(&p[1]);
  6900. ret = 1;
  6901. }
  6902. break;
  6903. }
  6904. }
  6905. p += nByte;
  6906. }
  6907. return ret;
  6908. }
  6909. /*
  6910. ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
  6911. ** fields of the CDS structure passed as the only argument to a 32-bit
  6912. ** UNIX seconds-since-the-epoch timestamp. Return the result.
  6913. **
  6914. ** "Standard" MS-DOS time format:
  6915. **
  6916. ** File modification time:
  6917. ** Bits 00-04: seconds divided by 2
  6918. ** Bits 05-10: minute
  6919. ** Bits 11-15: hour
  6920. ** File modification date:
  6921. ** Bits 00-04: day
  6922. ** Bits 05-08: month (1-12)
  6923. ** Bits 09-15: years from 1980
  6924. **
  6925. ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
  6926. */
  6927. static u32 zipfileMtime(ZipfileCDS *pCDS){
  6928. int Y,M,D,X1,X2,A,B,sec,min,hr;
  6929. i64 JDsec;
  6930. Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
  6931. M = ((pCDS->mDate >> 5) & 0x0F);
  6932. D = (pCDS->mDate & 0x1F);
  6933. sec = (pCDS->mTime & 0x1F)*2;
  6934. min = (pCDS->mTime >> 5) & 0x3F;
  6935. hr = (pCDS->mTime >> 11) & 0x1F;
  6936. if( M<=2 ){
  6937. Y--;
  6938. M += 12;
  6939. }
  6940. X1 = 36525*(Y+4716)/100;
  6941. X2 = 306001*(M+1)/10000;
  6942. A = Y/100;
  6943. B = 2 - A + (A/4);
  6944. JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
  6945. return (u32)(JDsec - (i64)24405875*(i64)8640);
  6946. }
  6947. /*
  6948. ** The opposite of zipfileMtime(). This function populates the mTime and
  6949. ** mDate fields of the CDS structure passed as the first argument according
  6950. ** to the UNIX timestamp value passed as the second.
  6951. */
  6952. static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
  6953. /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
  6954. i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
  6955. int A, B, C, D, E;
  6956. int yr, mon, day;
  6957. int hr, min, sec;
  6958. A = (int)((JD - 1867216.25)/36524.25);
  6959. A = (int)(JD + 1 + A - (A/4));
  6960. B = A + 1524;
  6961. C = (int)((B - 122.1)/365.25);
  6962. D = (36525*(C&32767))/100;
  6963. E = (int)((B-D)/30.6001);
  6964. day = B - D - (int)(30.6001*E);
  6965. mon = (E<14 ? E-1 : E-13);
  6966. yr = mon>2 ? C-4716 : C-4715;
  6967. hr = (mUnixTime % (24*60*60)) / (60*60);
  6968. min = (mUnixTime % (60*60)) / 60;
  6969. sec = (mUnixTime % 60);
  6970. if( yr>=1980 ){
  6971. pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
  6972. pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
  6973. }else{
  6974. pCds->mDate = pCds->mTime = 0;
  6975. }
  6976. assert( mUnixTime<315507600
  6977. || mUnixTime==zipfileMtime(pCds)
  6978. || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
  6979. /* || (mUnixTime % 2) */
  6980. );
  6981. }
  6982. /*
  6983. ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
  6984. ** size) containing an entire zip archive image. Or, if aBlob is NULL,
  6985. ** then pFile is a file-handle open on a zip file. In either case, this
  6986. ** function creates a ZipfileEntry object based on the zip archive entry
  6987. ** for which the CDS record is at offset iOff.
  6988. **
  6989. ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
  6990. ** the new object. Otherwise, an SQLite error code is returned and the
  6991. ** final value of (*ppEntry) undefined.
  6992. */
  6993. static int zipfileGetEntry(
  6994. ZipfileTab *pTab, /* Store any error message here */
  6995. const u8 *aBlob, /* Pointer to in-memory file image */
  6996. int nBlob, /* Size of aBlob[] in bytes */
  6997. FILE *pFile, /* If aBlob==0, read from this file */
  6998. i64 iOff, /* Offset of CDS record */
  6999. ZipfileEntry **ppEntry /* OUT: Pointer to new object */
  7000. ){
  7001. u8 *aRead;
  7002. char **pzErr = &pTab->base.zErrMsg;
  7003. int rc = SQLITE_OK;
  7004. if( aBlob==0 ){
  7005. aRead = pTab->aBuffer;
  7006. rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
  7007. }else{
  7008. aRead = (u8*)&aBlob[iOff];
  7009. }
  7010. if( rc==SQLITE_OK ){
  7011. sqlite3_int64 nAlloc;
  7012. ZipfileEntry *pNew;
  7013. int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
  7014. int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
  7015. nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
  7016. nAlloc = sizeof(ZipfileEntry) + nExtra;
  7017. if( aBlob ){
  7018. nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
  7019. }
  7020. pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
  7021. if( pNew==0 ){
  7022. rc = SQLITE_NOMEM;
  7023. }else{
  7024. memset(pNew, 0, sizeof(ZipfileEntry));
  7025. rc = zipfileReadCDS(aRead, &pNew->cds);
  7026. if( rc!=SQLITE_OK ){
  7027. *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
  7028. }else if( aBlob==0 ){
  7029. rc = zipfileReadData(
  7030. pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
  7031. );
  7032. }else{
  7033. aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
  7034. }
  7035. }
  7036. if( rc==SQLITE_OK ){
  7037. u32 *pt = &pNew->mUnixTime;
  7038. pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
  7039. pNew->aExtra = (u8*)&pNew[1];
  7040. memcpy(pNew->aExtra, &aRead[nFile], nExtra);
  7041. if( pNew->cds.zFile==0 ){
  7042. rc = SQLITE_NOMEM;
  7043. }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
  7044. pNew->mUnixTime = zipfileMtime(&pNew->cds);
  7045. }
  7046. }
  7047. if( rc==SQLITE_OK ){
  7048. static const int szFix = ZIPFILE_LFH_FIXED_SZ;
  7049. ZipfileLFH lfh;
  7050. if( pFile ){
  7051. rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
  7052. }else{
  7053. aRead = (u8*)&aBlob[pNew->cds.iOffset];
  7054. }
  7055. if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
  7056. if( rc==SQLITE_OK ){
  7057. pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
  7058. pNew->iDataOff += lfh.nFile + lfh.nExtra;
  7059. if( aBlob && pNew->cds.szCompressed ){
  7060. pNew->aData = &pNew->aExtra[nExtra];
  7061. memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
  7062. }
  7063. }else{
  7064. *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
  7065. (int)pNew->cds.iOffset
  7066. );
  7067. }
  7068. }
  7069. if( rc!=SQLITE_OK ){
  7070. zipfileEntryFree(pNew);
  7071. }else{
  7072. *ppEntry = pNew;
  7073. }
  7074. }
  7075. return rc;
  7076. }
  7077. /*
  7078. ** Advance an ZipfileCsr to its next row of output.
  7079. */
  7080. static int zipfileNext(sqlite3_vtab_cursor *cur){
  7081. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  7082. int rc = SQLITE_OK;
  7083. if( pCsr->pFile ){
  7084. i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
  7085. zipfileEntryFree(pCsr->pCurrent);
  7086. pCsr->pCurrent = 0;
  7087. if( pCsr->iNextOff>=iEof ){
  7088. pCsr->bEof = 1;
  7089. }else{
  7090. ZipfileEntry *p = 0;
  7091. ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
  7092. rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
  7093. if( rc==SQLITE_OK ){
  7094. pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
  7095. pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
  7096. }
  7097. pCsr->pCurrent = p;
  7098. }
  7099. }else{
  7100. if( !pCsr->bNoop ){
  7101. pCsr->pCurrent = pCsr->pCurrent->pNext;
  7102. }
  7103. if( pCsr->pCurrent==0 ){
  7104. pCsr->bEof = 1;
  7105. }
  7106. }
  7107. pCsr->bNoop = 0;
  7108. return rc;
  7109. }
  7110. static void zipfileFree(void *p) {
  7111. sqlite3_free(p);
  7112. }
  7113. /*
  7114. ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
  7115. ** size is nOut bytes. This function uncompresses the data and sets the
  7116. ** return value in context pCtx to the result (a blob).
  7117. **
  7118. ** If an error occurs, an error code is left in pCtx instead.
  7119. */
  7120. static void zipfileInflate(
  7121. sqlite3_context *pCtx, /* Store result here */
  7122. const u8 *aIn, /* Compressed data */
  7123. int nIn, /* Size of buffer aIn[] in bytes */
  7124. int nOut /* Expected output size */
  7125. ){
  7126. u8 *aRes = sqlite3_malloc(nOut);
  7127. if( aRes==0 ){
  7128. sqlite3_result_error_nomem(pCtx);
  7129. }else{
  7130. int err;
  7131. z_stream str;
  7132. memset(&str, 0, sizeof(str));
  7133. str.next_in = (Byte*)aIn;
  7134. str.avail_in = nIn;
  7135. str.next_out = (Byte*)aRes;
  7136. str.avail_out = nOut;
  7137. err = inflateInit2(&str, -15);
  7138. if( err!=Z_OK ){
  7139. zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
  7140. }else{
  7141. err = inflate(&str, Z_NO_FLUSH);
  7142. if( err!=Z_STREAM_END ){
  7143. zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
  7144. }else{
  7145. sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
  7146. aRes = 0;
  7147. }
  7148. }
  7149. sqlite3_free(aRes);
  7150. inflateEnd(&str);
  7151. }
  7152. }
  7153. /*
  7154. ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
  7155. ** compresses it and sets (*ppOut) to point to a buffer containing the
  7156. ** compressed data. The caller is responsible for eventually calling
  7157. ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
  7158. ** is set to the size of buffer (*ppOut) in bytes.
  7159. **
  7160. ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
  7161. ** code is returned and an error message left in virtual-table handle
  7162. ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
  7163. ** case.
  7164. */
  7165. static int zipfileDeflate(
  7166. const u8 *aIn, int nIn, /* Input */
  7167. u8 **ppOut, int *pnOut, /* Output */
  7168. char **pzErr /* OUT: Error message */
  7169. ){
  7170. int rc = SQLITE_OK;
  7171. sqlite3_int64 nAlloc;
  7172. z_stream str;
  7173. u8 *aOut;
  7174. memset(&str, 0, sizeof(str));
  7175. str.next_in = (Bytef*)aIn;
  7176. str.avail_in = nIn;
  7177. deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
  7178. nAlloc = deflateBound(&str, nIn);
  7179. aOut = (u8*)sqlite3_malloc64(nAlloc);
  7180. if( aOut==0 ){
  7181. rc = SQLITE_NOMEM;
  7182. }else{
  7183. int res;
  7184. str.next_out = aOut;
  7185. str.avail_out = nAlloc;
  7186. res = deflate(&str, Z_FINISH);
  7187. if( res==Z_STREAM_END ){
  7188. *ppOut = aOut;
  7189. *pnOut = (int)str.total_out;
  7190. }else{
  7191. sqlite3_free(aOut);
  7192. *pzErr = sqlite3_mprintf("zipfile: deflate() error");
  7193. rc = SQLITE_ERROR;
  7194. }
  7195. deflateEnd(&str);
  7196. }
  7197. return rc;
  7198. }
  7199. /*
  7200. ** Return values of columns for the row at which the series_cursor
  7201. ** is currently pointing.
  7202. */
  7203. static int zipfileColumn(
  7204. sqlite3_vtab_cursor *cur, /* The cursor */
  7205. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  7206. int i /* Which column to return */
  7207. ){
  7208. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  7209. ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
  7210. int rc = SQLITE_OK;
  7211. switch( i ){
  7212. case 0: /* name */
  7213. sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
  7214. break;
  7215. case 1: /* mode */
  7216. /* TODO: Whether or not the following is correct surely depends on
  7217. ** the platform on which the archive was created. */
  7218. sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
  7219. break;
  7220. case 2: { /* mtime */
  7221. sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
  7222. break;
  7223. }
  7224. case 3: { /* sz */
  7225. if( sqlite3_vtab_nochange(ctx)==0 ){
  7226. sqlite3_result_int64(ctx, pCDS->szUncompressed);
  7227. }
  7228. break;
  7229. }
  7230. case 4: /* rawdata */
  7231. if( sqlite3_vtab_nochange(ctx) ) break;
  7232. case 5: { /* data */
  7233. if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
  7234. int sz = pCDS->szCompressed;
  7235. int szFinal = pCDS->szUncompressed;
  7236. if( szFinal>0 ){
  7237. u8 *aBuf;
  7238. u8 *aFree = 0;
  7239. if( pCsr->pCurrent->aData ){
  7240. aBuf = pCsr->pCurrent->aData;
  7241. }else{
  7242. aBuf = aFree = sqlite3_malloc64(sz);
  7243. if( aBuf==0 ){
  7244. rc = SQLITE_NOMEM;
  7245. }else{
  7246. FILE *pFile = pCsr->pFile;
  7247. if( pFile==0 ){
  7248. pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
  7249. }
  7250. rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
  7251. &pCsr->base.pVtab->zErrMsg
  7252. );
  7253. }
  7254. }
  7255. if( rc==SQLITE_OK ){
  7256. if( i==5 && pCDS->iCompression ){
  7257. zipfileInflate(ctx, aBuf, sz, szFinal);
  7258. }else{
  7259. sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
  7260. }
  7261. }
  7262. sqlite3_free(aFree);
  7263. }else{
  7264. /* Figure out if this is a directory or a zero-sized file. Consider
  7265. ** it to be a directory either if the mode suggests so, or if
  7266. ** the final character in the name is '/'. */
  7267. u32 mode = pCDS->iExternalAttr >> 16;
  7268. if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
  7269. sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
  7270. }
  7271. }
  7272. }
  7273. break;
  7274. }
  7275. case 6: /* method */
  7276. sqlite3_result_int(ctx, pCDS->iCompression);
  7277. break;
  7278. default: /* z */
  7279. assert( i==7 );
  7280. sqlite3_result_int64(ctx, pCsr->iId);
  7281. break;
  7282. }
  7283. return rc;
  7284. }
  7285. /*
  7286. ** Return TRUE if the cursor is at EOF.
  7287. */
  7288. static int zipfileEof(sqlite3_vtab_cursor *cur){
  7289. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  7290. return pCsr->bEof;
  7291. }
  7292. /*
  7293. ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
  7294. ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
  7295. ** is guaranteed to be a file-handle open on a zip file.
  7296. **
  7297. ** This function attempts to locate the EOCD record within the zip archive
  7298. ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
  7299. ** returned if successful. Otherwise, an SQLite error code is returned and
  7300. ** an English language error message may be left in virtual-table pTab.
  7301. */
  7302. static int zipfileReadEOCD(
  7303. ZipfileTab *pTab, /* Return errors here */
  7304. const u8 *aBlob, /* Pointer to in-memory file image */
  7305. int nBlob, /* Size of aBlob[] in bytes */
  7306. FILE *pFile, /* Read from this file if aBlob==0 */
  7307. ZipfileEOCD *pEOCD /* Object to populate */
  7308. ){
  7309. u8 *aRead = pTab->aBuffer; /* Temporary buffer */
  7310. int nRead; /* Bytes to read from file */
  7311. int rc = SQLITE_OK;
  7312. memset(pEOCD, 0, sizeof(ZipfileEOCD));
  7313. if( aBlob==0 ){
  7314. i64 iOff; /* Offset to read from */
  7315. i64 szFile; /* Total size of file in bytes */
  7316. fseek(pFile, 0, SEEK_END);
  7317. szFile = (i64)ftell(pFile);
  7318. if( szFile==0 ){
  7319. return SQLITE_OK;
  7320. }
  7321. nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
  7322. iOff = szFile - nRead;
  7323. rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
  7324. }else{
  7325. nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
  7326. aRead = (u8*)&aBlob[nBlob-nRead];
  7327. }
  7328. if( rc==SQLITE_OK ){
  7329. int i;
  7330. /* Scan backwards looking for the signature bytes */
  7331. for(i=nRead-20; i>=0; i--){
  7332. if( aRead[i]==0x50 && aRead[i+1]==0x4b
  7333. && aRead[i+2]==0x05 && aRead[i+3]==0x06
  7334. ){
  7335. break;
  7336. }
  7337. }
  7338. if( i<0 ){
  7339. pTab->base.zErrMsg = sqlite3_mprintf(
  7340. "cannot find end of central directory record"
  7341. );
  7342. return SQLITE_ERROR;
  7343. }
  7344. aRead += i+4;
  7345. pEOCD->iDisk = zipfileRead16(aRead);
  7346. pEOCD->iFirstDisk = zipfileRead16(aRead);
  7347. pEOCD->nEntry = zipfileRead16(aRead);
  7348. pEOCD->nEntryTotal = zipfileRead16(aRead);
  7349. pEOCD->nSize = zipfileRead32(aRead);
  7350. pEOCD->iOffset = zipfileRead32(aRead);
  7351. }
  7352. return rc;
  7353. }
  7354. /*
  7355. ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
  7356. ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
  7357. ** to the end of the list. Otherwise, it is added to the list immediately
  7358. ** before pBefore (which is guaranteed to be a part of said list).
  7359. */
  7360. static void zipfileAddEntry(
  7361. ZipfileTab *pTab,
  7362. ZipfileEntry *pBefore,
  7363. ZipfileEntry *pNew
  7364. ){
  7365. assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
  7366. assert( pNew->pNext==0 );
  7367. if( pBefore==0 ){
  7368. if( pTab->pFirstEntry==0 ){
  7369. pTab->pFirstEntry = pTab->pLastEntry = pNew;
  7370. }else{
  7371. assert( pTab->pLastEntry->pNext==0 );
  7372. pTab->pLastEntry->pNext = pNew;
  7373. pTab->pLastEntry = pNew;
  7374. }
  7375. }else{
  7376. ZipfileEntry **pp;
  7377. for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
  7378. pNew->pNext = pBefore;
  7379. *pp = pNew;
  7380. }
  7381. }
  7382. static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
  7383. ZipfileEOCD eocd;
  7384. int rc;
  7385. int i;
  7386. i64 iOff;
  7387. rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
  7388. iOff = eocd.iOffset;
  7389. for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
  7390. ZipfileEntry *pNew = 0;
  7391. rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
  7392. if( rc==SQLITE_OK ){
  7393. zipfileAddEntry(pTab, 0, pNew);
  7394. iOff += ZIPFILE_CDS_FIXED_SZ;
  7395. iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
  7396. }
  7397. }
  7398. return rc;
  7399. }
  7400. /*
  7401. ** xFilter callback.
  7402. */
  7403. static int zipfileFilter(
  7404. sqlite3_vtab_cursor *cur,
  7405. int idxNum, const char *idxStr,
  7406. int argc, sqlite3_value **argv
  7407. ){
  7408. ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
  7409. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  7410. const char *zFile = 0; /* Zip file to scan */
  7411. int rc = SQLITE_OK; /* Return Code */
  7412. int bInMemory = 0; /* True for an in-memory zipfile */
  7413. zipfileResetCursor(pCsr);
  7414. if( pTab->zFile ){
  7415. zFile = pTab->zFile;
  7416. }else if( idxNum==0 ){
  7417. zipfileCursorErr(pCsr, "zipfile() function requires an argument");
  7418. return SQLITE_ERROR;
  7419. }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
  7420. static const u8 aEmptyBlob = 0;
  7421. const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
  7422. int nBlob = sqlite3_value_bytes(argv[0]);
  7423. assert( pTab->pFirstEntry==0 );
  7424. if( aBlob==0 ){
  7425. aBlob = &aEmptyBlob;
  7426. nBlob = 0;
  7427. }
  7428. rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
  7429. pCsr->pFreeEntry = pTab->pFirstEntry;
  7430. pTab->pFirstEntry = pTab->pLastEntry = 0;
  7431. if( rc!=SQLITE_OK ) return rc;
  7432. bInMemory = 1;
  7433. }else{
  7434. zFile = (const char*)sqlite3_value_text(argv[0]);
  7435. }
  7436. if( 0==pTab->pWriteFd && 0==bInMemory ){
  7437. pCsr->pFile = fopen(zFile, "rb");
  7438. if( pCsr->pFile==0 ){
  7439. zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
  7440. rc = SQLITE_ERROR;
  7441. }else{
  7442. rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
  7443. if( rc==SQLITE_OK ){
  7444. if( pCsr->eocd.nEntry==0 ){
  7445. pCsr->bEof = 1;
  7446. }else{
  7447. pCsr->iNextOff = pCsr->eocd.iOffset;
  7448. rc = zipfileNext(cur);
  7449. }
  7450. }
  7451. }
  7452. }else{
  7453. pCsr->bNoop = 1;
  7454. pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
  7455. rc = zipfileNext(cur);
  7456. }
  7457. return rc;
  7458. }
  7459. /*
  7460. ** xBestIndex callback.
  7461. */
  7462. static int zipfileBestIndex(
  7463. sqlite3_vtab *tab,
  7464. sqlite3_index_info *pIdxInfo
  7465. ){
  7466. int i;
  7467. int idx = -1;
  7468. int unusable = 0;
  7469. for(i=0; i<pIdxInfo->nConstraint; i++){
  7470. const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
  7471. if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
  7472. if( pCons->usable==0 ){
  7473. unusable = 1;
  7474. }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  7475. idx = i;
  7476. }
  7477. }
  7478. pIdxInfo->estimatedCost = 1000.0;
  7479. if( idx>=0 ){
  7480. pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
  7481. pIdxInfo->aConstraintUsage[idx].omit = 1;
  7482. pIdxInfo->idxNum = 1;
  7483. }else if( unusable ){
  7484. return SQLITE_CONSTRAINT;
  7485. }
  7486. return SQLITE_OK;
  7487. }
  7488. static ZipfileEntry *zipfileNewEntry(const char *zPath){
  7489. ZipfileEntry *pNew;
  7490. pNew = sqlite3_malloc(sizeof(ZipfileEntry));
  7491. if( pNew ){
  7492. memset(pNew, 0, sizeof(ZipfileEntry));
  7493. pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
  7494. if( pNew->cds.zFile==0 ){
  7495. sqlite3_free(pNew);
  7496. pNew = 0;
  7497. }
  7498. }
  7499. return pNew;
  7500. }
  7501. static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
  7502. ZipfileCDS *pCds = &pEntry->cds;
  7503. u8 *a = aBuf;
  7504. pCds->nExtra = 9;
  7505. /* Write the LFH itself */
  7506. zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
  7507. zipfileWrite16(a, pCds->iVersionExtract);
  7508. zipfileWrite16(a, pCds->flags);
  7509. zipfileWrite16(a, pCds->iCompression);
  7510. zipfileWrite16(a, pCds->mTime);
  7511. zipfileWrite16(a, pCds->mDate);
  7512. zipfileWrite32(a, pCds->crc32);
  7513. zipfileWrite32(a, pCds->szCompressed);
  7514. zipfileWrite32(a, pCds->szUncompressed);
  7515. zipfileWrite16(a, (u16)pCds->nFile);
  7516. zipfileWrite16(a, pCds->nExtra);
  7517. assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
  7518. /* Add the file name */
  7519. memcpy(a, pCds->zFile, (int)pCds->nFile);
  7520. a += (int)pCds->nFile;
  7521. /* The "extra" data */
  7522. zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
  7523. zipfileWrite16(a, 5);
  7524. *a++ = 0x01;
  7525. zipfileWrite32(a, pEntry->mUnixTime);
  7526. return a-aBuf;
  7527. }
  7528. static int zipfileAppendEntry(
  7529. ZipfileTab *pTab,
  7530. ZipfileEntry *pEntry,
  7531. const u8 *pData,
  7532. int nData
  7533. ){
  7534. u8 *aBuf = pTab->aBuffer;
  7535. int nBuf;
  7536. int rc;
  7537. nBuf = zipfileSerializeLFH(pEntry, aBuf);
  7538. rc = zipfileAppendData(pTab, aBuf, nBuf);
  7539. if( rc==SQLITE_OK ){
  7540. pEntry->iDataOff = pTab->szCurrent;
  7541. rc = zipfileAppendData(pTab, pData, nData);
  7542. }
  7543. return rc;
  7544. }
  7545. static int zipfileGetMode(
  7546. sqlite3_value *pVal,
  7547. int bIsDir, /* If true, default to directory */
  7548. u32 *pMode, /* OUT: Mode value */
  7549. char **pzErr /* OUT: Error message */
  7550. ){
  7551. const char *z = (const char*)sqlite3_value_text(pVal);
  7552. u32 mode = 0;
  7553. if( z==0 ){
  7554. mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
  7555. }else if( z[0]>='0' && z[0]<='9' ){
  7556. mode = (unsigned int)sqlite3_value_int(pVal);
  7557. }else{
  7558. const char zTemplate[11] = "-rwxrwxrwx";
  7559. int i;
  7560. if( strlen(z)!=10 ) goto parse_error;
  7561. switch( z[0] ){
  7562. case '-': mode |= S_IFREG; break;
  7563. case 'd': mode |= S_IFDIR; break;
  7564. case 'l': mode |= S_IFLNK; break;
  7565. default: goto parse_error;
  7566. }
  7567. for(i=1; i<10; i++){
  7568. if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
  7569. else if( z[i]!='-' ) goto parse_error;
  7570. }
  7571. }
  7572. if( ((mode & S_IFDIR)==0)==bIsDir ){
  7573. /* The "mode" attribute is a directory, but data has been specified.
  7574. ** Or vice-versa - no data but "mode" is a file or symlink. */
  7575. *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
  7576. return SQLITE_CONSTRAINT;
  7577. }
  7578. *pMode = mode;
  7579. return SQLITE_OK;
  7580. parse_error:
  7581. *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
  7582. return SQLITE_ERROR;
  7583. }
  7584. /*
  7585. ** Both (const char*) arguments point to nul-terminated strings. Argument
  7586. ** nB is the value of strlen(zB). This function returns 0 if the strings are
  7587. ** identical, ignoring any trailing '/' character in either path. */
  7588. static int zipfileComparePath(const char *zA, const char *zB, int nB){
  7589. int nA = (int)strlen(zA);
  7590. if( nA>0 && zA[nA-1]=='/' ) nA--;
  7591. if( nB>0 && zB[nB-1]=='/' ) nB--;
  7592. if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
  7593. return 1;
  7594. }
  7595. static int zipfileBegin(sqlite3_vtab *pVtab){
  7596. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  7597. int rc = SQLITE_OK;
  7598. assert( pTab->pWriteFd==0 );
  7599. if( pTab->zFile==0 || pTab->zFile[0]==0 ){
  7600. pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
  7601. return SQLITE_ERROR;
  7602. }
  7603. /* Open a write fd on the file. Also load the entire central directory
  7604. ** structure into memory. During the transaction any new file data is
  7605. ** appended to the archive file, but the central directory is accumulated
  7606. ** in main-memory until the transaction is committed. */
  7607. pTab->pWriteFd = fopen(pTab->zFile, "ab+");
  7608. if( pTab->pWriteFd==0 ){
  7609. pTab->base.zErrMsg = sqlite3_mprintf(
  7610. "zipfile: failed to open file %s for writing", pTab->zFile
  7611. );
  7612. rc = SQLITE_ERROR;
  7613. }else{
  7614. fseek(pTab->pWriteFd, 0, SEEK_END);
  7615. pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
  7616. rc = zipfileLoadDirectory(pTab, 0, 0);
  7617. }
  7618. if( rc!=SQLITE_OK ){
  7619. zipfileCleanupTransaction(pTab);
  7620. }
  7621. return rc;
  7622. }
  7623. /*
  7624. ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
  7625. ** time(2)).
  7626. */
  7627. static u32 zipfileTime(void){
  7628. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  7629. u32 ret;
  7630. if( pVfs==0 ) return 0;
  7631. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  7632. i64 ms;
  7633. pVfs->xCurrentTimeInt64(pVfs, &ms);
  7634. ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
  7635. }else{
  7636. double day;
  7637. pVfs->xCurrentTime(pVfs, &day);
  7638. ret = (u32)((day - 2440587.5) * 86400);
  7639. }
  7640. return ret;
  7641. }
  7642. /*
  7643. ** Return a 32-bit timestamp in UNIX epoch format.
  7644. **
  7645. ** If the value passed as the only argument is either NULL or an SQL NULL,
  7646. ** return the current time. Otherwise, return the value stored in (*pVal)
  7647. ** cast to a 32-bit unsigned integer.
  7648. */
  7649. static u32 zipfileGetTime(sqlite3_value *pVal){
  7650. if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
  7651. return zipfileTime();
  7652. }
  7653. return (u32)sqlite3_value_int64(pVal);
  7654. }
  7655. /*
  7656. ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
  7657. ** linked list. Remove it from the list and free the object.
  7658. */
  7659. static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
  7660. if( pOld ){
  7661. ZipfileEntry **pp;
  7662. for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
  7663. *pp = (*pp)->pNext;
  7664. zipfileEntryFree(pOld);
  7665. }
  7666. }
  7667. /*
  7668. ** xUpdate method.
  7669. */
  7670. static int zipfileUpdate(
  7671. sqlite3_vtab *pVtab,
  7672. int nVal,
  7673. sqlite3_value **apVal,
  7674. sqlite_int64 *pRowid
  7675. ){
  7676. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  7677. int rc = SQLITE_OK; /* Return Code */
  7678. ZipfileEntry *pNew = 0; /* New in-memory CDS entry */
  7679. u32 mode = 0; /* Mode for new entry */
  7680. u32 mTime = 0; /* Modification time for new entry */
  7681. i64 sz = 0; /* Uncompressed size */
  7682. const char *zPath = 0; /* Path for new entry */
  7683. int nPath = 0; /* strlen(zPath) */
  7684. const u8 *pData = 0; /* Pointer to buffer containing content */
  7685. int nData = 0; /* Size of pData buffer in bytes */
  7686. int iMethod = 0; /* Compression method for new entry */
  7687. u8 *pFree = 0; /* Free this */
  7688. char *zFree = 0; /* Also free this */
  7689. ZipfileEntry *pOld = 0;
  7690. ZipfileEntry *pOld2 = 0;
  7691. int bUpdate = 0; /* True for an update that modifies "name" */
  7692. int bIsDir = 0;
  7693. u32 iCrc32 = 0;
  7694. if( pTab->pWriteFd==0 ){
  7695. rc = zipfileBegin(pVtab);
  7696. if( rc!=SQLITE_OK ) return rc;
  7697. }
  7698. /* If this is a DELETE or UPDATE, find the archive entry to delete. */
  7699. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  7700. const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
  7701. int nDelete = (int)strlen(zDelete);
  7702. if( nVal>1 ){
  7703. const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
  7704. if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
  7705. bUpdate = 1;
  7706. }
  7707. }
  7708. for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
  7709. if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
  7710. break;
  7711. }
  7712. assert( pOld->pNext );
  7713. }
  7714. }
  7715. if( nVal>1 ){
  7716. /* Check that "sz" and "rawdata" are both NULL: */
  7717. if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
  7718. zipfileTableErr(pTab, "sz must be NULL");
  7719. rc = SQLITE_CONSTRAINT;
  7720. }
  7721. if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
  7722. zipfileTableErr(pTab, "rawdata must be NULL");
  7723. rc = SQLITE_CONSTRAINT;
  7724. }
  7725. if( rc==SQLITE_OK ){
  7726. if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
  7727. /* data=NULL. A directory */
  7728. bIsDir = 1;
  7729. }else{
  7730. /* Value specified for "data", and possibly "method". This must be
  7731. ** a regular file or a symlink. */
  7732. const u8 *aIn = sqlite3_value_blob(apVal[7]);
  7733. int nIn = sqlite3_value_bytes(apVal[7]);
  7734. int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
  7735. iMethod = sqlite3_value_int(apVal[8]);
  7736. sz = nIn;
  7737. pData = aIn;
  7738. nData = nIn;
  7739. if( iMethod!=0 && iMethod!=8 ){
  7740. zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
  7741. rc = SQLITE_CONSTRAINT;
  7742. }else{
  7743. if( bAuto || iMethod ){
  7744. int nCmp;
  7745. rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
  7746. if( rc==SQLITE_OK ){
  7747. if( iMethod || nCmp<nIn ){
  7748. iMethod = 8;
  7749. pData = pFree;
  7750. nData = nCmp;
  7751. }
  7752. }
  7753. }
  7754. iCrc32 = crc32(0, aIn, nIn);
  7755. }
  7756. }
  7757. }
  7758. if( rc==SQLITE_OK ){
  7759. rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
  7760. }
  7761. if( rc==SQLITE_OK ){
  7762. zPath = (const char*)sqlite3_value_text(apVal[2]);
  7763. if( zPath==0 ) zPath = "";
  7764. nPath = (int)strlen(zPath);
  7765. mTime = zipfileGetTime(apVal[4]);
  7766. }
  7767. if( rc==SQLITE_OK && bIsDir ){
  7768. /* For a directory, check that the last character in the path is a
  7769. ** '/'. This appears to be required for compatibility with info-zip
  7770. ** (the unzip command on unix). It does not create directories
  7771. ** otherwise. */
  7772. if( nPath<=0 || zPath[nPath-1]!='/' ){
  7773. zFree = sqlite3_mprintf("%s/", zPath);
  7774. zPath = (const char*)zFree;
  7775. if( zFree==0 ){
  7776. rc = SQLITE_NOMEM;
  7777. nPath = 0;
  7778. }else{
  7779. nPath = (int)strlen(zPath);
  7780. }
  7781. }
  7782. }
  7783. /* Check that we're not inserting a duplicate entry -OR- updating an
  7784. ** entry with a path, thereby making it into a duplicate. */
  7785. if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
  7786. ZipfileEntry *p;
  7787. for(p=pTab->pFirstEntry; p; p=p->pNext){
  7788. if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
  7789. switch( sqlite3_vtab_on_conflict(pTab->db) ){
  7790. case SQLITE_IGNORE: {
  7791. goto zipfile_update_done;
  7792. }
  7793. case SQLITE_REPLACE: {
  7794. pOld2 = p;
  7795. break;
  7796. }
  7797. default: {
  7798. zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
  7799. rc = SQLITE_CONSTRAINT;
  7800. break;
  7801. }
  7802. }
  7803. break;
  7804. }
  7805. }
  7806. }
  7807. if( rc==SQLITE_OK ){
  7808. /* Create the new CDS record. */
  7809. pNew = zipfileNewEntry(zPath);
  7810. if( pNew==0 ){
  7811. rc = SQLITE_NOMEM;
  7812. }else{
  7813. pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
  7814. pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
  7815. pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
  7816. pNew->cds.iCompression = (u16)iMethod;
  7817. zipfileMtimeToDos(&pNew->cds, mTime);
  7818. pNew->cds.crc32 = iCrc32;
  7819. pNew->cds.szCompressed = nData;
  7820. pNew->cds.szUncompressed = (u32)sz;
  7821. pNew->cds.iExternalAttr = (mode<<16);
  7822. pNew->cds.iOffset = (u32)pTab->szCurrent;
  7823. pNew->cds.nFile = (u16)nPath;
  7824. pNew->mUnixTime = (u32)mTime;
  7825. rc = zipfileAppendEntry(pTab, pNew, pData, nData);
  7826. zipfileAddEntry(pTab, pOld, pNew);
  7827. }
  7828. }
  7829. }
  7830. if( rc==SQLITE_OK && (pOld || pOld2) ){
  7831. ZipfileCsr *pCsr;
  7832. for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
  7833. if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
  7834. pCsr->pCurrent = pCsr->pCurrent->pNext;
  7835. pCsr->bNoop = 1;
  7836. }
  7837. }
  7838. zipfileRemoveEntryFromList(pTab, pOld);
  7839. zipfileRemoveEntryFromList(pTab, pOld2);
  7840. }
  7841. zipfile_update_done:
  7842. sqlite3_free(pFree);
  7843. sqlite3_free(zFree);
  7844. return rc;
  7845. }
  7846. static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
  7847. u8 *a = aBuf;
  7848. zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
  7849. zipfileWrite16(a, p->iDisk);
  7850. zipfileWrite16(a, p->iFirstDisk);
  7851. zipfileWrite16(a, p->nEntry);
  7852. zipfileWrite16(a, p->nEntryTotal);
  7853. zipfileWrite32(a, p->nSize);
  7854. zipfileWrite32(a, p->iOffset);
  7855. zipfileWrite16(a, 0); /* Size of trailing comment in bytes*/
  7856. return a-aBuf;
  7857. }
  7858. static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
  7859. int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
  7860. assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
  7861. return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
  7862. }
  7863. /*
  7864. ** Serialize the CDS structure into buffer aBuf[]. Return the number
  7865. ** of bytes written.
  7866. */
  7867. static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
  7868. u8 *a = aBuf;
  7869. ZipfileCDS *pCDS = &pEntry->cds;
  7870. if( pEntry->aExtra==0 ){
  7871. pCDS->nExtra = 9;
  7872. }
  7873. zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
  7874. zipfileWrite16(a, pCDS->iVersionMadeBy);
  7875. zipfileWrite16(a, pCDS->iVersionExtract);
  7876. zipfileWrite16(a, pCDS->flags);
  7877. zipfileWrite16(a, pCDS->iCompression);
  7878. zipfileWrite16(a, pCDS->mTime);
  7879. zipfileWrite16(a, pCDS->mDate);
  7880. zipfileWrite32(a, pCDS->crc32);
  7881. zipfileWrite32(a, pCDS->szCompressed);
  7882. zipfileWrite32(a, pCDS->szUncompressed);
  7883. assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
  7884. zipfileWrite16(a, pCDS->nFile);
  7885. zipfileWrite16(a, pCDS->nExtra);
  7886. zipfileWrite16(a, pCDS->nComment);
  7887. zipfileWrite16(a, pCDS->iDiskStart);
  7888. zipfileWrite16(a, pCDS->iInternalAttr);
  7889. zipfileWrite32(a, pCDS->iExternalAttr);
  7890. zipfileWrite32(a, pCDS->iOffset);
  7891. memcpy(a, pCDS->zFile, pCDS->nFile);
  7892. a += pCDS->nFile;
  7893. if( pEntry->aExtra ){
  7894. int n = (int)pCDS->nExtra + (int)pCDS->nComment;
  7895. memcpy(a, pEntry->aExtra, n);
  7896. a += n;
  7897. }else{
  7898. assert( pCDS->nExtra==9 );
  7899. zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
  7900. zipfileWrite16(a, 5);
  7901. *a++ = 0x01;
  7902. zipfileWrite32(a, pEntry->mUnixTime);
  7903. }
  7904. return a-aBuf;
  7905. }
  7906. static int zipfileCommit(sqlite3_vtab *pVtab){
  7907. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  7908. int rc = SQLITE_OK;
  7909. if( pTab->pWriteFd ){
  7910. i64 iOffset = pTab->szCurrent;
  7911. ZipfileEntry *p;
  7912. ZipfileEOCD eocd;
  7913. int nEntry = 0;
  7914. /* Write out all entries */
  7915. for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
  7916. int n = zipfileSerializeCDS(p, pTab->aBuffer);
  7917. rc = zipfileAppendData(pTab, pTab->aBuffer, n);
  7918. nEntry++;
  7919. }
  7920. /* Write out the EOCD record */
  7921. eocd.iDisk = 0;
  7922. eocd.iFirstDisk = 0;
  7923. eocd.nEntry = (u16)nEntry;
  7924. eocd.nEntryTotal = (u16)nEntry;
  7925. eocd.nSize = (u32)(pTab->szCurrent - iOffset);
  7926. eocd.iOffset = (u32)iOffset;
  7927. rc = zipfileAppendEOCD(pTab, &eocd);
  7928. zipfileCleanupTransaction(pTab);
  7929. }
  7930. return rc;
  7931. }
  7932. static int zipfileRollback(sqlite3_vtab *pVtab){
  7933. return zipfileCommit(pVtab);
  7934. }
  7935. static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
  7936. ZipfileCsr *pCsr;
  7937. for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
  7938. if( iId==pCsr->iId ) break;
  7939. }
  7940. return pCsr;
  7941. }
  7942. static void zipfileFunctionCds(
  7943. sqlite3_context *context,
  7944. int argc,
  7945. sqlite3_value **argv
  7946. ){
  7947. ZipfileCsr *pCsr;
  7948. ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
  7949. assert( argc>0 );
  7950. pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
  7951. if( pCsr ){
  7952. ZipfileCDS *p = &pCsr->pCurrent->cds;
  7953. char *zRes = sqlite3_mprintf("{"
  7954. "\"version-made-by\" : %u, "
  7955. "\"version-to-extract\" : %u, "
  7956. "\"flags\" : %u, "
  7957. "\"compression\" : %u, "
  7958. "\"time\" : %u, "
  7959. "\"date\" : %u, "
  7960. "\"crc32\" : %u, "
  7961. "\"compressed-size\" : %u, "
  7962. "\"uncompressed-size\" : %u, "
  7963. "\"file-name-length\" : %u, "
  7964. "\"extra-field-length\" : %u, "
  7965. "\"file-comment-length\" : %u, "
  7966. "\"disk-number-start\" : %u, "
  7967. "\"internal-attr\" : %u, "
  7968. "\"external-attr\" : %u, "
  7969. "\"offset\" : %u }",
  7970. (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
  7971. (u32)p->flags, (u32)p->iCompression,
  7972. (u32)p->mTime, (u32)p->mDate,
  7973. (u32)p->crc32, (u32)p->szCompressed,
  7974. (u32)p->szUncompressed, (u32)p->nFile,
  7975. (u32)p->nExtra, (u32)p->nComment,
  7976. (u32)p->iDiskStart, (u32)p->iInternalAttr,
  7977. (u32)p->iExternalAttr, (u32)p->iOffset
  7978. );
  7979. if( zRes==0 ){
  7980. sqlite3_result_error_nomem(context);
  7981. }else{
  7982. sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
  7983. sqlite3_free(zRes);
  7984. }
  7985. }
  7986. }
  7987. /*
  7988. ** xFindFunction method.
  7989. */
  7990. static int zipfileFindFunction(
  7991. sqlite3_vtab *pVtab, /* Virtual table handle */
  7992. int nArg, /* Number of SQL function arguments */
  7993. const char *zName, /* Name of SQL function */
  7994. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  7995. void **ppArg /* OUT: User data for *pxFunc */
  7996. ){
  7997. if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
  7998. *pxFunc = zipfileFunctionCds;
  7999. *ppArg = (void*)pVtab;
  8000. return 1;
  8001. }
  8002. return 0;
  8003. }
  8004. typedef struct ZipfileBuffer ZipfileBuffer;
  8005. struct ZipfileBuffer {
  8006. u8 *a; /* Pointer to buffer */
  8007. int n; /* Size of buffer in bytes */
  8008. int nAlloc; /* Byte allocated at a[] */
  8009. };
  8010. typedef struct ZipfileCtx ZipfileCtx;
  8011. struct ZipfileCtx {
  8012. int nEntry;
  8013. ZipfileBuffer body;
  8014. ZipfileBuffer cds;
  8015. };
  8016. static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
  8017. if( pBuf->n+nByte>pBuf->nAlloc ){
  8018. u8 *aNew;
  8019. sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
  8020. int nReq = pBuf->n + nByte;
  8021. while( nNew<nReq ) nNew = nNew*2;
  8022. aNew = sqlite3_realloc64(pBuf->a, nNew);
  8023. if( aNew==0 ) return SQLITE_NOMEM;
  8024. pBuf->a = aNew;
  8025. pBuf->nAlloc = (int)nNew;
  8026. }
  8027. return SQLITE_OK;
  8028. }
  8029. /*
  8030. ** xStep() callback for the zipfile() aggregate. This can be called in
  8031. ** any of the following ways:
  8032. **
  8033. ** SELECT zipfile(name,data) ...
  8034. ** SELECT zipfile(name,mode,mtime,data) ...
  8035. ** SELECT zipfile(name,mode,mtime,data,method) ...
  8036. */
  8037. static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
  8038. ZipfileCtx *p; /* Aggregate function context */
  8039. ZipfileEntry e; /* New entry to add to zip archive */
  8040. sqlite3_value *pName = 0;
  8041. sqlite3_value *pMode = 0;
  8042. sqlite3_value *pMtime = 0;
  8043. sqlite3_value *pData = 0;
  8044. sqlite3_value *pMethod = 0;
  8045. int bIsDir = 0;
  8046. u32 mode;
  8047. int rc = SQLITE_OK;
  8048. char *zErr = 0;
  8049. int iMethod = -1; /* Compression method to use (0 or 8) */
  8050. const u8 *aData = 0; /* Possibly compressed data for new entry */
  8051. int nData = 0; /* Size of aData[] in bytes */
  8052. int szUncompressed = 0; /* Size of data before compression */
  8053. u8 *aFree = 0; /* Free this before returning */
  8054. u32 iCrc32 = 0; /* crc32 of uncompressed data */
  8055. char *zName = 0; /* Path (name) of new entry */
  8056. int nName = 0; /* Size of zName in bytes */
  8057. char *zFree = 0; /* Free this before returning */
  8058. int nByte;
  8059. memset(&e, 0, sizeof(e));
  8060. p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
  8061. if( p==0 ) return;
  8062. /* Martial the arguments into stack variables */
  8063. if( nVal!=2 && nVal!=4 && nVal!=5 ){
  8064. zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
  8065. rc = SQLITE_ERROR;
  8066. goto zipfile_step_out;
  8067. }
  8068. pName = apVal[0];
  8069. if( nVal==2 ){
  8070. pData = apVal[1];
  8071. }else{
  8072. pMode = apVal[1];
  8073. pMtime = apVal[2];
  8074. pData = apVal[3];
  8075. if( nVal==5 ){
  8076. pMethod = apVal[4];
  8077. }
  8078. }
  8079. /* Check that the 'name' parameter looks ok. */
  8080. zName = (char*)sqlite3_value_text(pName);
  8081. nName = sqlite3_value_bytes(pName);
  8082. if( zName==0 ){
  8083. zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
  8084. rc = SQLITE_ERROR;
  8085. goto zipfile_step_out;
  8086. }
  8087. /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
  8088. ** deflate compression) or NULL (choose automatically). */
  8089. if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
  8090. iMethod = (int)sqlite3_value_int64(pMethod);
  8091. if( iMethod!=0 && iMethod!=8 ){
  8092. zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
  8093. rc = SQLITE_ERROR;
  8094. goto zipfile_step_out;
  8095. }
  8096. }
  8097. /* Now inspect the data. If this is NULL, then the new entry must be a
  8098. ** directory. Otherwise, figure out whether or not the data should
  8099. ** be deflated or simply stored in the zip archive. */
  8100. if( sqlite3_value_type(pData)==SQLITE_NULL ){
  8101. bIsDir = 1;
  8102. iMethod = 0;
  8103. }else{
  8104. aData = sqlite3_value_blob(pData);
  8105. szUncompressed = nData = sqlite3_value_bytes(pData);
  8106. iCrc32 = crc32(0, aData, nData);
  8107. if( iMethod<0 || iMethod==8 ){
  8108. int nOut = 0;
  8109. rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
  8110. if( rc!=SQLITE_OK ){
  8111. goto zipfile_step_out;
  8112. }
  8113. if( iMethod==8 || nOut<nData ){
  8114. aData = aFree;
  8115. nData = nOut;
  8116. iMethod = 8;
  8117. }else{
  8118. iMethod = 0;
  8119. }
  8120. }
  8121. }
  8122. /* Decode the "mode" argument. */
  8123. rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
  8124. if( rc ) goto zipfile_step_out;
  8125. /* Decode the "mtime" argument. */
  8126. e.mUnixTime = zipfileGetTime(pMtime);
  8127. /* If this is a directory entry, ensure that there is exactly one '/'
  8128. ** at the end of the path. Or, if this is not a directory and the path
  8129. ** ends in '/' it is an error. */
  8130. if( bIsDir==0 ){
  8131. if( nName>0 && zName[nName-1]=='/' ){
  8132. zErr = sqlite3_mprintf("non-directory name must not end with /");
  8133. rc = SQLITE_ERROR;
  8134. goto zipfile_step_out;
  8135. }
  8136. }else{
  8137. if( nName==0 || zName[nName-1]!='/' ){
  8138. zName = zFree = sqlite3_mprintf("%s/", zName);
  8139. if( zName==0 ){
  8140. rc = SQLITE_NOMEM;
  8141. goto zipfile_step_out;
  8142. }
  8143. nName = (int)strlen(zName);
  8144. }else{
  8145. while( nName>1 && zName[nName-2]=='/' ) nName--;
  8146. }
  8147. }
  8148. /* Assemble the ZipfileEntry object for the new zip archive entry */
  8149. e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
  8150. e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
  8151. e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
  8152. e.cds.iCompression = (u16)iMethod;
  8153. zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
  8154. e.cds.crc32 = iCrc32;
  8155. e.cds.szCompressed = nData;
  8156. e.cds.szUncompressed = szUncompressed;
  8157. e.cds.iExternalAttr = (mode<<16);
  8158. e.cds.iOffset = p->body.n;
  8159. e.cds.nFile = (u16)nName;
  8160. e.cds.zFile = zName;
  8161. /* Append the LFH to the body of the new archive */
  8162. nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
  8163. if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
  8164. p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
  8165. /* Append the data to the body of the new archive */
  8166. if( nData>0 ){
  8167. if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
  8168. memcpy(&p->body.a[p->body.n], aData, nData);
  8169. p->body.n += nData;
  8170. }
  8171. /* Append the CDS record to the directory of the new archive */
  8172. nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
  8173. if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
  8174. p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
  8175. /* Increment the count of entries in the archive */
  8176. p->nEntry++;
  8177. zipfile_step_out:
  8178. sqlite3_free(aFree);
  8179. sqlite3_free(zFree);
  8180. if( rc ){
  8181. if( zErr ){
  8182. sqlite3_result_error(pCtx, zErr, -1);
  8183. }else{
  8184. sqlite3_result_error_code(pCtx, rc);
  8185. }
  8186. }
  8187. sqlite3_free(zErr);
  8188. }
  8189. /*
  8190. ** xFinalize() callback for zipfile aggregate function.
  8191. */
  8192. static void zipfileFinal(sqlite3_context *pCtx){
  8193. ZipfileCtx *p;
  8194. ZipfileEOCD eocd;
  8195. sqlite3_int64 nZip;
  8196. u8 *aZip;
  8197. p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
  8198. if( p==0 ) return;
  8199. if( p->nEntry>0 ){
  8200. memset(&eocd, 0, sizeof(eocd));
  8201. eocd.nEntry = (u16)p->nEntry;
  8202. eocd.nEntryTotal = (u16)p->nEntry;
  8203. eocd.nSize = p->cds.n;
  8204. eocd.iOffset = p->body.n;
  8205. nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
  8206. aZip = (u8*)sqlite3_malloc64(nZip);
  8207. if( aZip==0 ){
  8208. sqlite3_result_error_nomem(pCtx);
  8209. }else{
  8210. memcpy(aZip, p->body.a, p->body.n);
  8211. memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
  8212. zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
  8213. sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
  8214. }
  8215. }
  8216. sqlite3_free(p->body.a);
  8217. sqlite3_free(p->cds.a);
  8218. }
  8219. /*
  8220. ** Register the "zipfile" virtual table.
  8221. */
  8222. static int zipfileRegister(sqlite3 *db){
  8223. static sqlite3_module zipfileModule = {
  8224. 1, /* iVersion */
  8225. zipfileConnect, /* xCreate */
  8226. zipfileConnect, /* xConnect */
  8227. zipfileBestIndex, /* xBestIndex */
  8228. zipfileDisconnect, /* xDisconnect */
  8229. zipfileDisconnect, /* xDestroy */
  8230. zipfileOpen, /* xOpen - open a cursor */
  8231. zipfileClose, /* xClose - close a cursor */
  8232. zipfileFilter, /* xFilter - configure scan constraints */
  8233. zipfileNext, /* xNext - advance a cursor */
  8234. zipfileEof, /* xEof - check for end of scan */
  8235. zipfileColumn, /* xColumn - read data */
  8236. 0, /* xRowid - read data */
  8237. zipfileUpdate, /* xUpdate */
  8238. zipfileBegin, /* xBegin */
  8239. 0, /* xSync */
  8240. zipfileCommit, /* xCommit */
  8241. zipfileRollback, /* xRollback */
  8242. zipfileFindFunction, /* xFindMethod */
  8243. 0, /* xRename */
  8244. };
  8245. int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0);
  8246. if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
  8247. if( rc==SQLITE_OK ){
  8248. rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
  8249. zipfileStep, zipfileFinal
  8250. );
  8251. }
  8252. assert( sizeof(i64)==8 );
  8253. assert( sizeof(u32)==4 );
  8254. assert( sizeof(u16)==2 );
  8255. assert( sizeof(u8)==1 );
  8256. return rc;
  8257. }
  8258. #else /* SQLITE_OMIT_VIRTUALTABLE */
  8259. # define zipfileRegister(x) SQLITE_OK
  8260. #endif
  8261. #ifdef _WIN32
  8262. #endif
  8263. int sqlite3_zipfile_init(
  8264. sqlite3 *db,
  8265. char **pzErrMsg,
  8266. const sqlite3_api_routines *pApi
  8267. ){
  8268. SQLITE_EXTENSION_INIT2(pApi);
  8269. (void)pzErrMsg; /* Unused parameter */
  8270. return zipfileRegister(db);
  8271. }
  8272. /************************* End ../ext/misc/zipfile.c ********************/
  8273. /************************* Begin ../ext/misc/sqlar.c ******************/
  8274. /*
  8275. ** 2017-12-17
  8276. **
  8277. ** The author disclaims copyright to this source code. In place of
  8278. ** a legal notice, here is a blessing:
  8279. **
  8280. ** May you do good and not evil.
  8281. ** May you find forgiveness for yourself and forgive others.
  8282. ** May you share freely, never taking more than you give.
  8283. **
  8284. ******************************************************************************
  8285. **
  8286. ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
  8287. ** for working with sqlar archives and used by the shell tool's built-in
  8288. ** sqlar support.
  8289. */
  8290. /* #include "sqlite3ext.h" */
  8291. SQLITE_EXTENSION_INIT1
  8292. #include <zlib.h>
  8293. #include <assert.h>
  8294. /*
  8295. ** Implementation of the "sqlar_compress(X)" SQL function.
  8296. **
  8297. ** If the type of X is SQLITE_BLOB, and compressing that blob using
  8298. ** zlib utility function compress() yields a smaller blob, return the
  8299. ** compressed blob. Otherwise, return a copy of X.
  8300. **
  8301. ** SQLar uses the "zlib format" for compressed content. The zlib format
  8302. ** contains a two-byte identification header and a four-byte checksum at
  8303. ** the end. This is different from ZIP which uses the raw deflate format.
  8304. **
  8305. ** Future enhancements to SQLar might add support for new compression formats.
  8306. ** If so, those new formats will be identified by alternative headers in the
  8307. ** compressed data.
  8308. */
  8309. static void sqlarCompressFunc(
  8310. sqlite3_context *context,
  8311. int argc,
  8312. sqlite3_value **argv
  8313. ){
  8314. assert( argc==1 );
  8315. if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
  8316. const Bytef *pData = sqlite3_value_blob(argv[0]);
  8317. uLong nData = sqlite3_value_bytes(argv[0]);
  8318. uLongf nOut = compressBound(nData);
  8319. Bytef *pOut;
  8320. pOut = (Bytef*)sqlite3_malloc(nOut);
  8321. if( pOut==0 ){
  8322. sqlite3_result_error_nomem(context);
  8323. return;
  8324. }else{
  8325. if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
  8326. sqlite3_result_error(context, "error in compress()", -1);
  8327. }else if( nOut<nData ){
  8328. sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
  8329. }else{
  8330. sqlite3_result_value(context, argv[0]);
  8331. }
  8332. sqlite3_free(pOut);
  8333. }
  8334. }else{
  8335. sqlite3_result_value(context, argv[0]);
  8336. }
  8337. }
  8338. /*
  8339. ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
  8340. **
  8341. ** Parameter SZ is interpreted as an integer. If it is less than or
  8342. ** equal to zero, then this function returns a copy of X. Or, if
  8343. ** SZ is equal to the size of X when interpreted as a blob, also
  8344. ** return a copy of X. Otherwise, decompress blob X using zlib
  8345. ** utility function uncompress() and return the results (another
  8346. ** blob).
  8347. */
  8348. static void sqlarUncompressFunc(
  8349. sqlite3_context *context,
  8350. int argc,
  8351. sqlite3_value **argv
  8352. ){
  8353. uLong nData;
  8354. uLongf sz;
  8355. assert( argc==2 );
  8356. sz = sqlite3_value_int(argv[1]);
  8357. if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
  8358. sqlite3_result_value(context, argv[0]);
  8359. }else{
  8360. const Bytef *pData= sqlite3_value_blob(argv[0]);
  8361. Bytef *pOut = sqlite3_malloc(sz);
  8362. if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
  8363. sqlite3_result_error(context, "error in uncompress()", -1);
  8364. }else{
  8365. sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
  8366. }
  8367. sqlite3_free(pOut);
  8368. }
  8369. }
  8370. #ifdef _WIN32
  8371. #endif
  8372. int sqlite3_sqlar_init(
  8373. sqlite3 *db,
  8374. char **pzErrMsg,
  8375. const sqlite3_api_routines *pApi
  8376. ){
  8377. int rc = SQLITE_OK;
  8378. SQLITE_EXTENSION_INIT2(pApi);
  8379. (void)pzErrMsg; /* Unused parameter */
  8380. rc = sqlite3_create_function(db, "sqlar_compress", 1,
  8381. SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
  8382. sqlarCompressFunc, 0, 0);
  8383. if( rc==SQLITE_OK ){
  8384. rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
  8385. SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
  8386. sqlarUncompressFunc, 0, 0);
  8387. }
  8388. return rc;
  8389. }
  8390. /************************* End ../ext/misc/sqlar.c ********************/
  8391. #endif
  8392. /************************* Begin ../ext/expert/sqlite3expert.h ******************/
  8393. /*
  8394. ** 2017 April 07
  8395. **
  8396. ** The author disclaims copyright to this source code. In place of
  8397. ** a legal notice, here is a blessing:
  8398. **
  8399. ** May you do good and not evil.
  8400. ** May you find forgiveness for yourself and forgive others.
  8401. ** May you share freely, never taking more than you give.
  8402. **
  8403. *************************************************************************
  8404. */
  8405. #if !defined(SQLITEEXPERT_H)
  8406. #define SQLITEEXPERT_H 1
  8407. /* #include "sqlite3.h" */
  8408. typedef struct sqlite3expert sqlite3expert;
  8409. /*
  8410. ** Create a new sqlite3expert object.
  8411. **
  8412. ** If successful, a pointer to the new object is returned and (*pzErr) set
  8413. ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
  8414. ** an English-language error message. In this case it is the responsibility
  8415. ** of the caller to eventually free the error message buffer using
  8416. ** sqlite3_free().
  8417. */
  8418. sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
  8419. /*
  8420. ** Configure an sqlite3expert object.
  8421. **
  8422. ** EXPERT_CONFIG_SAMPLE:
  8423. ** By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
  8424. ** each candidate index. This involves scanning and sorting the entire
  8425. ** contents of each user database table once for each candidate index
  8426. ** associated with the table. For large databases, this can be
  8427. ** prohibitively slow. This option allows the sqlite3expert object to
  8428. ** be configured so that sqlite_stat1 data is instead generated based on a
  8429. ** subset of each table, or so that no sqlite_stat1 data is used at all.
  8430. **
  8431. ** A single integer argument is passed to this option. If the value is less
  8432. ** than or equal to zero, then no sqlite_stat1 data is generated or used by
  8433. ** the analysis - indexes are recommended based on the database schema only.
  8434. ** Or, if the value is 100 or greater, complete sqlite_stat1 data is
  8435. ** generated for each candidate index (this is the default). Finally, if the
  8436. ** value falls between 0 and 100, then it represents the percentage of user
  8437. ** table rows that should be considered when generating sqlite_stat1 data.
  8438. **
  8439. ** Examples:
  8440. **
  8441. ** // Do not generate any sqlite_stat1 data
  8442. ** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
  8443. **
  8444. ** // Generate sqlite_stat1 data based on 10% of the rows in each table.
  8445. ** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
  8446. */
  8447. int sqlite3_expert_config(sqlite3expert *p, int op, ...);
  8448. #define EXPERT_CONFIG_SAMPLE 1 /* int */
  8449. /*
  8450. ** Specify zero or more SQL statements to be included in the analysis.
  8451. **
  8452. ** Buffer zSql must contain zero or more complete SQL statements. This
  8453. ** function parses all statements contained in the buffer and adds them
  8454. ** to the internal list of statements to analyze. If successful, SQLITE_OK
  8455. ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
  8456. ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
  8457. ** may be set to point to an English language error message. In this case
  8458. ** the caller is responsible for eventually freeing the error message buffer
  8459. ** using sqlite3_free().
  8460. **
  8461. ** If an error does occur while processing one of the statements in the
  8462. ** buffer passed as the second argument, none of the statements in the
  8463. ** buffer are added to the analysis.
  8464. **
  8465. ** This function must be called before sqlite3_expert_analyze(). If a call
  8466. ** to this function is made on an sqlite3expert object that has already
  8467. ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
  8468. ** immediately and no statements are added to the analysis.
  8469. */
  8470. int sqlite3_expert_sql(
  8471. sqlite3expert *p, /* From a successful sqlite3_expert_new() */
  8472. const char *zSql, /* SQL statement(s) to add */
  8473. char **pzErr /* OUT: Error message (if any) */
  8474. );
  8475. /*
  8476. ** This function is called after the sqlite3expert object has been configured
  8477. ** with all SQL statements using sqlite3_expert_sql() to actually perform
  8478. ** the analysis. Once this function has been called, it is not possible to
  8479. ** add further SQL statements to the analysis.
  8480. **
  8481. ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
  8482. ** an error occurs, an SQLite error code is returned and (*pzErr) set to
  8483. ** point to a buffer containing an English language error message. In this
  8484. ** case it is the responsibility of the caller to eventually free the buffer
  8485. ** using sqlite3_free().
  8486. **
  8487. ** If an error does occur within this function, the sqlite3expert object
  8488. ** is no longer useful for any purpose. At that point it is no longer
  8489. ** possible to add further SQL statements to the object or to re-attempt
  8490. ** the analysis. The sqlite3expert object must still be freed using a call
  8491. ** sqlite3_expert_destroy().
  8492. */
  8493. int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
  8494. /*
  8495. ** Return the total number of statements loaded using sqlite3_expert_sql().
  8496. ** The total number of SQL statements may be different from the total number
  8497. ** to calls to sqlite3_expert_sql().
  8498. */
  8499. int sqlite3_expert_count(sqlite3expert*);
  8500. /*
  8501. ** Return a component of the report.
  8502. **
  8503. ** This function is called after sqlite3_expert_analyze() to extract the
  8504. ** results of the analysis. Each call to this function returns either a
  8505. ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
  8506. ** The value passed as the third argument must be one of the EXPERT_REPORT_*
  8507. ** #define constants defined below.
  8508. **
  8509. ** For some EXPERT_REPORT_* parameters, the buffer returned contains
  8510. ** information relating to a specific SQL statement. In these cases that
  8511. ** SQL statement is identified by the value passed as the second argument.
  8512. ** SQL statements are numbered from 0 in the order in which they are parsed.
  8513. ** If an out-of-range value (less than zero or equal to or greater than the
  8514. ** value returned by sqlite3_expert_count()) is passed as the second argument
  8515. ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
  8516. **
  8517. ** EXPERT_REPORT_SQL:
  8518. ** Return the text of SQL statement iStmt.
  8519. **
  8520. ** EXPERT_REPORT_INDEXES:
  8521. ** Return a buffer containing the CREATE INDEX statements for all recommended
  8522. ** indexes for statement iStmt. If there are no new recommeded indexes, NULL
  8523. ** is returned.
  8524. **
  8525. ** EXPERT_REPORT_PLAN:
  8526. ** Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
  8527. ** iStmt after the proposed indexes have been added to the database schema.
  8528. **
  8529. ** EXPERT_REPORT_CANDIDATES:
  8530. ** Return a pointer to a buffer containing the CREATE INDEX statements
  8531. ** for all indexes that were tested (for all SQL statements). The iStmt
  8532. ** parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
  8533. */
  8534. const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
  8535. /*
  8536. ** Values for the third argument passed to sqlite3_expert_report().
  8537. */
  8538. #define EXPERT_REPORT_SQL 1
  8539. #define EXPERT_REPORT_INDEXES 2
  8540. #define EXPERT_REPORT_PLAN 3
  8541. #define EXPERT_REPORT_CANDIDATES 4
  8542. /*
  8543. ** Free an (sqlite3expert*) handle and all associated resources. There
  8544. ** should be one call to this function for each successful call to
  8545. ** sqlite3-expert_new().
  8546. */
  8547. void sqlite3_expert_destroy(sqlite3expert*);
  8548. #endif /* !defined(SQLITEEXPERT_H) */
  8549. /************************* End ../ext/expert/sqlite3expert.h ********************/
  8550. /************************* Begin ../ext/expert/sqlite3expert.c ******************/
  8551. /*
  8552. ** 2017 April 09
  8553. **
  8554. ** The author disclaims copyright to this source code. In place of
  8555. ** a legal notice, here is a blessing:
  8556. **
  8557. ** May you do good and not evil.
  8558. ** May you find forgiveness for yourself and forgive others.
  8559. ** May you share freely, never taking more than you give.
  8560. **
  8561. *************************************************************************
  8562. */
  8563. /* #include "sqlite3expert.h" */
  8564. #include <assert.h>
  8565. #include <string.h>
  8566. #include <stdio.h>
  8567. #if !defined(SQLITE_AMALGAMATION)
  8568. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  8569. # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
  8570. #endif
  8571. #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
  8572. # define ALWAYS(X) (1)
  8573. # define NEVER(X) (0)
  8574. #elif !defined(NDEBUG)
  8575. # define ALWAYS(X) ((X)?1:(assert(0),0))
  8576. # define NEVER(X) ((X)?(assert(0),1):0)
  8577. #else
  8578. # define ALWAYS(X) (X)
  8579. # define NEVER(X) (X)
  8580. #endif
  8581. #endif /* !defined(SQLITE_AMALGAMATION) */
  8582. #ifndef SQLITE_OMIT_VIRTUALTABLE
  8583. /* typedef sqlite3_int64 i64; */
  8584. /* typedef sqlite3_uint64 u64; */
  8585. typedef struct IdxColumn IdxColumn;
  8586. typedef struct IdxConstraint IdxConstraint;
  8587. typedef struct IdxScan IdxScan;
  8588. typedef struct IdxStatement IdxStatement;
  8589. typedef struct IdxTable IdxTable;
  8590. typedef struct IdxWrite IdxWrite;
  8591. #define STRLEN (int)strlen
  8592. /*
  8593. ** A temp table name that we assume no user database will actually use.
  8594. ** If this assumption proves incorrect triggers on the table with the
  8595. ** conflicting name will be ignored.
  8596. */
  8597. #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
  8598. /*
  8599. ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
  8600. ** any other type of single-ended range constraint on a column).
  8601. **
  8602. ** pLink:
  8603. ** Used to temporarily link IdxConstraint objects into lists while
  8604. ** creating candidate indexes.
  8605. */
  8606. struct IdxConstraint {
  8607. char *zColl; /* Collation sequence */
  8608. int bRange; /* True for range, false for eq */
  8609. int iCol; /* Constrained table column */
  8610. int bFlag; /* Used by idxFindCompatible() */
  8611. int bDesc; /* True if ORDER BY <expr> DESC */
  8612. IdxConstraint *pNext; /* Next constraint in pEq or pRange list */
  8613. IdxConstraint *pLink; /* See above */
  8614. };
  8615. /*
  8616. ** A single scan of a single table.
  8617. */
  8618. struct IdxScan {
  8619. IdxTable *pTab; /* Associated table object */
  8620. int iDb; /* Database containing table zTable */
  8621. i64 covering; /* Mask of columns required for cov. index */
  8622. IdxConstraint *pOrder; /* ORDER BY columns */
  8623. IdxConstraint *pEq; /* List of == constraints */
  8624. IdxConstraint *pRange; /* List of < constraints */
  8625. IdxScan *pNextScan; /* Next IdxScan object for same analysis */
  8626. };
  8627. /*
  8628. ** Information regarding a single database table. Extracted from
  8629. ** "PRAGMA table_info" by function idxGetTableInfo().
  8630. */
  8631. struct IdxColumn {
  8632. char *zName;
  8633. char *zColl;
  8634. int iPk;
  8635. };
  8636. struct IdxTable {
  8637. int nCol;
  8638. char *zName; /* Table name */
  8639. IdxColumn *aCol;
  8640. IdxTable *pNext; /* Next table in linked list of all tables */
  8641. };
  8642. /*
  8643. ** An object of the following type is created for each unique table/write-op
  8644. ** seen. The objects are stored in a singly-linked list beginning at
  8645. ** sqlite3expert.pWrite.
  8646. */
  8647. struct IdxWrite {
  8648. IdxTable *pTab;
  8649. int eOp; /* SQLITE_UPDATE, DELETE or INSERT */
  8650. IdxWrite *pNext;
  8651. };
  8652. /*
  8653. ** Each statement being analyzed is represented by an instance of this
  8654. ** structure.
  8655. */
  8656. struct IdxStatement {
  8657. int iId; /* Statement number */
  8658. char *zSql; /* SQL statement */
  8659. char *zIdx; /* Indexes */
  8660. char *zEQP; /* Plan */
  8661. IdxStatement *pNext;
  8662. };
  8663. /*
  8664. ** A hash table for storing strings. With space for a payload string
  8665. ** with each entry. Methods are:
  8666. **
  8667. ** idxHashInit()
  8668. ** idxHashClear()
  8669. ** idxHashAdd()
  8670. ** idxHashSearch()
  8671. */
  8672. #define IDX_HASH_SIZE 1023
  8673. typedef struct IdxHashEntry IdxHashEntry;
  8674. typedef struct IdxHash IdxHash;
  8675. struct IdxHashEntry {
  8676. char *zKey; /* nul-terminated key */
  8677. char *zVal; /* nul-terminated value string */
  8678. char *zVal2; /* nul-terminated value string 2 */
  8679. IdxHashEntry *pHashNext; /* Next entry in same hash bucket */
  8680. IdxHashEntry *pNext; /* Next entry in hash */
  8681. };
  8682. struct IdxHash {
  8683. IdxHashEntry *pFirst;
  8684. IdxHashEntry *aHash[IDX_HASH_SIZE];
  8685. };
  8686. /*
  8687. ** sqlite3expert object.
  8688. */
  8689. struct sqlite3expert {
  8690. int iSample; /* Percentage of tables to sample for stat1 */
  8691. sqlite3 *db; /* User database */
  8692. sqlite3 *dbm; /* In-memory db for this analysis */
  8693. sqlite3 *dbv; /* Vtab schema for this analysis */
  8694. IdxTable *pTable; /* List of all IdxTable objects */
  8695. IdxScan *pScan; /* List of scan objects */
  8696. IdxWrite *pWrite; /* List of write objects */
  8697. IdxStatement *pStatement; /* List of IdxStatement objects */
  8698. int bRun; /* True once analysis has run */
  8699. char **pzErrmsg;
  8700. int rc; /* Error code from whereinfo hook */
  8701. IdxHash hIdx; /* Hash containing all candidate indexes */
  8702. char *zCandidates; /* For EXPERT_REPORT_CANDIDATES */
  8703. };
  8704. /*
  8705. ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
  8706. ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
  8707. */
  8708. static void *idxMalloc(int *pRc, int nByte){
  8709. void *pRet;
  8710. assert( *pRc==SQLITE_OK );
  8711. assert( nByte>0 );
  8712. pRet = sqlite3_malloc(nByte);
  8713. if( pRet ){
  8714. memset(pRet, 0, nByte);
  8715. }else{
  8716. *pRc = SQLITE_NOMEM;
  8717. }
  8718. return pRet;
  8719. }
  8720. /*
  8721. ** Initialize an IdxHash hash table.
  8722. */
  8723. static void idxHashInit(IdxHash *pHash){
  8724. memset(pHash, 0, sizeof(IdxHash));
  8725. }
  8726. /*
  8727. ** Reset an IdxHash hash table.
  8728. */
  8729. static void idxHashClear(IdxHash *pHash){
  8730. int i;
  8731. for(i=0; i<IDX_HASH_SIZE; i++){
  8732. IdxHashEntry *pEntry;
  8733. IdxHashEntry *pNext;
  8734. for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
  8735. pNext = pEntry->pHashNext;
  8736. sqlite3_free(pEntry->zVal2);
  8737. sqlite3_free(pEntry);
  8738. }
  8739. }
  8740. memset(pHash, 0, sizeof(IdxHash));
  8741. }
  8742. /*
  8743. ** Return the index of the hash bucket that the string specified by the
  8744. ** arguments to this function belongs.
  8745. */
  8746. static int idxHashString(const char *z, int n){
  8747. unsigned int ret = 0;
  8748. int i;
  8749. for(i=0; i<n; i++){
  8750. ret += (ret<<3) + (unsigned char)(z[i]);
  8751. }
  8752. return (int)(ret % IDX_HASH_SIZE);
  8753. }
  8754. /*
  8755. ** If zKey is already present in the hash table, return non-zero and do
  8756. ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
  8757. ** the hash table passed as the second argument.
  8758. */
  8759. static int idxHashAdd(
  8760. int *pRc,
  8761. IdxHash *pHash,
  8762. const char *zKey,
  8763. const char *zVal
  8764. ){
  8765. int nKey = STRLEN(zKey);
  8766. int iHash = idxHashString(zKey, nKey);
  8767. int nVal = (zVal ? STRLEN(zVal) : 0);
  8768. IdxHashEntry *pEntry;
  8769. assert( iHash>=0 );
  8770. for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
  8771. if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
  8772. return 1;
  8773. }
  8774. }
  8775. pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
  8776. if( pEntry ){
  8777. pEntry->zKey = (char*)&pEntry[1];
  8778. memcpy(pEntry->zKey, zKey, nKey);
  8779. if( zVal ){
  8780. pEntry->zVal = &pEntry->zKey[nKey+1];
  8781. memcpy(pEntry->zVal, zVal, nVal);
  8782. }
  8783. pEntry->pHashNext = pHash->aHash[iHash];
  8784. pHash->aHash[iHash] = pEntry;
  8785. pEntry->pNext = pHash->pFirst;
  8786. pHash->pFirst = pEntry;
  8787. }
  8788. return 0;
  8789. }
  8790. /*
  8791. ** If zKey/nKey is present in the hash table, return a pointer to the
  8792. ** hash-entry object.
  8793. */
  8794. static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
  8795. int iHash;
  8796. IdxHashEntry *pEntry;
  8797. if( nKey<0 ) nKey = STRLEN(zKey);
  8798. iHash = idxHashString(zKey, nKey);
  8799. assert( iHash>=0 );
  8800. for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
  8801. if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
  8802. return pEntry;
  8803. }
  8804. }
  8805. return 0;
  8806. }
  8807. /*
  8808. ** If the hash table contains an entry with a key equal to the string
  8809. ** passed as the final two arguments to this function, return a pointer
  8810. ** to the payload string. Otherwise, if zKey/nKey is not present in the
  8811. ** hash table, return NULL.
  8812. */
  8813. static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
  8814. IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
  8815. if( pEntry ) return pEntry->zVal;
  8816. return 0;
  8817. }
  8818. /*
  8819. ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
  8820. ** variable to point to a copy of nul-terminated string zColl.
  8821. */
  8822. static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
  8823. IdxConstraint *pNew;
  8824. int nColl = STRLEN(zColl);
  8825. assert( *pRc==SQLITE_OK );
  8826. pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
  8827. if( pNew ){
  8828. pNew->zColl = (char*)&pNew[1];
  8829. memcpy(pNew->zColl, zColl, nColl+1);
  8830. }
  8831. return pNew;
  8832. }
  8833. /*
  8834. ** An error associated with database handle db has just occurred. Pass
  8835. ** the error message to callback function xOut.
  8836. */
  8837. static void idxDatabaseError(
  8838. sqlite3 *db, /* Database handle */
  8839. char **pzErrmsg /* Write error here */
  8840. ){
  8841. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  8842. }
  8843. /*
  8844. ** Prepare an SQL statement.
  8845. */
  8846. static int idxPrepareStmt(
  8847. sqlite3 *db, /* Database handle to compile against */
  8848. sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
  8849. char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
  8850. const char *zSql /* SQL statement to compile */
  8851. ){
  8852. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  8853. if( rc!=SQLITE_OK ){
  8854. *ppStmt = 0;
  8855. idxDatabaseError(db, pzErrmsg);
  8856. }
  8857. return rc;
  8858. }
  8859. /*
  8860. ** Prepare an SQL statement using the results of a printf() formatting.
  8861. */
  8862. static int idxPrintfPrepareStmt(
  8863. sqlite3 *db, /* Database handle to compile against */
  8864. sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
  8865. char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
  8866. const char *zFmt, /* printf() format of SQL statement */
  8867. ... /* Trailing printf() arguments */
  8868. ){
  8869. va_list ap;
  8870. int rc;
  8871. char *zSql;
  8872. va_start(ap, zFmt);
  8873. zSql = sqlite3_vmprintf(zFmt, ap);
  8874. if( zSql==0 ){
  8875. rc = SQLITE_NOMEM;
  8876. }else{
  8877. rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
  8878. sqlite3_free(zSql);
  8879. }
  8880. va_end(ap);
  8881. return rc;
  8882. }
  8883. /*************************************************************************
  8884. ** Beginning of virtual table implementation.
  8885. */
  8886. typedef struct ExpertVtab ExpertVtab;
  8887. struct ExpertVtab {
  8888. sqlite3_vtab base;
  8889. IdxTable *pTab;
  8890. sqlite3expert *pExpert;
  8891. };
  8892. typedef struct ExpertCsr ExpertCsr;
  8893. struct ExpertCsr {
  8894. sqlite3_vtab_cursor base;
  8895. sqlite3_stmt *pData;
  8896. };
  8897. static char *expertDequote(const char *zIn){
  8898. int n = STRLEN(zIn);
  8899. char *zRet = sqlite3_malloc(n);
  8900. assert( zIn[0]=='\'' );
  8901. assert( zIn[n-1]=='\'' );
  8902. if( zRet ){
  8903. int iOut = 0;
  8904. int iIn = 0;
  8905. for(iIn=1; iIn<(n-1); iIn++){
  8906. if( zIn[iIn]=='\'' ){
  8907. assert( zIn[iIn+1]=='\'' );
  8908. iIn++;
  8909. }
  8910. zRet[iOut++] = zIn[iIn];
  8911. }
  8912. zRet[iOut] = '\0';
  8913. }
  8914. return zRet;
  8915. }
  8916. /*
  8917. ** This function is the implementation of both the xConnect and xCreate
  8918. ** methods of the r-tree virtual table.
  8919. **
  8920. ** argv[0] -> module name
  8921. ** argv[1] -> database name
  8922. ** argv[2] -> table name
  8923. ** argv[...] -> column names...
  8924. */
  8925. static int expertConnect(
  8926. sqlite3 *db,
  8927. void *pAux,
  8928. int argc, const char *const*argv,
  8929. sqlite3_vtab **ppVtab,
  8930. char **pzErr
  8931. ){
  8932. sqlite3expert *pExpert = (sqlite3expert*)pAux;
  8933. ExpertVtab *p = 0;
  8934. int rc;
  8935. if( argc!=4 ){
  8936. *pzErr = sqlite3_mprintf("internal error!");
  8937. rc = SQLITE_ERROR;
  8938. }else{
  8939. char *zCreateTable = expertDequote(argv[3]);
  8940. if( zCreateTable ){
  8941. rc = sqlite3_declare_vtab(db, zCreateTable);
  8942. if( rc==SQLITE_OK ){
  8943. p = idxMalloc(&rc, sizeof(ExpertVtab));
  8944. }
  8945. if( rc==SQLITE_OK ){
  8946. p->pExpert = pExpert;
  8947. p->pTab = pExpert->pTable;
  8948. assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
  8949. }
  8950. sqlite3_free(zCreateTable);
  8951. }else{
  8952. rc = SQLITE_NOMEM;
  8953. }
  8954. }
  8955. *ppVtab = (sqlite3_vtab*)p;
  8956. return rc;
  8957. }
  8958. static int expertDisconnect(sqlite3_vtab *pVtab){
  8959. ExpertVtab *p = (ExpertVtab*)pVtab;
  8960. sqlite3_free(p);
  8961. return SQLITE_OK;
  8962. }
  8963. static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
  8964. ExpertVtab *p = (ExpertVtab*)pVtab;
  8965. int rc = SQLITE_OK;
  8966. int n = 0;
  8967. IdxScan *pScan;
  8968. const int opmask =
  8969. SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
  8970. SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
  8971. SQLITE_INDEX_CONSTRAINT_LE;
  8972. pScan = idxMalloc(&rc, sizeof(IdxScan));
  8973. if( pScan ){
  8974. int i;
  8975. /* Link the new scan object into the list */
  8976. pScan->pTab = p->pTab;
  8977. pScan->pNextScan = p->pExpert->pScan;
  8978. p->pExpert->pScan = pScan;
  8979. /* Add the constraints to the IdxScan object */
  8980. for(i=0; i<pIdxInfo->nConstraint; i++){
  8981. struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
  8982. if( pCons->usable
  8983. && pCons->iColumn>=0
  8984. && p->pTab->aCol[pCons->iColumn].iPk==0
  8985. && (pCons->op & opmask)
  8986. ){
  8987. IdxConstraint *pNew;
  8988. const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
  8989. pNew = idxNewConstraint(&rc, zColl);
  8990. if( pNew ){
  8991. pNew->iCol = pCons->iColumn;
  8992. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  8993. pNew->pNext = pScan->pEq;
  8994. pScan->pEq = pNew;
  8995. }else{
  8996. pNew->bRange = 1;
  8997. pNew->pNext = pScan->pRange;
  8998. pScan->pRange = pNew;
  8999. }
  9000. }
  9001. n++;
  9002. pIdxInfo->aConstraintUsage[i].argvIndex = n;
  9003. }
  9004. }
  9005. /* Add the ORDER BY to the IdxScan object */
  9006. for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
  9007. int iCol = pIdxInfo->aOrderBy[i].iColumn;
  9008. if( iCol>=0 ){
  9009. IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
  9010. if( pNew ){
  9011. pNew->iCol = iCol;
  9012. pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
  9013. pNew->pNext = pScan->pOrder;
  9014. pNew->pLink = pScan->pOrder;
  9015. pScan->pOrder = pNew;
  9016. n++;
  9017. }
  9018. }
  9019. }
  9020. }
  9021. pIdxInfo->estimatedCost = 1000000.0 / (n+1);
  9022. return rc;
  9023. }
  9024. static int expertUpdate(
  9025. sqlite3_vtab *pVtab,
  9026. int nData,
  9027. sqlite3_value **azData,
  9028. sqlite_int64 *pRowid
  9029. ){
  9030. (void)pVtab;
  9031. (void)nData;
  9032. (void)azData;
  9033. (void)pRowid;
  9034. return SQLITE_OK;
  9035. }
  9036. /*
  9037. ** Virtual table module xOpen method.
  9038. */
  9039. static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  9040. int rc = SQLITE_OK;
  9041. ExpertCsr *pCsr;
  9042. (void)pVTab;
  9043. pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
  9044. *ppCursor = (sqlite3_vtab_cursor*)pCsr;
  9045. return rc;
  9046. }
  9047. /*
  9048. ** Virtual table module xClose method.
  9049. */
  9050. static int expertClose(sqlite3_vtab_cursor *cur){
  9051. ExpertCsr *pCsr = (ExpertCsr*)cur;
  9052. sqlite3_finalize(pCsr->pData);
  9053. sqlite3_free(pCsr);
  9054. return SQLITE_OK;
  9055. }
  9056. /*
  9057. ** Virtual table module xEof method.
  9058. **
  9059. ** Return non-zero if the cursor does not currently point to a valid
  9060. ** record (i.e if the scan has finished), or zero otherwise.
  9061. */
  9062. static int expertEof(sqlite3_vtab_cursor *cur){
  9063. ExpertCsr *pCsr = (ExpertCsr*)cur;
  9064. return pCsr->pData==0;
  9065. }
  9066. /*
  9067. ** Virtual table module xNext method.
  9068. */
  9069. static int expertNext(sqlite3_vtab_cursor *cur){
  9070. ExpertCsr *pCsr = (ExpertCsr*)cur;
  9071. int rc = SQLITE_OK;
  9072. assert( pCsr->pData );
  9073. rc = sqlite3_step(pCsr->pData);
  9074. if( rc!=SQLITE_ROW ){
  9075. rc = sqlite3_finalize(pCsr->pData);
  9076. pCsr->pData = 0;
  9077. }else{
  9078. rc = SQLITE_OK;
  9079. }
  9080. return rc;
  9081. }
  9082. /*
  9083. ** Virtual table module xRowid method.
  9084. */
  9085. static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  9086. (void)cur;
  9087. *pRowid = 0;
  9088. return SQLITE_OK;
  9089. }
  9090. /*
  9091. ** Virtual table module xColumn method.
  9092. */
  9093. static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  9094. ExpertCsr *pCsr = (ExpertCsr*)cur;
  9095. sqlite3_value *pVal;
  9096. pVal = sqlite3_column_value(pCsr->pData, i);
  9097. if( pVal ){
  9098. sqlite3_result_value(ctx, pVal);
  9099. }
  9100. return SQLITE_OK;
  9101. }
  9102. /*
  9103. ** Virtual table module xFilter method.
  9104. */
  9105. static int expertFilter(
  9106. sqlite3_vtab_cursor *cur,
  9107. int idxNum, const char *idxStr,
  9108. int argc, sqlite3_value **argv
  9109. ){
  9110. ExpertCsr *pCsr = (ExpertCsr*)cur;
  9111. ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
  9112. sqlite3expert *pExpert = pVtab->pExpert;
  9113. int rc;
  9114. (void)idxNum;
  9115. (void)idxStr;
  9116. (void)argc;
  9117. (void)argv;
  9118. rc = sqlite3_finalize(pCsr->pData);
  9119. pCsr->pData = 0;
  9120. if( rc==SQLITE_OK ){
  9121. rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
  9122. "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
  9123. );
  9124. }
  9125. if( rc==SQLITE_OK ){
  9126. rc = expertNext(cur);
  9127. }
  9128. return rc;
  9129. }
  9130. static int idxRegisterVtab(sqlite3expert *p){
  9131. static sqlite3_module expertModule = {
  9132. 2, /* iVersion */
  9133. expertConnect, /* xCreate - create a table */
  9134. expertConnect, /* xConnect - connect to an existing table */
  9135. expertBestIndex, /* xBestIndex - Determine search strategy */
  9136. expertDisconnect, /* xDisconnect - Disconnect from a table */
  9137. expertDisconnect, /* xDestroy - Drop a table */
  9138. expertOpen, /* xOpen - open a cursor */
  9139. expertClose, /* xClose - close a cursor */
  9140. expertFilter, /* xFilter - configure scan constraints */
  9141. expertNext, /* xNext - advance a cursor */
  9142. expertEof, /* xEof */
  9143. expertColumn, /* xColumn - read data */
  9144. expertRowid, /* xRowid - read data */
  9145. expertUpdate, /* xUpdate - write data */
  9146. 0, /* xBegin - begin transaction */
  9147. 0, /* xSync - sync transaction */
  9148. 0, /* xCommit - commit transaction */
  9149. 0, /* xRollback - rollback transaction */
  9150. 0, /* xFindFunction - function overloading */
  9151. 0, /* xRename - rename the table */
  9152. 0, /* xSavepoint */
  9153. 0, /* xRelease */
  9154. 0, /* xRollbackTo */
  9155. 0, /* xShadowName */
  9156. };
  9157. return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
  9158. }
  9159. /*
  9160. ** End of virtual table implementation.
  9161. *************************************************************************/
  9162. /*
  9163. ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
  9164. ** is called, set it to the return value of sqlite3_finalize() before
  9165. ** returning. Otherwise, discard the sqlite3_finalize() return value.
  9166. */
  9167. static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
  9168. int rc = sqlite3_finalize(pStmt);
  9169. if( *pRc==SQLITE_OK ) *pRc = rc;
  9170. }
  9171. /*
  9172. ** Attempt to allocate an IdxTable structure corresponding to table zTab
  9173. ** in the main database of connection db. If successful, set (*ppOut) to
  9174. ** point to the new object and return SQLITE_OK. Otherwise, return an
  9175. ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
  9176. ** set to point to an error string.
  9177. **
  9178. ** It is the responsibility of the caller to eventually free either the
  9179. ** IdxTable object or error message using sqlite3_free().
  9180. */
  9181. static int idxGetTableInfo(
  9182. sqlite3 *db, /* Database connection to read details from */
  9183. const char *zTab, /* Table name */
  9184. IdxTable **ppOut, /* OUT: New object (if successful) */
  9185. char **pzErrmsg /* OUT: Error message (if not) */
  9186. ){
  9187. sqlite3_stmt *p1 = 0;
  9188. int nCol = 0;
  9189. int nTab;
  9190. int nByte;
  9191. IdxTable *pNew = 0;
  9192. int rc, rc2;
  9193. char *pCsr = 0;
  9194. int nPk = 0;
  9195. *ppOut = 0;
  9196. if( zTab==0 ) return SQLITE_ERROR;
  9197. nTab = STRLEN(zTab);
  9198. nByte = sizeof(IdxTable) + nTab + 1;
  9199. rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
  9200. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
  9201. const char *zCol = (const char*)sqlite3_column_text(p1, 1);
  9202. const char *zColSeq = 0;
  9203. if( zCol==0 ){
  9204. rc = SQLITE_ERROR;
  9205. break;
  9206. }
  9207. nByte += 1 + STRLEN(zCol);
  9208. rc = sqlite3_table_column_metadata(
  9209. db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
  9210. );
  9211. if( zColSeq==0 ) zColSeq = "binary";
  9212. nByte += 1 + STRLEN(zColSeq);
  9213. nCol++;
  9214. nPk += (sqlite3_column_int(p1, 5)>0);
  9215. }
  9216. rc2 = sqlite3_reset(p1);
  9217. if( rc==SQLITE_OK ) rc = rc2;
  9218. nByte += sizeof(IdxColumn) * nCol;
  9219. if( rc==SQLITE_OK ){
  9220. pNew = idxMalloc(&rc, nByte);
  9221. }
  9222. if( rc==SQLITE_OK ){
  9223. pNew->aCol = (IdxColumn*)&pNew[1];
  9224. pNew->nCol = nCol;
  9225. pCsr = (char*)&pNew->aCol[nCol];
  9226. }
  9227. nCol = 0;
  9228. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
  9229. const char *zCol = (const char*)sqlite3_column_text(p1, 1);
  9230. const char *zColSeq = 0;
  9231. int nCopy;
  9232. if( zCol==0 ) continue;
  9233. nCopy = STRLEN(zCol) + 1;
  9234. pNew->aCol[nCol].zName = pCsr;
  9235. pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
  9236. memcpy(pCsr, zCol, nCopy);
  9237. pCsr += nCopy;
  9238. rc = sqlite3_table_column_metadata(
  9239. db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
  9240. );
  9241. if( rc==SQLITE_OK ){
  9242. if( zColSeq==0 ) zColSeq = "binary";
  9243. nCopy = STRLEN(zColSeq) + 1;
  9244. pNew->aCol[nCol].zColl = pCsr;
  9245. memcpy(pCsr, zColSeq, nCopy);
  9246. pCsr += nCopy;
  9247. }
  9248. nCol++;
  9249. }
  9250. idxFinalize(&rc, p1);
  9251. if( rc!=SQLITE_OK ){
  9252. sqlite3_free(pNew);
  9253. pNew = 0;
  9254. }else if( ALWAYS(pNew!=0) ){
  9255. pNew->zName = pCsr;
  9256. if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
  9257. }
  9258. *ppOut = pNew;
  9259. return rc;
  9260. }
  9261. /*
  9262. ** This function is a no-op if *pRc is set to anything other than
  9263. ** SQLITE_OK when it is called.
  9264. **
  9265. ** If *pRc is initially set to SQLITE_OK, then the text specified by
  9266. ** the printf() style arguments is appended to zIn and the result returned
  9267. ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
  9268. ** zIn before returning.
  9269. */
  9270. static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
  9271. va_list ap;
  9272. char *zAppend = 0;
  9273. char *zRet = 0;
  9274. int nIn = zIn ? STRLEN(zIn) : 0;
  9275. int nAppend = 0;
  9276. va_start(ap, zFmt);
  9277. if( *pRc==SQLITE_OK ){
  9278. zAppend = sqlite3_vmprintf(zFmt, ap);
  9279. if( zAppend ){
  9280. nAppend = STRLEN(zAppend);
  9281. zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
  9282. }
  9283. if( zAppend && zRet ){
  9284. if( nIn ) memcpy(zRet, zIn, nIn);
  9285. memcpy(&zRet[nIn], zAppend, nAppend+1);
  9286. }else{
  9287. sqlite3_free(zRet);
  9288. zRet = 0;
  9289. *pRc = SQLITE_NOMEM;
  9290. }
  9291. sqlite3_free(zAppend);
  9292. sqlite3_free(zIn);
  9293. }
  9294. va_end(ap);
  9295. return zRet;
  9296. }
  9297. /*
  9298. ** Return true if zId must be quoted in order to use it as an SQL
  9299. ** identifier, or false otherwise.
  9300. */
  9301. static int idxIdentifierRequiresQuotes(const char *zId){
  9302. int i;
  9303. for(i=0; zId[i]; i++){
  9304. if( !(zId[i]=='_')
  9305. && !(zId[i]>='0' && zId[i]<='9')
  9306. && !(zId[i]>='a' && zId[i]<='z')
  9307. && !(zId[i]>='A' && zId[i]<='Z')
  9308. ){
  9309. return 1;
  9310. }
  9311. }
  9312. return 0;
  9313. }
  9314. /*
  9315. ** This function appends an index column definition suitable for constraint
  9316. ** pCons to the string passed as zIn and returns the result.
  9317. */
  9318. static char *idxAppendColDefn(
  9319. int *pRc, /* IN/OUT: Error code */
  9320. char *zIn, /* Column defn accumulated so far */
  9321. IdxTable *pTab, /* Table index will be created on */
  9322. IdxConstraint *pCons
  9323. ){
  9324. char *zRet = zIn;
  9325. IdxColumn *p = &pTab->aCol[pCons->iCol];
  9326. if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
  9327. if( idxIdentifierRequiresQuotes(p->zName) ){
  9328. zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
  9329. }else{
  9330. zRet = idxAppendText(pRc, zRet, "%s", p->zName);
  9331. }
  9332. if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
  9333. if( idxIdentifierRequiresQuotes(pCons->zColl) ){
  9334. zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
  9335. }else{
  9336. zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
  9337. }
  9338. }
  9339. if( pCons->bDesc ){
  9340. zRet = idxAppendText(pRc, zRet, " DESC");
  9341. }
  9342. return zRet;
  9343. }
  9344. /*
  9345. ** Search database dbm for an index compatible with the one idxCreateFromCons()
  9346. ** would create from arguments pScan, pEq and pTail. If no error occurs and
  9347. ** such an index is found, return non-zero. Or, if no such index is found,
  9348. ** return zero.
  9349. **
  9350. ** If an error occurs, set *pRc to an SQLite error code and return zero.
  9351. */
  9352. static int idxFindCompatible(
  9353. int *pRc, /* OUT: Error code */
  9354. sqlite3* dbm, /* Database to search */
  9355. IdxScan *pScan, /* Scan for table to search for index on */
  9356. IdxConstraint *pEq, /* List of == constraints */
  9357. IdxConstraint *pTail /* List of range constraints */
  9358. ){
  9359. const char *zTbl = pScan->pTab->zName;
  9360. sqlite3_stmt *pIdxList = 0;
  9361. IdxConstraint *pIter;
  9362. int nEq = 0; /* Number of elements in pEq */
  9363. int rc;
  9364. /* Count the elements in list pEq */
  9365. for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
  9366. rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
  9367. while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
  9368. int bMatch = 1;
  9369. IdxConstraint *pT = pTail;
  9370. sqlite3_stmt *pInfo = 0;
  9371. const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
  9372. if( zIdx==0 ) continue;
  9373. /* Zero the IdxConstraint.bFlag values in the pEq list */
  9374. for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
  9375. rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
  9376. while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
  9377. int iIdx = sqlite3_column_int(pInfo, 0);
  9378. int iCol = sqlite3_column_int(pInfo, 1);
  9379. const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
  9380. if( iIdx<nEq ){
  9381. for(pIter=pEq; pIter; pIter=pIter->pLink){
  9382. if( pIter->bFlag ) continue;
  9383. if( pIter->iCol!=iCol ) continue;
  9384. if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
  9385. pIter->bFlag = 1;
  9386. break;
  9387. }
  9388. if( pIter==0 ){
  9389. bMatch = 0;
  9390. break;
  9391. }
  9392. }else{
  9393. if( pT ){
  9394. if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
  9395. bMatch = 0;
  9396. break;
  9397. }
  9398. pT = pT->pLink;
  9399. }
  9400. }
  9401. }
  9402. idxFinalize(&rc, pInfo);
  9403. if( rc==SQLITE_OK && bMatch ){
  9404. sqlite3_finalize(pIdxList);
  9405. return 1;
  9406. }
  9407. }
  9408. idxFinalize(&rc, pIdxList);
  9409. *pRc = rc;
  9410. return 0;
  9411. }
  9412. /* Callback for sqlite3_exec() with query with leading count(*) column.
  9413. * The first argument is expected to be an int*, referent to be incremented
  9414. * if that leading column is not exactly '0'.
  9415. */
  9416. static int countNonzeros(void* pCount, int nc,
  9417. char* azResults[], char* azColumns[]){
  9418. (void)azColumns; /* Suppress unused parameter warning */
  9419. if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
  9420. *((int *)pCount) += 1;
  9421. }
  9422. return 0;
  9423. }
  9424. static int idxCreateFromCons(
  9425. sqlite3expert *p,
  9426. IdxScan *pScan,
  9427. IdxConstraint *pEq,
  9428. IdxConstraint *pTail
  9429. ){
  9430. sqlite3 *dbm = p->dbm;
  9431. int rc = SQLITE_OK;
  9432. if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
  9433. IdxTable *pTab = pScan->pTab;
  9434. char *zCols = 0;
  9435. char *zIdx = 0;
  9436. IdxConstraint *pCons;
  9437. unsigned int h = 0;
  9438. const char *zFmt;
  9439. for(pCons=pEq; pCons; pCons=pCons->pLink){
  9440. zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
  9441. }
  9442. for(pCons=pTail; pCons; pCons=pCons->pLink){
  9443. zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
  9444. }
  9445. if( rc==SQLITE_OK ){
  9446. /* Hash the list of columns to come up with a name for the index */
  9447. const char *zTable = pScan->pTab->zName;
  9448. int quoteTable = idxIdentifierRequiresQuotes(zTable);
  9449. char *zName = 0; /* Index name */
  9450. int collisions = 0;
  9451. do{
  9452. int i;
  9453. char *zFind;
  9454. for(i=0; zCols[i]; i++){
  9455. h += ((h<<3) + zCols[i]);
  9456. }
  9457. sqlite3_free(zName);
  9458. zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
  9459. if( zName==0 ) break;
  9460. /* Is is unique among table, view and index names? */
  9461. zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
  9462. " AND type in ('index','table','view')";
  9463. zFind = sqlite3_mprintf(zFmt, zName);
  9464. i = 0;
  9465. rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
  9466. assert(rc==SQLITE_OK);
  9467. sqlite3_free(zFind);
  9468. if( i==0 ){
  9469. collisions = 0;
  9470. break;
  9471. }
  9472. ++collisions;
  9473. }while( collisions<50 && zName!=0 );
  9474. if( collisions ){
  9475. /* This return means "Gave up trying to find a unique index name." */
  9476. rc = SQLITE_BUSY_TIMEOUT;
  9477. }else if( zName==0 ){
  9478. rc = SQLITE_NOMEM;
  9479. }else{
  9480. if( quoteTable ){
  9481. zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
  9482. }else{
  9483. zFmt = "CREATE INDEX %s ON %s(%s)";
  9484. }
  9485. zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
  9486. if( !zIdx ){
  9487. rc = SQLITE_NOMEM;
  9488. }else{
  9489. rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
  9490. if( rc!=SQLITE_OK ){
  9491. rc = SQLITE_BUSY_TIMEOUT;
  9492. }else{
  9493. idxHashAdd(&rc, &p->hIdx, zName, zIdx);
  9494. }
  9495. }
  9496. sqlite3_free(zName);
  9497. sqlite3_free(zIdx);
  9498. }
  9499. }
  9500. sqlite3_free(zCols);
  9501. }
  9502. return rc;
  9503. }
  9504. /*
  9505. ** Return true if list pList (linked by IdxConstraint.pLink) contains
  9506. ** a constraint compatible with *p. Otherwise return false.
  9507. */
  9508. static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
  9509. IdxConstraint *pCmp;
  9510. for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
  9511. if( p->iCol==pCmp->iCol ) return 1;
  9512. }
  9513. return 0;
  9514. }
  9515. static int idxCreateFromWhere(
  9516. sqlite3expert *p,
  9517. IdxScan *pScan, /* Create indexes for this scan */
  9518. IdxConstraint *pTail /* range/ORDER BY constraints for inclusion */
  9519. ){
  9520. IdxConstraint *p1 = 0;
  9521. IdxConstraint *pCon;
  9522. int rc;
  9523. /* Gather up all the == constraints. */
  9524. for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
  9525. if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
  9526. pCon->pLink = p1;
  9527. p1 = pCon;
  9528. }
  9529. }
  9530. /* Create an index using the == constraints collected above. And the
  9531. ** range constraint/ORDER BY terms passed in by the caller, if any. */
  9532. rc = idxCreateFromCons(p, pScan, p1, pTail);
  9533. /* If no range/ORDER BY passed by the caller, create a version of the
  9534. ** index for each range constraint. */
  9535. if( pTail==0 ){
  9536. for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
  9537. assert( pCon->pLink==0 );
  9538. if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
  9539. rc = idxCreateFromCons(p, pScan, p1, pCon);
  9540. }
  9541. }
  9542. }
  9543. return rc;
  9544. }
  9545. /*
  9546. ** Create candidate indexes in database [dbm] based on the data in
  9547. ** linked-list pScan.
  9548. */
  9549. static int idxCreateCandidates(sqlite3expert *p){
  9550. int rc = SQLITE_OK;
  9551. IdxScan *pIter;
  9552. for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
  9553. rc = idxCreateFromWhere(p, pIter, 0);
  9554. if( rc==SQLITE_OK && pIter->pOrder ){
  9555. rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
  9556. }
  9557. }
  9558. return rc;
  9559. }
  9560. /*
  9561. ** Free all elements of the linked list starting at pConstraint.
  9562. */
  9563. static void idxConstraintFree(IdxConstraint *pConstraint){
  9564. IdxConstraint *pNext;
  9565. IdxConstraint *p;
  9566. for(p=pConstraint; p; p=pNext){
  9567. pNext = p->pNext;
  9568. sqlite3_free(p);
  9569. }
  9570. }
  9571. /*
  9572. ** Free all elements of the linked list starting from pScan up until pLast
  9573. ** (pLast is not freed).
  9574. */
  9575. static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
  9576. IdxScan *p;
  9577. IdxScan *pNext;
  9578. for(p=pScan; p!=pLast; p=pNext){
  9579. pNext = p->pNextScan;
  9580. idxConstraintFree(p->pOrder);
  9581. idxConstraintFree(p->pEq);
  9582. idxConstraintFree(p->pRange);
  9583. sqlite3_free(p);
  9584. }
  9585. }
  9586. /*
  9587. ** Free all elements of the linked list starting from pStatement up
  9588. ** until pLast (pLast is not freed).
  9589. */
  9590. static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
  9591. IdxStatement *p;
  9592. IdxStatement *pNext;
  9593. for(p=pStatement; p!=pLast; p=pNext){
  9594. pNext = p->pNext;
  9595. sqlite3_free(p->zEQP);
  9596. sqlite3_free(p->zIdx);
  9597. sqlite3_free(p);
  9598. }
  9599. }
  9600. /*
  9601. ** Free the linked list of IdxTable objects starting at pTab.
  9602. */
  9603. static void idxTableFree(IdxTable *pTab){
  9604. IdxTable *pIter;
  9605. IdxTable *pNext;
  9606. for(pIter=pTab; pIter; pIter=pNext){
  9607. pNext = pIter->pNext;
  9608. sqlite3_free(pIter);
  9609. }
  9610. }
  9611. /*
  9612. ** Free the linked list of IdxWrite objects starting at pTab.
  9613. */
  9614. static void idxWriteFree(IdxWrite *pTab){
  9615. IdxWrite *pIter;
  9616. IdxWrite *pNext;
  9617. for(pIter=pTab; pIter; pIter=pNext){
  9618. pNext = pIter->pNext;
  9619. sqlite3_free(pIter);
  9620. }
  9621. }
  9622. /*
  9623. ** This function is called after candidate indexes have been created. It
  9624. ** runs all the queries to see which indexes they prefer, and populates
  9625. ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
  9626. */
  9627. static int idxFindIndexes(
  9628. sqlite3expert *p,
  9629. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  9630. ){
  9631. IdxStatement *pStmt;
  9632. sqlite3 *dbm = p->dbm;
  9633. int rc = SQLITE_OK;
  9634. IdxHash hIdx;
  9635. idxHashInit(&hIdx);
  9636. for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
  9637. IdxHashEntry *pEntry;
  9638. sqlite3_stmt *pExplain = 0;
  9639. idxHashClear(&hIdx);
  9640. rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
  9641. "EXPLAIN QUERY PLAN %s", pStmt->zSql
  9642. );
  9643. while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
  9644. /* int iId = sqlite3_column_int(pExplain, 0); */
  9645. /* int iParent = sqlite3_column_int(pExplain, 1); */
  9646. /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
  9647. const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
  9648. int nDetail;
  9649. int i;
  9650. if( !zDetail ) continue;
  9651. nDetail = STRLEN(zDetail);
  9652. for(i=0; i<nDetail; i++){
  9653. const char *zIdx = 0;
  9654. if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
  9655. zIdx = &zDetail[i+13];
  9656. }else if( i+22<nDetail
  9657. && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
  9658. ){
  9659. zIdx = &zDetail[i+22];
  9660. }
  9661. if( zIdx ){
  9662. const char *zSql;
  9663. int nIdx = 0;
  9664. while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
  9665. nIdx++;
  9666. }
  9667. zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
  9668. if( zSql ){
  9669. idxHashAdd(&rc, &hIdx, zSql, 0);
  9670. if( rc ) goto find_indexes_out;
  9671. }
  9672. break;
  9673. }
  9674. }
  9675. if( zDetail[0]!='-' ){
  9676. pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
  9677. }
  9678. }
  9679. for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
  9680. pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
  9681. }
  9682. idxFinalize(&rc, pExplain);
  9683. }
  9684. find_indexes_out:
  9685. idxHashClear(&hIdx);
  9686. return rc;
  9687. }
  9688. static int idxAuthCallback(
  9689. void *pCtx,
  9690. int eOp,
  9691. const char *z3,
  9692. const char *z4,
  9693. const char *zDb,
  9694. const char *zTrigger
  9695. ){
  9696. int rc = SQLITE_OK;
  9697. (void)z4;
  9698. (void)zTrigger;
  9699. if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
  9700. if( sqlite3_stricmp(zDb, "main")==0 ){
  9701. sqlite3expert *p = (sqlite3expert*)pCtx;
  9702. IdxTable *pTab;
  9703. for(pTab=p->pTable; pTab; pTab=pTab->pNext){
  9704. if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
  9705. }
  9706. if( pTab ){
  9707. IdxWrite *pWrite;
  9708. for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
  9709. if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
  9710. }
  9711. if( pWrite==0 ){
  9712. pWrite = idxMalloc(&rc, sizeof(IdxWrite));
  9713. if( rc==SQLITE_OK ){
  9714. pWrite->pTab = pTab;
  9715. pWrite->eOp = eOp;
  9716. pWrite->pNext = p->pWrite;
  9717. p->pWrite = pWrite;
  9718. }
  9719. }
  9720. }
  9721. }
  9722. }
  9723. return rc;
  9724. }
  9725. static int idxProcessOneTrigger(
  9726. sqlite3expert *p,
  9727. IdxWrite *pWrite,
  9728. char **pzErr
  9729. ){
  9730. static const char *zInt = UNIQUE_TABLE_NAME;
  9731. static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
  9732. IdxTable *pTab = pWrite->pTab;
  9733. const char *zTab = pTab->zName;
  9734. const char *zSql =
  9735. "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
  9736. "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
  9737. "ORDER BY type;";
  9738. sqlite3_stmt *pSelect = 0;
  9739. int rc = SQLITE_OK;
  9740. char *zWrite = 0;
  9741. /* Create the table and its triggers in the temp schema */
  9742. rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
  9743. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
  9744. const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
  9745. if( zCreate==0 ) continue;
  9746. rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
  9747. }
  9748. idxFinalize(&rc, pSelect);
  9749. /* Rename the table in the temp schema to zInt */
  9750. if( rc==SQLITE_OK ){
  9751. char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
  9752. if( z==0 ){
  9753. rc = SQLITE_NOMEM;
  9754. }else{
  9755. rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
  9756. sqlite3_free(z);
  9757. }
  9758. }
  9759. switch( pWrite->eOp ){
  9760. case SQLITE_INSERT: {
  9761. int i;
  9762. zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
  9763. for(i=0; i<pTab->nCol; i++){
  9764. zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
  9765. }
  9766. zWrite = idxAppendText(&rc, zWrite, ")");
  9767. break;
  9768. }
  9769. case SQLITE_UPDATE: {
  9770. int i;
  9771. zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
  9772. for(i=0; i<pTab->nCol; i++){
  9773. zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
  9774. pTab->aCol[i].zName
  9775. );
  9776. }
  9777. break;
  9778. }
  9779. default: {
  9780. assert( pWrite->eOp==SQLITE_DELETE );
  9781. if( rc==SQLITE_OK ){
  9782. zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
  9783. if( zWrite==0 ) rc = SQLITE_NOMEM;
  9784. }
  9785. }
  9786. }
  9787. if( rc==SQLITE_OK ){
  9788. sqlite3_stmt *pX = 0;
  9789. rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
  9790. idxFinalize(&rc, pX);
  9791. if( rc!=SQLITE_OK ){
  9792. idxDatabaseError(p->dbv, pzErr);
  9793. }
  9794. }
  9795. sqlite3_free(zWrite);
  9796. if( rc==SQLITE_OK ){
  9797. rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
  9798. }
  9799. return rc;
  9800. }
  9801. static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
  9802. int rc = SQLITE_OK;
  9803. IdxWrite *pEnd = 0;
  9804. IdxWrite *pFirst = p->pWrite;
  9805. while( rc==SQLITE_OK && pFirst!=pEnd ){
  9806. IdxWrite *pIter;
  9807. for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
  9808. rc = idxProcessOneTrigger(p, pIter, pzErr);
  9809. }
  9810. pEnd = pFirst;
  9811. pFirst = p->pWrite;
  9812. }
  9813. return rc;
  9814. }
  9815. static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
  9816. int rc = idxRegisterVtab(p);
  9817. sqlite3_stmt *pSchema = 0;
  9818. /* For each table in the main db schema:
  9819. **
  9820. ** 1) Add an entry to the p->pTable list, and
  9821. ** 2) Create the equivalent virtual table in dbv.
  9822. */
  9823. rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
  9824. "SELECT type, name, sql, 1 FROM sqlite_schema "
  9825. "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
  9826. " UNION ALL "
  9827. "SELECT type, name, sql, 2 FROM sqlite_schema "
  9828. "WHERE type = 'trigger'"
  9829. " AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
  9830. "ORDER BY 4, 1"
  9831. );
  9832. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
  9833. const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
  9834. const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
  9835. const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
  9836. if( zType==0 || zName==0 ) continue;
  9837. if( zType[0]=='v' || zType[1]=='r' ){
  9838. if( zSql ) rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
  9839. }else{
  9840. IdxTable *pTab;
  9841. rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
  9842. if( rc==SQLITE_OK ){
  9843. int i;
  9844. char *zInner = 0;
  9845. char *zOuter = 0;
  9846. pTab->pNext = p->pTable;
  9847. p->pTable = pTab;
  9848. /* The statement the vtab will pass to sqlite3_declare_vtab() */
  9849. zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
  9850. for(i=0; i<pTab->nCol; i++){
  9851. zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
  9852. (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
  9853. );
  9854. }
  9855. zInner = idxAppendText(&rc, zInner, ")");
  9856. /* The CVT statement to create the vtab */
  9857. zOuter = idxAppendText(&rc, 0,
  9858. "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
  9859. );
  9860. if( rc==SQLITE_OK ){
  9861. rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
  9862. }
  9863. sqlite3_free(zInner);
  9864. sqlite3_free(zOuter);
  9865. }
  9866. }
  9867. }
  9868. idxFinalize(&rc, pSchema);
  9869. return rc;
  9870. }
  9871. struct IdxSampleCtx {
  9872. int iTarget;
  9873. double target; /* Target nRet/nRow value */
  9874. double nRow; /* Number of rows seen */
  9875. double nRet; /* Number of rows returned */
  9876. };
  9877. static void idxSampleFunc(
  9878. sqlite3_context *pCtx,
  9879. int argc,
  9880. sqlite3_value **argv
  9881. ){
  9882. struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
  9883. int bRet;
  9884. (void)argv;
  9885. assert( argc==0 );
  9886. if( p->nRow==0.0 ){
  9887. bRet = 1;
  9888. }else{
  9889. bRet = (p->nRet / p->nRow) <= p->target;
  9890. if( bRet==0 ){
  9891. unsigned short rnd;
  9892. sqlite3_randomness(2, (void*)&rnd);
  9893. bRet = ((int)rnd % 100) <= p->iTarget;
  9894. }
  9895. }
  9896. sqlite3_result_int(pCtx, bRet);
  9897. p->nRow += 1.0;
  9898. p->nRet += (double)bRet;
  9899. }
  9900. struct IdxRemCtx {
  9901. int nSlot;
  9902. struct IdxRemSlot {
  9903. int eType; /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
  9904. i64 iVal; /* SQLITE_INTEGER value */
  9905. double rVal; /* SQLITE_FLOAT value */
  9906. int nByte; /* Bytes of space allocated at z */
  9907. int n; /* Size of buffer z */
  9908. char *z; /* SQLITE_TEXT/BLOB value */
  9909. } aSlot[1];
  9910. };
  9911. /*
  9912. ** Implementation of scalar function rem().
  9913. */
  9914. static void idxRemFunc(
  9915. sqlite3_context *pCtx,
  9916. int argc,
  9917. sqlite3_value **argv
  9918. ){
  9919. struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
  9920. struct IdxRemSlot *pSlot;
  9921. int iSlot;
  9922. assert( argc==2 );
  9923. iSlot = sqlite3_value_int(argv[0]);
  9924. assert( iSlot<=p->nSlot );
  9925. pSlot = &p->aSlot[iSlot];
  9926. switch( pSlot->eType ){
  9927. case SQLITE_NULL:
  9928. /* no-op */
  9929. break;
  9930. case SQLITE_INTEGER:
  9931. sqlite3_result_int64(pCtx, pSlot->iVal);
  9932. break;
  9933. case SQLITE_FLOAT:
  9934. sqlite3_result_double(pCtx, pSlot->rVal);
  9935. break;
  9936. case SQLITE_BLOB:
  9937. sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
  9938. break;
  9939. case SQLITE_TEXT:
  9940. sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
  9941. break;
  9942. }
  9943. pSlot->eType = sqlite3_value_type(argv[1]);
  9944. switch( pSlot->eType ){
  9945. case SQLITE_NULL:
  9946. /* no-op */
  9947. break;
  9948. case SQLITE_INTEGER:
  9949. pSlot->iVal = sqlite3_value_int64(argv[1]);
  9950. break;
  9951. case SQLITE_FLOAT:
  9952. pSlot->rVal = sqlite3_value_double(argv[1]);
  9953. break;
  9954. case SQLITE_BLOB:
  9955. case SQLITE_TEXT: {
  9956. int nByte = sqlite3_value_bytes(argv[1]);
  9957. const void *pData = 0;
  9958. if( nByte>pSlot->nByte ){
  9959. char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
  9960. if( zNew==0 ){
  9961. sqlite3_result_error_nomem(pCtx);
  9962. return;
  9963. }
  9964. pSlot->nByte = nByte*2;
  9965. pSlot->z = zNew;
  9966. }
  9967. pSlot->n = nByte;
  9968. if( pSlot->eType==SQLITE_BLOB ){
  9969. pData = sqlite3_value_blob(argv[1]);
  9970. if( pData ) memcpy(pSlot->z, pData, nByte);
  9971. }else{
  9972. pData = sqlite3_value_text(argv[1]);
  9973. memcpy(pSlot->z, pData, nByte);
  9974. }
  9975. break;
  9976. }
  9977. }
  9978. }
  9979. static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
  9980. int rc = SQLITE_OK;
  9981. const char *zMax =
  9982. "SELECT max(i.seqno) FROM "
  9983. " sqlite_schema AS s, "
  9984. " pragma_index_list(s.name) AS l, "
  9985. " pragma_index_info(l.name) AS i "
  9986. "WHERE s.type = 'table'";
  9987. sqlite3_stmt *pMax = 0;
  9988. *pnMax = 0;
  9989. rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
  9990. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
  9991. *pnMax = sqlite3_column_int(pMax, 0) + 1;
  9992. }
  9993. idxFinalize(&rc, pMax);
  9994. return rc;
  9995. }
  9996. static int idxPopulateOneStat1(
  9997. sqlite3expert *p,
  9998. sqlite3_stmt *pIndexXInfo,
  9999. sqlite3_stmt *pWriteStat,
  10000. const char *zTab,
  10001. const char *zIdx,
  10002. char **pzErr
  10003. ){
  10004. char *zCols = 0;
  10005. char *zOrder = 0;
  10006. char *zQuery = 0;
  10007. int nCol = 0;
  10008. int i;
  10009. sqlite3_stmt *pQuery = 0;
  10010. int *aStat = 0;
  10011. int rc = SQLITE_OK;
  10012. assert( p->iSample>0 );
  10013. /* Formulate the query text */
  10014. sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
  10015. while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
  10016. const char *zComma = zCols==0 ? "" : ", ";
  10017. const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
  10018. const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
  10019. zCols = idxAppendText(&rc, zCols,
  10020. "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
  10021. );
  10022. zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
  10023. }
  10024. sqlite3_reset(pIndexXInfo);
  10025. if( rc==SQLITE_OK ){
  10026. if( p->iSample==100 ){
  10027. zQuery = sqlite3_mprintf(
  10028. "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
  10029. );
  10030. }else{
  10031. zQuery = sqlite3_mprintf(
  10032. "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
  10033. );
  10034. }
  10035. }
  10036. sqlite3_free(zCols);
  10037. sqlite3_free(zOrder);
  10038. /* Formulate the query text */
  10039. if( rc==SQLITE_OK ){
  10040. sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
  10041. rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
  10042. }
  10043. sqlite3_free(zQuery);
  10044. if( rc==SQLITE_OK ){
  10045. aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
  10046. }
  10047. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
  10048. IdxHashEntry *pEntry;
  10049. char *zStat = 0;
  10050. for(i=0; i<=nCol; i++) aStat[i] = 1;
  10051. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
  10052. aStat[0]++;
  10053. for(i=0; i<nCol; i++){
  10054. if( sqlite3_column_int(pQuery, i)==0 ) break;
  10055. }
  10056. for(/*no-op*/; i<nCol; i++){
  10057. aStat[i+1]++;
  10058. }
  10059. }
  10060. if( rc==SQLITE_OK ){
  10061. int s0 = aStat[0];
  10062. zStat = sqlite3_mprintf("%d", s0);
  10063. if( zStat==0 ) rc = SQLITE_NOMEM;
  10064. for(i=1; rc==SQLITE_OK && i<=nCol; i++){
  10065. zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
  10066. }
  10067. }
  10068. if( rc==SQLITE_OK ){
  10069. sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
  10070. sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
  10071. sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
  10072. sqlite3_step(pWriteStat);
  10073. rc = sqlite3_reset(pWriteStat);
  10074. }
  10075. pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
  10076. if( pEntry ){
  10077. assert( pEntry->zVal2==0 );
  10078. pEntry->zVal2 = zStat;
  10079. }else{
  10080. sqlite3_free(zStat);
  10081. }
  10082. }
  10083. sqlite3_free(aStat);
  10084. idxFinalize(&rc, pQuery);
  10085. return rc;
  10086. }
  10087. static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
  10088. int rc;
  10089. char *zSql;
  10090. rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
  10091. if( rc!=SQLITE_OK ) return rc;
  10092. zSql = sqlite3_mprintf(
  10093. "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
  10094. );
  10095. if( zSql==0 ) return SQLITE_NOMEM;
  10096. rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
  10097. sqlite3_free(zSql);
  10098. return rc;
  10099. }
  10100. /*
  10101. ** This function is called as part of sqlite3_expert_analyze(). Candidate
  10102. ** indexes have already been created in database sqlite3expert.dbm, this
  10103. ** function populates sqlite_stat1 table in the same database.
  10104. **
  10105. ** The stat1 data is generated by querying the
  10106. */
  10107. static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
  10108. int rc = SQLITE_OK;
  10109. int nMax =0;
  10110. struct IdxRemCtx *pCtx = 0;
  10111. struct IdxSampleCtx samplectx;
  10112. int i;
  10113. i64 iPrev = -100000;
  10114. sqlite3_stmt *pAllIndex = 0;
  10115. sqlite3_stmt *pIndexXInfo = 0;
  10116. sqlite3_stmt *pWrite = 0;
  10117. const char *zAllIndex =
  10118. "SELECT s.rowid, s.name, l.name FROM "
  10119. " sqlite_schema AS s, "
  10120. " pragma_index_list(s.name) AS l "
  10121. "WHERE s.type = 'table'";
  10122. const char *zIndexXInfo =
  10123. "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
  10124. const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
  10125. /* If iSample==0, no sqlite_stat1 data is required. */
  10126. if( p->iSample==0 ) return SQLITE_OK;
  10127. rc = idxLargestIndex(p->dbm, &nMax, pzErr);
  10128. if( nMax<=0 || rc!=SQLITE_OK ) return rc;
  10129. rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
  10130. if( rc==SQLITE_OK ){
  10131. int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
  10132. pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
  10133. }
  10134. if( rc==SQLITE_OK ){
  10135. sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
  10136. rc = sqlite3_create_function(
  10137. dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
  10138. );
  10139. }
  10140. if( rc==SQLITE_OK ){
  10141. rc = sqlite3_create_function(
  10142. p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
  10143. );
  10144. }
  10145. if( rc==SQLITE_OK ){
  10146. pCtx->nSlot = nMax+1;
  10147. rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
  10148. }
  10149. if( rc==SQLITE_OK ){
  10150. rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
  10151. }
  10152. if( rc==SQLITE_OK ){
  10153. rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
  10154. }
  10155. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
  10156. i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
  10157. const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
  10158. const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
  10159. if( zTab==0 || zIdx==0 ) continue;
  10160. if( p->iSample<100 && iPrev!=iRowid ){
  10161. samplectx.target = (double)p->iSample / 100.0;
  10162. samplectx.iTarget = p->iSample;
  10163. samplectx.nRow = 0.0;
  10164. samplectx.nRet = 0.0;
  10165. rc = idxBuildSampleTable(p, zTab);
  10166. if( rc!=SQLITE_OK ) break;
  10167. }
  10168. rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
  10169. iPrev = iRowid;
  10170. }
  10171. if( rc==SQLITE_OK && p->iSample<100 ){
  10172. rc = sqlite3_exec(p->dbv,
  10173. "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
  10174. );
  10175. }
  10176. idxFinalize(&rc, pAllIndex);
  10177. idxFinalize(&rc, pIndexXInfo);
  10178. idxFinalize(&rc, pWrite);
  10179. if( pCtx ){
  10180. for(i=0; i<pCtx->nSlot; i++){
  10181. sqlite3_free(pCtx->aSlot[i].z);
  10182. }
  10183. sqlite3_free(pCtx);
  10184. }
  10185. if( rc==SQLITE_OK ){
  10186. rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
  10187. }
  10188. sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
  10189. return rc;
  10190. }
  10191. /*
  10192. ** Allocate a new sqlite3expert object.
  10193. */
  10194. sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
  10195. int rc = SQLITE_OK;
  10196. sqlite3expert *pNew;
  10197. pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
  10198. /* Open two in-memory databases to work with. The "vtab database" (dbv)
  10199. ** will contain a virtual table corresponding to each real table in
  10200. ** the user database schema, and a copy of each view. It is used to
  10201. ** collect information regarding the WHERE, ORDER BY and other clauses
  10202. ** of the user's query.
  10203. */
  10204. if( rc==SQLITE_OK ){
  10205. pNew->db = db;
  10206. pNew->iSample = 100;
  10207. rc = sqlite3_open(":memory:", &pNew->dbv);
  10208. }
  10209. if( rc==SQLITE_OK ){
  10210. rc = sqlite3_open(":memory:", &pNew->dbm);
  10211. if( rc==SQLITE_OK ){
  10212. sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
  10213. }
  10214. }
  10215. /* Copy the entire schema of database [db] into [dbm]. */
  10216. if( rc==SQLITE_OK ){
  10217. sqlite3_stmt *pSql = 0;
  10218. rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
  10219. "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
  10220. " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
  10221. );
  10222. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  10223. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  10224. if( zSql ) rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
  10225. }
  10226. idxFinalize(&rc, pSql);
  10227. }
  10228. /* Create the vtab schema */
  10229. if( rc==SQLITE_OK ){
  10230. rc = idxCreateVtabSchema(pNew, pzErrmsg);
  10231. }
  10232. /* Register the auth callback with dbv */
  10233. if( rc==SQLITE_OK ){
  10234. sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
  10235. }
  10236. /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
  10237. ** return the new sqlite3expert handle. */
  10238. if( rc!=SQLITE_OK ){
  10239. sqlite3_expert_destroy(pNew);
  10240. pNew = 0;
  10241. }
  10242. return pNew;
  10243. }
  10244. /*
  10245. ** Configure an sqlite3expert object.
  10246. */
  10247. int sqlite3_expert_config(sqlite3expert *p, int op, ...){
  10248. int rc = SQLITE_OK;
  10249. va_list ap;
  10250. va_start(ap, op);
  10251. switch( op ){
  10252. case EXPERT_CONFIG_SAMPLE: {
  10253. int iVal = va_arg(ap, int);
  10254. if( iVal<0 ) iVal = 0;
  10255. if( iVal>100 ) iVal = 100;
  10256. p->iSample = iVal;
  10257. break;
  10258. }
  10259. default:
  10260. rc = SQLITE_NOTFOUND;
  10261. break;
  10262. }
  10263. va_end(ap);
  10264. return rc;
  10265. }
  10266. /*
  10267. ** Add an SQL statement to the analysis.
  10268. */
  10269. int sqlite3_expert_sql(
  10270. sqlite3expert *p, /* From sqlite3_expert_new() */
  10271. const char *zSql, /* SQL statement to add */
  10272. char **pzErr /* OUT: Error message (if any) */
  10273. ){
  10274. IdxScan *pScanOrig = p->pScan;
  10275. IdxStatement *pStmtOrig = p->pStatement;
  10276. int rc = SQLITE_OK;
  10277. const char *zStmt = zSql;
  10278. if( p->bRun ) return SQLITE_MISUSE;
  10279. while( rc==SQLITE_OK && zStmt && zStmt[0] ){
  10280. sqlite3_stmt *pStmt = 0;
  10281. rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
  10282. if( rc==SQLITE_OK ){
  10283. if( pStmt ){
  10284. IdxStatement *pNew;
  10285. const char *z = sqlite3_sql(pStmt);
  10286. int n = STRLEN(z);
  10287. pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
  10288. if( rc==SQLITE_OK ){
  10289. pNew->zSql = (char*)&pNew[1];
  10290. memcpy(pNew->zSql, z, n+1);
  10291. pNew->pNext = p->pStatement;
  10292. if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
  10293. p->pStatement = pNew;
  10294. }
  10295. sqlite3_finalize(pStmt);
  10296. }
  10297. }else{
  10298. idxDatabaseError(p->dbv, pzErr);
  10299. }
  10300. }
  10301. if( rc!=SQLITE_OK ){
  10302. idxScanFree(p->pScan, pScanOrig);
  10303. idxStatementFree(p->pStatement, pStmtOrig);
  10304. p->pScan = pScanOrig;
  10305. p->pStatement = pStmtOrig;
  10306. }
  10307. return rc;
  10308. }
  10309. int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
  10310. int rc;
  10311. IdxHashEntry *pEntry;
  10312. /* Do trigger processing to collect any extra IdxScan structures */
  10313. rc = idxProcessTriggers(p, pzErr);
  10314. /* Create candidate indexes within the in-memory database file */
  10315. if( rc==SQLITE_OK ){
  10316. rc = idxCreateCandidates(p);
  10317. }else if ( rc==SQLITE_BUSY_TIMEOUT ){
  10318. if( pzErr )
  10319. *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
  10320. return rc;
  10321. }
  10322. /* Generate the stat1 data */
  10323. if( rc==SQLITE_OK ){
  10324. rc = idxPopulateStat1(p, pzErr);
  10325. }
  10326. /* Formulate the EXPERT_REPORT_CANDIDATES text */
  10327. for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
  10328. p->zCandidates = idxAppendText(&rc, p->zCandidates,
  10329. "%s;%s%s\n", pEntry->zVal,
  10330. pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
  10331. );
  10332. }
  10333. /* Figure out which of the candidate indexes are preferred by the query
  10334. ** planner and report the results to the user. */
  10335. if( rc==SQLITE_OK ){
  10336. rc = idxFindIndexes(p, pzErr);
  10337. }
  10338. if( rc==SQLITE_OK ){
  10339. p->bRun = 1;
  10340. }
  10341. return rc;
  10342. }
  10343. /*
  10344. ** Return the total number of statements that have been added to this
  10345. ** sqlite3expert using sqlite3_expert_sql().
  10346. */
  10347. int sqlite3_expert_count(sqlite3expert *p){
  10348. int nRet = 0;
  10349. if( p->pStatement ) nRet = p->pStatement->iId+1;
  10350. return nRet;
  10351. }
  10352. /*
  10353. ** Return a component of the report.
  10354. */
  10355. const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
  10356. const char *zRet = 0;
  10357. IdxStatement *pStmt;
  10358. if( p->bRun==0 ) return 0;
  10359. for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
  10360. switch( eReport ){
  10361. case EXPERT_REPORT_SQL:
  10362. if( pStmt ) zRet = pStmt->zSql;
  10363. break;
  10364. case EXPERT_REPORT_INDEXES:
  10365. if( pStmt ) zRet = pStmt->zIdx;
  10366. break;
  10367. case EXPERT_REPORT_PLAN:
  10368. if( pStmt ) zRet = pStmt->zEQP;
  10369. break;
  10370. case EXPERT_REPORT_CANDIDATES:
  10371. zRet = p->zCandidates;
  10372. break;
  10373. }
  10374. return zRet;
  10375. }
  10376. /*
  10377. ** Free an sqlite3expert object.
  10378. */
  10379. void sqlite3_expert_destroy(sqlite3expert *p){
  10380. if( p ){
  10381. sqlite3_close(p->dbm);
  10382. sqlite3_close(p->dbv);
  10383. idxScanFree(p->pScan, 0);
  10384. idxStatementFree(p->pStatement, 0);
  10385. idxTableFree(p->pTable);
  10386. idxWriteFree(p->pWrite);
  10387. idxHashClear(&p->hIdx);
  10388. sqlite3_free(p->zCandidates);
  10389. sqlite3_free(p);
  10390. }
  10391. }
  10392. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  10393. /************************* End ../ext/expert/sqlite3expert.c ********************/
  10394. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
  10395. /************************* Begin ../ext/misc/dbdata.c ******************/
  10396. /*
  10397. ** 2019-04-17
  10398. **
  10399. ** The author disclaims copyright to this source code. In place of
  10400. ** a legal notice, here is a blessing:
  10401. **
  10402. ** May you do good and not evil.
  10403. ** May you find forgiveness for yourself and forgive others.
  10404. ** May you share freely, never taking more than you give.
  10405. **
  10406. ******************************************************************************
  10407. **
  10408. ** This file contains an implementation of two eponymous virtual tables,
  10409. ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
  10410. ** "sqlite_dbpage" eponymous virtual table be available.
  10411. **
  10412. ** SQLITE_DBDATA:
  10413. ** sqlite_dbdata is used to extract data directly from a database b-tree
  10414. ** page and its associated overflow pages, bypassing the b-tree layer.
  10415. ** The table schema is equivalent to:
  10416. **
  10417. ** CREATE TABLE sqlite_dbdata(
  10418. ** pgno INTEGER,
  10419. ** cell INTEGER,
  10420. ** field INTEGER,
  10421. ** value ANY,
  10422. ** schema TEXT HIDDEN
  10423. ** );
  10424. **
  10425. ** IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
  10426. ** FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
  10427. ** "schema".
  10428. **
  10429. ** Each page of the database is inspected. If it cannot be interpreted as
  10430. ** a b-tree page, or if it is a b-tree page containing 0 entries, the
  10431. ** sqlite_dbdata table contains no rows for that page. Otherwise, the
  10432. ** table contains one row for each field in the record associated with
  10433. ** each cell on the page. For intkey b-trees, the key value is stored in
  10434. ** field -1.
  10435. **
  10436. ** For example, for the database:
  10437. **
  10438. ** CREATE TABLE t1(a, b); -- root page is page 2
  10439. ** INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
  10440. ** INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
  10441. **
  10442. ** the sqlite_dbdata table contains, as well as from entries related to
  10443. ** page 1, content equivalent to:
  10444. **
  10445. ** INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
  10446. ** (2, 0, -1, 5 ),
  10447. ** (2, 0, 0, 'v' ),
  10448. ** (2, 0, 1, 'five'),
  10449. ** (2, 1, -1, 10 ),
  10450. ** (2, 1, 0, 'x' ),
  10451. ** (2, 1, 1, 'ten' );
  10452. **
  10453. ** If database corruption is encountered, this module does not report an
  10454. ** error. Instead, it attempts to extract as much data as possible and
  10455. ** ignores the corruption.
  10456. **
  10457. ** SQLITE_DBPTR:
  10458. ** The sqlite_dbptr table has the following schema:
  10459. **
  10460. ** CREATE TABLE sqlite_dbptr(
  10461. ** pgno INTEGER,
  10462. ** child INTEGER,
  10463. ** schema TEXT HIDDEN
  10464. ** );
  10465. **
  10466. ** It contains one entry for each b-tree pointer between a parent and
  10467. ** child page in the database.
  10468. */
  10469. #if !defined(SQLITEINT_H)
  10470. /* #include "sqlite3ext.h" */
  10471. /* typedef unsigned char u8; */
  10472. #endif
  10473. SQLITE_EXTENSION_INIT1
  10474. #include <string.h>
  10475. #include <assert.h>
  10476. #define DBDATA_PADDING_BYTES 100
  10477. typedef struct DbdataTable DbdataTable;
  10478. typedef struct DbdataCursor DbdataCursor;
  10479. /* Cursor object */
  10480. struct DbdataCursor {
  10481. sqlite3_vtab_cursor base; /* Base class. Must be first */
  10482. sqlite3_stmt *pStmt; /* For fetching database pages */
  10483. int iPgno; /* Current page number */
  10484. u8 *aPage; /* Buffer containing page */
  10485. int nPage; /* Size of aPage[] in bytes */
  10486. int nCell; /* Number of cells on aPage[] */
  10487. int iCell; /* Current cell number */
  10488. int bOnePage; /* True to stop after one page */
  10489. int szDb;
  10490. sqlite3_int64 iRowid;
  10491. /* Only for the sqlite_dbdata table */
  10492. u8 *pRec; /* Buffer containing current record */
  10493. int nRec; /* Size of pRec[] in bytes */
  10494. int nHdr; /* Size of header in bytes */
  10495. int iField; /* Current field number */
  10496. u8 *pHdrPtr;
  10497. u8 *pPtr;
  10498. sqlite3_int64 iIntkey; /* Integer key value */
  10499. };
  10500. /* Table object */
  10501. struct DbdataTable {
  10502. sqlite3_vtab base; /* Base class. Must be first */
  10503. sqlite3 *db; /* The database connection */
  10504. sqlite3_stmt *pStmt; /* For fetching database pages */
  10505. int bPtr; /* True for sqlite3_dbptr table */
  10506. };
  10507. /* Column and schema definitions for sqlite_dbdata */
  10508. #define DBDATA_COLUMN_PGNO 0
  10509. #define DBDATA_COLUMN_CELL 1
  10510. #define DBDATA_COLUMN_FIELD 2
  10511. #define DBDATA_COLUMN_VALUE 3
  10512. #define DBDATA_COLUMN_SCHEMA 4
  10513. #define DBDATA_SCHEMA \
  10514. "CREATE TABLE x(" \
  10515. " pgno INTEGER," \
  10516. " cell INTEGER," \
  10517. " field INTEGER," \
  10518. " value ANY," \
  10519. " schema TEXT HIDDEN" \
  10520. ")"
  10521. /* Column and schema definitions for sqlite_dbptr */
  10522. #define DBPTR_COLUMN_PGNO 0
  10523. #define DBPTR_COLUMN_CHILD 1
  10524. #define DBPTR_COLUMN_SCHEMA 2
  10525. #define DBPTR_SCHEMA \
  10526. "CREATE TABLE x(" \
  10527. " pgno INTEGER," \
  10528. " child INTEGER," \
  10529. " schema TEXT HIDDEN" \
  10530. ")"
  10531. /*
  10532. ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
  10533. ** table.
  10534. */
  10535. static int dbdataConnect(
  10536. sqlite3 *db,
  10537. void *pAux,
  10538. int argc, const char *const*argv,
  10539. sqlite3_vtab **ppVtab,
  10540. char **pzErr
  10541. ){
  10542. DbdataTable *pTab = 0;
  10543. int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
  10544. if( rc==SQLITE_OK ){
  10545. pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
  10546. if( pTab==0 ){
  10547. rc = SQLITE_NOMEM;
  10548. }else{
  10549. memset(pTab, 0, sizeof(DbdataTable));
  10550. pTab->db = db;
  10551. pTab->bPtr = (pAux!=0);
  10552. }
  10553. }
  10554. *ppVtab = (sqlite3_vtab*)pTab;
  10555. return rc;
  10556. }
  10557. /*
  10558. ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
  10559. */
  10560. static int dbdataDisconnect(sqlite3_vtab *pVtab){
  10561. DbdataTable *pTab = (DbdataTable*)pVtab;
  10562. if( pTab ){
  10563. sqlite3_finalize(pTab->pStmt);
  10564. sqlite3_free(pVtab);
  10565. }
  10566. return SQLITE_OK;
  10567. }
  10568. /*
  10569. ** This function interprets two types of constraints:
  10570. **
  10571. ** schema=?
  10572. ** pgno=?
  10573. **
  10574. ** If neither are present, idxNum is set to 0. If schema=? is present,
  10575. ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
  10576. ** in idxNum is set.
  10577. **
  10578. ** If both parameters are present, schema is in position 0 and pgno in
  10579. ** position 1.
  10580. */
  10581. static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
  10582. DbdataTable *pTab = (DbdataTable*)tab;
  10583. int i;
  10584. int iSchema = -1;
  10585. int iPgno = -1;
  10586. int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
  10587. for(i=0; i<pIdx->nConstraint; i++){
  10588. struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
  10589. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  10590. if( p->iColumn==colSchema ){
  10591. if( p->usable==0 ) return SQLITE_CONSTRAINT;
  10592. iSchema = i;
  10593. }
  10594. if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
  10595. iPgno = i;
  10596. }
  10597. }
  10598. }
  10599. if( iSchema>=0 ){
  10600. pIdx->aConstraintUsage[iSchema].argvIndex = 1;
  10601. pIdx->aConstraintUsage[iSchema].omit = 1;
  10602. }
  10603. if( iPgno>=0 ){
  10604. pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
  10605. pIdx->aConstraintUsage[iPgno].omit = 1;
  10606. pIdx->estimatedCost = 100;
  10607. pIdx->estimatedRows = 50;
  10608. if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
  10609. int iCol = pIdx->aOrderBy[0].iColumn;
  10610. if( pIdx->nOrderBy==1 ){
  10611. pIdx->orderByConsumed = (iCol==0 || iCol==1);
  10612. }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
  10613. pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
  10614. }
  10615. }
  10616. }else{
  10617. pIdx->estimatedCost = 100000000;
  10618. pIdx->estimatedRows = 1000000000;
  10619. }
  10620. pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
  10621. return SQLITE_OK;
  10622. }
  10623. /*
  10624. ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
  10625. */
  10626. static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  10627. DbdataCursor *pCsr;
  10628. pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
  10629. if( pCsr==0 ){
  10630. return SQLITE_NOMEM;
  10631. }else{
  10632. memset(pCsr, 0, sizeof(DbdataCursor));
  10633. pCsr->base.pVtab = pVTab;
  10634. }
  10635. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  10636. return SQLITE_OK;
  10637. }
  10638. /*
  10639. ** Restore a cursor object to the state it was in when first allocated
  10640. ** by dbdataOpen().
  10641. */
  10642. static void dbdataResetCursor(DbdataCursor *pCsr){
  10643. DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
  10644. if( pTab->pStmt==0 ){
  10645. pTab->pStmt = pCsr->pStmt;
  10646. }else{
  10647. sqlite3_finalize(pCsr->pStmt);
  10648. }
  10649. pCsr->pStmt = 0;
  10650. pCsr->iPgno = 1;
  10651. pCsr->iCell = 0;
  10652. pCsr->iField = 0;
  10653. pCsr->bOnePage = 0;
  10654. sqlite3_free(pCsr->aPage);
  10655. sqlite3_free(pCsr->pRec);
  10656. pCsr->pRec = 0;
  10657. pCsr->aPage = 0;
  10658. }
  10659. /*
  10660. ** Close an sqlite_dbdata or sqlite_dbptr cursor.
  10661. */
  10662. static int dbdataClose(sqlite3_vtab_cursor *pCursor){
  10663. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  10664. dbdataResetCursor(pCsr);
  10665. sqlite3_free(pCsr);
  10666. return SQLITE_OK;
  10667. }
  10668. /*
  10669. ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
  10670. */
  10671. static unsigned int get_uint16(unsigned char *a){
  10672. return (a[0]<<8)|a[1];
  10673. }
  10674. static unsigned int get_uint32(unsigned char *a){
  10675. return ((unsigned int)a[0]<<24)
  10676. | ((unsigned int)a[1]<<16)
  10677. | ((unsigned int)a[2]<<8)
  10678. | ((unsigned int)a[3]);
  10679. }
  10680. /*
  10681. ** Load page pgno from the database via the sqlite_dbpage virtual table.
  10682. ** If successful, set (*ppPage) to point to a buffer containing the page
  10683. ** data, (*pnPage) to the size of that buffer in bytes and return
  10684. ** SQLITE_OK. In this case it is the responsibility of the caller to
  10685. ** eventually free the buffer using sqlite3_free().
  10686. **
  10687. ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
  10688. ** return an SQLite error code.
  10689. */
  10690. static int dbdataLoadPage(
  10691. DbdataCursor *pCsr, /* Cursor object */
  10692. unsigned int pgno, /* Page number of page to load */
  10693. u8 **ppPage, /* OUT: pointer to page buffer */
  10694. int *pnPage /* OUT: Size of (*ppPage) in bytes */
  10695. ){
  10696. int rc2;
  10697. int rc = SQLITE_OK;
  10698. sqlite3_stmt *pStmt = pCsr->pStmt;
  10699. *ppPage = 0;
  10700. *pnPage = 0;
  10701. sqlite3_bind_int64(pStmt, 2, pgno);
  10702. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  10703. int nCopy = sqlite3_column_bytes(pStmt, 0);
  10704. if( nCopy>0 ){
  10705. u8 *pPage;
  10706. pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
  10707. if( pPage==0 ){
  10708. rc = SQLITE_NOMEM;
  10709. }else{
  10710. const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
  10711. memcpy(pPage, pCopy, nCopy);
  10712. memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
  10713. }
  10714. *ppPage = pPage;
  10715. *pnPage = nCopy;
  10716. }
  10717. }
  10718. rc2 = sqlite3_reset(pStmt);
  10719. if( rc==SQLITE_OK ) rc = rc2;
  10720. return rc;
  10721. }
  10722. /*
  10723. ** Read a varint. Put the value in *pVal and return the number of bytes.
  10724. */
  10725. static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
  10726. sqlite3_int64 v = 0;
  10727. int i;
  10728. for(i=0; i<8; i++){
  10729. v = (v<<7) + (z[i]&0x7f);
  10730. if( (z[i]&0x80)==0 ){ *pVal = v; return i+1; }
  10731. }
  10732. v = (v<<8) + (z[i]&0xff);
  10733. *pVal = v;
  10734. return 9;
  10735. }
  10736. /*
  10737. ** Return the number of bytes of space used by an SQLite value of type
  10738. ** eType.
  10739. */
  10740. static int dbdataValueBytes(int eType){
  10741. switch( eType ){
  10742. case 0: case 8: case 9:
  10743. case 10: case 11:
  10744. return 0;
  10745. case 1:
  10746. return 1;
  10747. case 2:
  10748. return 2;
  10749. case 3:
  10750. return 3;
  10751. case 4:
  10752. return 4;
  10753. case 5:
  10754. return 6;
  10755. case 6:
  10756. case 7:
  10757. return 8;
  10758. default:
  10759. if( eType>0 ){
  10760. return ((eType-12) / 2);
  10761. }
  10762. return 0;
  10763. }
  10764. }
  10765. /*
  10766. ** Load a value of type eType from buffer pData and use it to set the
  10767. ** result of context object pCtx.
  10768. */
  10769. static void dbdataValue(
  10770. sqlite3_context *pCtx,
  10771. int eType,
  10772. u8 *pData,
  10773. int nData
  10774. ){
  10775. if( eType>=0 && dbdataValueBytes(eType)<=nData ){
  10776. switch( eType ){
  10777. case 0:
  10778. case 10:
  10779. case 11:
  10780. sqlite3_result_null(pCtx);
  10781. break;
  10782. case 8:
  10783. sqlite3_result_int(pCtx, 0);
  10784. break;
  10785. case 9:
  10786. sqlite3_result_int(pCtx, 1);
  10787. break;
  10788. case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
  10789. sqlite3_uint64 v = (signed char)pData[0];
  10790. pData++;
  10791. switch( eType ){
  10792. case 7:
  10793. case 6: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2;
  10794. case 5: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2;
  10795. case 4: v = (v<<8) + pData[0]; pData++;
  10796. case 3: v = (v<<8) + pData[0]; pData++;
  10797. case 2: v = (v<<8) + pData[0]; pData++;
  10798. }
  10799. if( eType==7 ){
  10800. double r;
  10801. memcpy(&r, &v, sizeof(r));
  10802. sqlite3_result_double(pCtx, r);
  10803. }else{
  10804. sqlite3_result_int64(pCtx, (sqlite3_int64)v);
  10805. }
  10806. break;
  10807. }
  10808. default: {
  10809. int n = ((eType-12) / 2);
  10810. if( eType % 2 ){
  10811. sqlite3_result_text(pCtx, (const char*)pData, n, SQLITE_TRANSIENT);
  10812. }else{
  10813. sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
  10814. }
  10815. }
  10816. }
  10817. }
  10818. }
  10819. /*
  10820. ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
  10821. */
  10822. static int dbdataNext(sqlite3_vtab_cursor *pCursor){
  10823. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  10824. DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
  10825. pCsr->iRowid++;
  10826. while( 1 ){
  10827. int rc;
  10828. int iOff = (pCsr->iPgno==1 ? 100 : 0);
  10829. int bNextPage = 0;
  10830. if( pCsr->aPage==0 ){
  10831. while( 1 ){
  10832. if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
  10833. rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
  10834. if( rc!=SQLITE_OK ) return rc;
  10835. if( pCsr->aPage ) break;
  10836. pCsr->iPgno++;
  10837. }
  10838. pCsr->iCell = pTab->bPtr ? -2 : 0;
  10839. pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
  10840. }
  10841. if( pTab->bPtr ){
  10842. if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
  10843. pCsr->iCell = pCsr->nCell;
  10844. }
  10845. pCsr->iCell++;
  10846. if( pCsr->iCell>=pCsr->nCell ){
  10847. sqlite3_free(pCsr->aPage);
  10848. pCsr->aPage = 0;
  10849. if( pCsr->bOnePage ) return SQLITE_OK;
  10850. pCsr->iPgno++;
  10851. }else{
  10852. return SQLITE_OK;
  10853. }
  10854. }else{
  10855. /* If there is no record loaded, load it now. */
  10856. if( pCsr->pRec==0 ){
  10857. int bHasRowid = 0;
  10858. int nPointer = 0;
  10859. sqlite3_int64 nPayload = 0;
  10860. sqlite3_int64 nHdr = 0;
  10861. int iHdr;
  10862. int U, X;
  10863. int nLocal;
  10864. switch( pCsr->aPage[iOff] ){
  10865. case 0x02:
  10866. nPointer = 4;
  10867. break;
  10868. case 0x0a:
  10869. break;
  10870. case 0x0d:
  10871. bHasRowid = 1;
  10872. break;
  10873. default:
  10874. /* This is not a b-tree page with records on it. Continue. */
  10875. pCsr->iCell = pCsr->nCell;
  10876. break;
  10877. }
  10878. if( pCsr->iCell>=pCsr->nCell ){
  10879. bNextPage = 1;
  10880. }else{
  10881. iOff += 8 + nPointer + pCsr->iCell*2;
  10882. if( iOff>pCsr->nPage ){
  10883. bNextPage = 1;
  10884. }else{
  10885. iOff = get_uint16(&pCsr->aPage[iOff]);
  10886. }
  10887. /* For an interior node cell, skip past the child-page number */
  10888. iOff += nPointer;
  10889. /* Load the "byte of payload including overflow" field */
  10890. if( bNextPage || iOff>pCsr->nPage ){
  10891. bNextPage = 1;
  10892. }else{
  10893. iOff += dbdataGetVarint(&pCsr->aPage[iOff], &nPayload);
  10894. }
  10895. /* If this is a leaf intkey cell, load the rowid */
  10896. if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
  10897. iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
  10898. }
  10899. /* Figure out how much data to read from the local page */
  10900. U = pCsr->nPage;
  10901. if( bHasRowid ){
  10902. X = U-35;
  10903. }else{
  10904. X = ((U-12)*64/255)-23;
  10905. }
  10906. if( nPayload<=X ){
  10907. nLocal = nPayload;
  10908. }else{
  10909. int M, K;
  10910. M = ((U-12)*32/255)-23;
  10911. K = M+((nPayload-M)%(U-4));
  10912. if( K<=X ){
  10913. nLocal = K;
  10914. }else{
  10915. nLocal = M;
  10916. }
  10917. }
  10918. if( bNextPage || nLocal+iOff>pCsr->nPage ){
  10919. bNextPage = 1;
  10920. }else{
  10921. /* Allocate space for payload. And a bit more to catch small buffer
  10922. ** overruns caused by attempting to read a varint or similar from
  10923. ** near the end of a corrupt record. */
  10924. pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
  10925. if( pCsr->pRec==0 ) return SQLITE_NOMEM;
  10926. memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
  10927. pCsr->nRec = nPayload;
  10928. /* Load the nLocal bytes of payload */
  10929. memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
  10930. iOff += nLocal;
  10931. /* Load content from overflow pages */
  10932. if( nPayload>nLocal ){
  10933. sqlite3_int64 nRem = nPayload - nLocal;
  10934. unsigned int pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
  10935. while( nRem>0 ){
  10936. u8 *aOvfl = 0;
  10937. int nOvfl = 0;
  10938. int nCopy;
  10939. rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
  10940. assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
  10941. if( rc!=SQLITE_OK ) return rc;
  10942. if( aOvfl==0 ) break;
  10943. nCopy = U-4;
  10944. if( nCopy>nRem ) nCopy = nRem;
  10945. memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
  10946. nRem -= nCopy;
  10947. pgnoOvfl = get_uint32(aOvfl);
  10948. sqlite3_free(aOvfl);
  10949. }
  10950. }
  10951. iHdr = dbdataGetVarint(pCsr->pRec, &nHdr);
  10952. pCsr->nHdr = nHdr;
  10953. pCsr->pHdrPtr = &pCsr->pRec[iHdr];
  10954. pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
  10955. pCsr->iField = (bHasRowid ? -1 : 0);
  10956. }
  10957. }
  10958. }else{
  10959. pCsr->iField++;
  10960. if( pCsr->iField>0 ){
  10961. sqlite3_int64 iType;
  10962. if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
  10963. bNextPage = 1;
  10964. }else{
  10965. pCsr->pHdrPtr += dbdataGetVarint(pCsr->pHdrPtr, &iType);
  10966. pCsr->pPtr += dbdataValueBytes(iType);
  10967. }
  10968. }
  10969. }
  10970. if( bNextPage ){
  10971. sqlite3_free(pCsr->aPage);
  10972. sqlite3_free(pCsr->pRec);
  10973. pCsr->aPage = 0;
  10974. pCsr->pRec = 0;
  10975. if( pCsr->bOnePage ) return SQLITE_OK;
  10976. pCsr->iPgno++;
  10977. }else{
  10978. if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
  10979. return SQLITE_OK;
  10980. }
  10981. /* Advance to the next cell. The next iteration of the loop will load
  10982. ** the record and so on. */
  10983. sqlite3_free(pCsr->pRec);
  10984. pCsr->pRec = 0;
  10985. pCsr->iCell++;
  10986. }
  10987. }
  10988. }
  10989. assert( !"can't get here" );
  10990. return SQLITE_OK;
  10991. }
  10992. /*
  10993. ** Return true if the cursor is at EOF.
  10994. */
  10995. static int dbdataEof(sqlite3_vtab_cursor *pCursor){
  10996. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  10997. return pCsr->aPage==0;
  10998. }
  10999. /*
  11000. ** Determine the size in pages of database zSchema (where zSchema is
  11001. ** "main", "temp" or the name of an attached database) and set
  11002. ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
  11003. ** an SQLite error code.
  11004. */
  11005. static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
  11006. DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
  11007. char *zSql = 0;
  11008. int rc, rc2;
  11009. sqlite3_stmt *pStmt = 0;
  11010. zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
  11011. if( zSql==0 ) return SQLITE_NOMEM;
  11012. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  11013. sqlite3_free(zSql);
  11014. if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
  11015. pCsr->szDb = sqlite3_column_int(pStmt, 0);
  11016. }
  11017. rc2 = sqlite3_finalize(pStmt);
  11018. if( rc==SQLITE_OK ) rc = rc2;
  11019. return rc;
  11020. }
  11021. /*
  11022. ** xFilter method for sqlite_dbdata and sqlite_dbptr.
  11023. */
  11024. static int dbdataFilter(
  11025. sqlite3_vtab_cursor *pCursor,
  11026. int idxNum, const char *idxStr,
  11027. int argc, sqlite3_value **argv
  11028. ){
  11029. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  11030. DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
  11031. int rc = SQLITE_OK;
  11032. const char *zSchema = "main";
  11033. dbdataResetCursor(pCsr);
  11034. assert( pCsr->iPgno==1 );
  11035. if( idxNum & 0x01 ){
  11036. zSchema = (const char*)sqlite3_value_text(argv[0]);
  11037. }
  11038. if( idxNum & 0x02 ){
  11039. pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
  11040. pCsr->bOnePage = 1;
  11041. }else{
  11042. pCsr->nPage = dbdataDbsize(pCsr, zSchema);
  11043. rc = dbdataDbsize(pCsr, zSchema);
  11044. }
  11045. if( rc==SQLITE_OK ){
  11046. if( pTab->pStmt ){
  11047. pCsr->pStmt = pTab->pStmt;
  11048. pTab->pStmt = 0;
  11049. }else{
  11050. rc = sqlite3_prepare_v2(pTab->db,
  11051. "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
  11052. &pCsr->pStmt, 0
  11053. );
  11054. }
  11055. }
  11056. if( rc==SQLITE_OK ){
  11057. rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
  11058. }else{
  11059. pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
  11060. }
  11061. if( rc==SQLITE_OK ){
  11062. rc = dbdataNext(pCursor);
  11063. }
  11064. return rc;
  11065. }
  11066. /*
  11067. ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
  11068. */
  11069. static int dbdataColumn(
  11070. sqlite3_vtab_cursor *pCursor,
  11071. sqlite3_context *ctx,
  11072. int i
  11073. ){
  11074. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  11075. DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
  11076. if( pTab->bPtr ){
  11077. switch( i ){
  11078. case DBPTR_COLUMN_PGNO:
  11079. sqlite3_result_int64(ctx, pCsr->iPgno);
  11080. break;
  11081. case DBPTR_COLUMN_CHILD: {
  11082. int iOff = pCsr->iPgno==1 ? 100 : 0;
  11083. if( pCsr->iCell<0 ){
  11084. iOff += 8;
  11085. }else{
  11086. iOff += 12 + pCsr->iCell*2;
  11087. if( iOff>pCsr->nPage ) return SQLITE_OK;
  11088. iOff = get_uint16(&pCsr->aPage[iOff]);
  11089. }
  11090. if( iOff<=pCsr->nPage ){
  11091. sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
  11092. }
  11093. break;
  11094. }
  11095. }
  11096. }else{
  11097. switch( i ){
  11098. case DBDATA_COLUMN_PGNO:
  11099. sqlite3_result_int64(ctx, pCsr->iPgno);
  11100. break;
  11101. case DBDATA_COLUMN_CELL:
  11102. sqlite3_result_int(ctx, pCsr->iCell);
  11103. break;
  11104. case DBDATA_COLUMN_FIELD:
  11105. sqlite3_result_int(ctx, pCsr->iField);
  11106. break;
  11107. case DBDATA_COLUMN_VALUE: {
  11108. if( pCsr->iField<0 ){
  11109. sqlite3_result_int64(ctx, pCsr->iIntkey);
  11110. }else{
  11111. sqlite3_int64 iType;
  11112. dbdataGetVarint(pCsr->pHdrPtr, &iType);
  11113. dbdataValue(
  11114. ctx, iType, pCsr->pPtr, &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
  11115. );
  11116. }
  11117. break;
  11118. }
  11119. }
  11120. }
  11121. return SQLITE_OK;
  11122. }
  11123. /*
  11124. ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
  11125. */
  11126. static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  11127. DbdataCursor *pCsr = (DbdataCursor*)pCursor;
  11128. *pRowid = pCsr->iRowid;
  11129. return SQLITE_OK;
  11130. }
  11131. /*
  11132. ** Invoke this routine to register the "sqlite_dbdata" virtual table module
  11133. */
  11134. static int sqlite3DbdataRegister(sqlite3 *db){
  11135. static sqlite3_module dbdata_module = {
  11136. 0, /* iVersion */
  11137. 0, /* xCreate */
  11138. dbdataConnect, /* xConnect */
  11139. dbdataBestIndex, /* xBestIndex */
  11140. dbdataDisconnect, /* xDisconnect */
  11141. 0, /* xDestroy */
  11142. dbdataOpen, /* xOpen - open a cursor */
  11143. dbdataClose, /* xClose - close a cursor */
  11144. dbdataFilter, /* xFilter - configure scan constraints */
  11145. dbdataNext, /* xNext - advance a cursor */
  11146. dbdataEof, /* xEof - check for end of scan */
  11147. dbdataColumn, /* xColumn - read data */
  11148. dbdataRowid, /* xRowid - read data */
  11149. 0, /* xUpdate */
  11150. 0, /* xBegin */
  11151. 0, /* xSync */
  11152. 0, /* xCommit */
  11153. 0, /* xRollback */
  11154. 0, /* xFindMethod */
  11155. 0, /* xRename */
  11156. 0, /* xSavepoint */
  11157. 0, /* xRelease */
  11158. 0, /* xRollbackTo */
  11159. 0 /* xShadowName */
  11160. };
  11161. int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
  11162. if( rc==SQLITE_OK ){
  11163. rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
  11164. }
  11165. return rc;
  11166. }
  11167. #ifdef _WIN32
  11168. #endif
  11169. int sqlite3_dbdata_init(
  11170. sqlite3 *db,
  11171. char **pzErrMsg,
  11172. const sqlite3_api_routines *pApi
  11173. ){
  11174. SQLITE_EXTENSION_INIT2(pApi);
  11175. return sqlite3DbdataRegister(db);
  11176. }
  11177. /************************* End ../ext/misc/dbdata.c ********************/
  11178. #endif
  11179. #if defined(SQLITE_ENABLE_SESSION)
  11180. /*
  11181. ** State information for a single open session
  11182. */
  11183. typedef struct OpenSession OpenSession;
  11184. struct OpenSession {
  11185. char *zName; /* Symbolic name for this session */
  11186. int nFilter; /* Number of xFilter rejection GLOB patterns */
  11187. char **azFilter; /* Array of xFilter rejection GLOB patterns */
  11188. sqlite3_session *p; /* The open session */
  11189. };
  11190. #endif
  11191. typedef struct ExpertInfo ExpertInfo;
  11192. struct ExpertInfo {
  11193. sqlite3expert *pExpert;
  11194. int bVerbose;
  11195. };
  11196. /* A single line in the EQP output */
  11197. typedef struct EQPGraphRow EQPGraphRow;
  11198. struct EQPGraphRow {
  11199. int iEqpId; /* ID for this row */
  11200. int iParentId; /* ID of the parent row */
  11201. EQPGraphRow *pNext; /* Next row in sequence */
  11202. char zText[1]; /* Text to display for this row */
  11203. };
  11204. /* All EQP output is collected into an instance of the following */
  11205. typedef struct EQPGraph EQPGraph;
  11206. struct EQPGraph {
  11207. EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
  11208. EQPGraphRow *pLast; /* Last element of the pRow list */
  11209. char zPrefix[100]; /* Graph prefix */
  11210. };
  11211. /* Parameters affecting columnar mode result display (defaulting together) */
  11212. typedef struct ColModeOpts {
  11213. int iWrap; /* In columnar modes, wrap lines reaching this limit */
  11214. u8 bQuote; /* Quote results for .mode box and table */
  11215. u8 bWordWrap; /* In columnar modes, wrap at word boundaries */
  11216. } ColModeOpts;
  11217. #define ColModeOpts_default { 60, 0, 0 }
  11218. #define ColModeOpts_default_qbox { 60, 1, 0 }
  11219. /*
  11220. ** State information about the database connection is contained in an
  11221. ** instance of the following structure.
  11222. */
  11223. typedef struct ShellState ShellState;
  11224. struct ShellState {
  11225. sqlite3 *db; /* The database */
  11226. u8 autoExplain; /* Automatically turn on .explain mode */
  11227. u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
  11228. u8 autoEQPtest; /* autoEQP is in test mode */
  11229. u8 autoEQPtrace; /* autoEQP is in trace mode */
  11230. u8 scanstatsOn; /* True to display scan stats before each finalize */
  11231. u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
  11232. u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
  11233. u8 nEqpLevel; /* Depth of the EQP output graph */
  11234. u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
  11235. u8 bSafeMode; /* True to prohibit unsafe operations */
  11236. u8 bSafeModePersist; /* The long-term value of bSafeMode */
  11237. ColModeOpts cmOpts; /* Option values affecting columnar mode output */
  11238. unsigned statsOn; /* True to display memory stats before each finalize */
  11239. unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
  11240. int inputNesting; /* Track nesting level of .read and other redirects */
  11241. int outCount; /* Revert to stdout when reaching zero */
  11242. int cnt; /* Number of records displayed so far */
  11243. int lineno; /* Line number of last line read from in */
  11244. int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
  11245. FILE *in; /* Read commands from this stream */
  11246. FILE *out; /* Write results here */
  11247. FILE *traceOut; /* Output for sqlite3_trace() */
  11248. int nErr; /* Number of errors seen */
  11249. int mode; /* An output mode setting */
  11250. int modePrior; /* Saved mode */
  11251. int cMode; /* temporary output mode for the current query */
  11252. int normalMode; /* Output mode before ".explain on" */
  11253. int writableSchema; /* True if PRAGMA writable_schema=ON */
  11254. int showHeader; /* True to show column names in List or Column mode */
  11255. int nCheck; /* Number of ".check" commands run */
  11256. unsigned nProgress; /* Number of progress callbacks encountered */
  11257. unsigned mxProgress; /* Maximum progress callbacks before failing */
  11258. unsigned flgProgress; /* Flags for the progress callback */
  11259. unsigned shellFlgs; /* Various flags */
  11260. unsigned priorShFlgs; /* Saved copy of flags */
  11261. sqlite3_int64 szMax; /* --maxsize argument to .open */
  11262. char *zDestTable; /* Name of destination table when MODE_Insert */
  11263. char *zTempFile; /* Temporary file that might need deleting */
  11264. char zTestcase[30]; /* Name of current test case */
  11265. char colSeparator[20]; /* Column separator character for several modes */
  11266. char rowSeparator[20]; /* Row separator character for MODE_Ascii */
  11267. char colSepPrior[20]; /* Saved column separator */
  11268. char rowSepPrior[20]; /* Saved row separator */
  11269. int *colWidth; /* Requested width of each column in columnar modes */
  11270. int *actualWidth; /* Actual width of each column */
  11271. int nWidth; /* Number of slots in colWidth[] and actualWidth[] */
  11272. char nullValue[20]; /* The text to print when a NULL comes back from
  11273. ** the database */
  11274. char outfile[FILENAME_MAX]; /* Filename for *out */
  11275. sqlite3_stmt *pStmt; /* Current statement if any. */
  11276. FILE *pLog; /* Write log output here */
  11277. struct AuxDb { /* Storage space for auxiliary database connections */
  11278. sqlite3 *db; /* Connection pointer */
  11279. const char *zDbFilename; /* Filename used to open the connection */
  11280. char *zFreeOnClose; /* Free this memory allocation on close */
  11281. #if defined(SQLITE_ENABLE_SESSION)
  11282. int nSession; /* Number of active sessions */
  11283. OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
  11284. #endif
  11285. } aAuxDb[5], /* Array of all database connections */
  11286. *pAuxDb; /* Currently active database connection */
  11287. int *aiIndent; /* Array of indents used in MODE_Explain */
  11288. int nIndent; /* Size of array aiIndent[] */
  11289. int iIndent; /* Index of current op in aiIndent[] */
  11290. char *zNonce; /* Nonce for temporary safe-mode excapes */
  11291. EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
  11292. ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
  11293. };
  11294. /* Allowed values for ShellState.autoEQP
  11295. */
  11296. #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
  11297. #define AUTOEQP_on 1 /* Automatic EQP is on */
  11298. #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
  11299. #define AUTOEQP_full 3 /* Show full EXPLAIN */
  11300. /* Allowed values for ShellState.openMode
  11301. */
  11302. #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
  11303. #define SHELL_OPEN_NORMAL 1 /* Normal database file */
  11304. #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
  11305. #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
  11306. #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
  11307. #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
  11308. #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
  11309. /* Allowed values for ShellState.eTraceType
  11310. */
  11311. #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
  11312. #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
  11313. #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
  11314. /* Bits in the ShellState.flgProgress variable */
  11315. #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
  11316. #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
  11317. ** callback limit is reached, and for each
  11318. ** top-level SQL statement */
  11319. #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
  11320. /*
  11321. ** These are the allowed shellFlgs values
  11322. */
  11323. #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
  11324. #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
  11325. #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
  11326. #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
  11327. #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
  11328. #define SHFLG_CountChanges 0x00000020 /* .changes setting */
  11329. #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
  11330. #define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */
  11331. #define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */
  11332. #define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */
  11333. /*
  11334. ** Macros for testing and setting shellFlgs
  11335. */
  11336. #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
  11337. #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
  11338. #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
  11339. /*
  11340. ** These are the allowed modes.
  11341. */
  11342. #define MODE_Line 0 /* One column per line. Blank line between records */
  11343. #define MODE_Column 1 /* One record per line in neat columns */
  11344. #define MODE_List 2 /* One record per line with a separator */
  11345. #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
  11346. #define MODE_Html 4 /* Generate an XHTML table */
  11347. #define MODE_Insert 5 /* Generate SQL "insert" statements */
  11348. #define MODE_Quote 6 /* Quote values as for SQL */
  11349. #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
  11350. #define MODE_Csv 8 /* Quote strings, numbers are plain */
  11351. #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
  11352. #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
  11353. #define MODE_Pretty 11 /* Pretty-print schemas */
  11354. #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
  11355. #define MODE_Json 13 /* Output JSON */
  11356. #define MODE_Markdown 14 /* Markdown formatting */
  11357. #define MODE_Table 15 /* MySQL-style table formatting */
  11358. #define MODE_Box 16 /* Unicode box-drawing characters */
  11359. #define MODE_Count 17 /* Output only a count of the rows of output */
  11360. #define MODE_Off 18 /* No query output shown */
  11361. static const char *modeDescr[] = {
  11362. "line",
  11363. "column",
  11364. "list",
  11365. "semi",
  11366. "html",
  11367. "insert",
  11368. "quote",
  11369. "tcl",
  11370. "csv",
  11371. "explain",
  11372. "ascii",
  11373. "prettyprint",
  11374. "eqp",
  11375. "json",
  11376. "markdown",
  11377. "table",
  11378. "box",
  11379. "count",
  11380. "off"
  11381. };
  11382. /*
  11383. ** These are the column/row/line separators used by the various
  11384. ** import/export modes.
  11385. */
  11386. #define SEP_Column "|"
  11387. #define SEP_Row "\n"
  11388. #define SEP_Tab "\t"
  11389. #define SEP_Space " "
  11390. #define SEP_Comma ","
  11391. #define SEP_CrLf "\r\n"
  11392. #define SEP_Unit "\x1F"
  11393. #define SEP_Record "\x1E"
  11394. /*
  11395. ** Limit input nesting via .read or any other input redirect.
  11396. ** It's not too expensive, so a generous allowance can be made.
  11397. */
  11398. #define MAX_INPUT_NESTING 25
  11399. /*
  11400. ** A callback for the sqlite3_log() interface.
  11401. */
  11402. static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  11403. ShellState *p = (ShellState*)pArg;
  11404. if( p->pLog==0 ) return;
  11405. utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  11406. fflush(p->pLog);
  11407. }
  11408. /*
  11409. ** SQL function: shell_putsnl(X)
  11410. **
  11411. ** Write the text X to the screen (or whatever output is being directed)
  11412. ** adding a newline at the end, and then return X.
  11413. */
  11414. static void shellPutsFunc(
  11415. sqlite3_context *pCtx,
  11416. int nVal,
  11417. sqlite3_value **apVal
  11418. ){
  11419. ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
  11420. (void)nVal;
  11421. utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
  11422. sqlite3_result_value(pCtx, apVal[0]);
  11423. }
  11424. /*
  11425. ** If in safe mode, print an error message described by the arguments
  11426. ** and exit immediately.
  11427. */
  11428. static void failIfSafeMode(
  11429. ShellState *p,
  11430. const char *zErrMsg,
  11431. ...
  11432. ){
  11433. if( p->bSafeMode ){
  11434. va_list ap;
  11435. char *zMsg;
  11436. va_start(ap, zErrMsg);
  11437. zMsg = sqlite3_vmprintf(zErrMsg, ap);
  11438. va_end(ap);
  11439. raw_printf(stderr, "line %d: ", p->lineno);
  11440. utf8_printf(stderr, "%s\n", zMsg);
  11441. exit(1);
  11442. }
  11443. }
  11444. /*
  11445. ** SQL function: edit(VALUE)
  11446. ** edit(VALUE,EDITOR)
  11447. **
  11448. ** These steps:
  11449. **
  11450. ** (1) Write VALUE into a temporary file.
  11451. ** (2) Run program EDITOR on that temporary file.
  11452. ** (3) Read the temporary file back and return its content as the result.
  11453. ** (4) Delete the temporary file
  11454. **
  11455. ** If the EDITOR argument is omitted, use the value in the VISUAL
  11456. ** environment variable. If still there is no EDITOR, through an error.
  11457. **
  11458. ** Also throw an error if the EDITOR program returns a non-zero exit code.
  11459. */
  11460. #ifndef SQLITE_NOHAVE_SYSTEM
  11461. static void editFunc(
  11462. sqlite3_context *context,
  11463. int argc,
  11464. sqlite3_value **argv
  11465. ){
  11466. const char *zEditor;
  11467. char *zTempFile = 0;
  11468. sqlite3 *db;
  11469. char *zCmd = 0;
  11470. int bBin;
  11471. int rc;
  11472. int hasCRNL = 0;
  11473. FILE *f = 0;
  11474. sqlite3_int64 sz;
  11475. sqlite3_int64 x;
  11476. unsigned char *p = 0;
  11477. if( argc==2 ){
  11478. zEditor = (const char*)sqlite3_value_text(argv[1]);
  11479. }else{
  11480. zEditor = getenv("VISUAL");
  11481. }
  11482. if( zEditor==0 ){
  11483. sqlite3_result_error(context, "no editor for edit()", -1);
  11484. return;
  11485. }
  11486. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  11487. sqlite3_result_error(context, "NULL input to edit()", -1);
  11488. return;
  11489. }
  11490. db = sqlite3_context_db_handle(context);
  11491. zTempFile = 0;
  11492. sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
  11493. if( zTempFile==0 ){
  11494. sqlite3_uint64 r = 0;
  11495. sqlite3_randomness(sizeof(r), &r);
  11496. zTempFile = sqlite3_mprintf("temp%llx", r);
  11497. if( zTempFile==0 ){
  11498. sqlite3_result_error_nomem(context);
  11499. return;
  11500. }
  11501. }
  11502. bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
  11503. /* When writing the file to be edited, do \n to \r\n conversions on systems
  11504. ** that want \r\n line endings */
  11505. f = fopen(zTempFile, bBin ? "wb" : "w");
  11506. if( f==0 ){
  11507. sqlite3_result_error(context, "edit() cannot open temp file", -1);
  11508. goto edit_func_end;
  11509. }
  11510. sz = sqlite3_value_bytes(argv[0]);
  11511. if( bBin ){
  11512. x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
  11513. }else{
  11514. const char *z = (const char*)sqlite3_value_text(argv[0]);
  11515. /* Remember whether or not the value originally contained \r\n */
  11516. if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
  11517. x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
  11518. }
  11519. fclose(f);
  11520. f = 0;
  11521. if( x!=sz ){
  11522. sqlite3_result_error(context, "edit() could not write the whole file", -1);
  11523. goto edit_func_end;
  11524. }
  11525. zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
  11526. if( zCmd==0 ){
  11527. sqlite3_result_error_nomem(context);
  11528. goto edit_func_end;
  11529. }
  11530. rc = system(zCmd);
  11531. sqlite3_free(zCmd);
  11532. if( rc ){
  11533. sqlite3_result_error(context, "EDITOR returned non-zero", -1);
  11534. goto edit_func_end;
  11535. }
  11536. f = fopen(zTempFile, "rb");
  11537. if( f==0 ){
  11538. sqlite3_result_error(context,
  11539. "edit() cannot reopen temp file after edit", -1);
  11540. goto edit_func_end;
  11541. }
  11542. fseek(f, 0, SEEK_END);
  11543. sz = ftell(f);
  11544. rewind(f);
  11545. p = sqlite3_malloc64( sz+1 );
  11546. if( p==0 ){
  11547. sqlite3_result_error_nomem(context);
  11548. goto edit_func_end;
  11549. }
  11550. x = fread(p, 1, (size_t)sz, f);
  11551. fclose(f);
  11552. f = 0;
  11553. if( x!=sz ){
  11554. sqlite3_result_error(context, "could not read back the whole file", -1);
  11555. goto edit_func_end;
  11556. }
  11557. if( bBin ){
  11558. sqlite3_result_blob64(context, p, sz, sqlite3_free);
  11559. }else{
  11560. sqlite3_int64 i, j;
  11561. if( hasCRNL ){
  11562. /* If the original contains \r\n then do no conversions back to \n */
  11563. }else{
  11564. /* If the file did not originally contain \r\n then convert any new
  11565. ** \r\n back into \n */
  11566. for(i=j=0; i<sz; i++){
  11567. if( p[i]=='\r' && p[i+1]=='\n' ) i++;
  11568. p[j++] = p[i];
  11569. }
  11570. sz = j;
  11571. p[sz] = 0;
  11572. }
  11573. sqlite3_result_text64(context, (const char*)p, sz,
  11574. sqlite3_free, SQLITE_UTF8);
  11575. }
  11576. p = 0;
  11577. edit_func_end:
  11578. if( f ) fclose(f);
  11579. unlink(zTempFile);
  11580. sqlite3_free(zTempFile);
  11581. sqlite3_free(p);
  11582. }
  11583. #endif /* SQLITE_NOHAVE_SYSTEM */
  11584. /*
  11585. ** Save or restore the current output mode
  11586. */
  11587. static void outputModePush(ShellState *p){
  11588. p->modePrior = p->mode;
  11589. p->priorShFlgs = p->shellFlgs;
  11590. memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
  11591. memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
  11592. }
  11593. static void outputModePop(ShellState *p){
  11594. p->mode = p->modePrior;
  11595. p->shellFlgs = p->priorShFlgs;
  11596. memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
  11597. memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
  11598. }
  11599. /*
  11600. ** Output the given string as a hex-encoded blob (eg. X'1234' )
  11601. */
  11602. static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  11603. int i;
  11604. char *zBlob = (char *)pBlob;
  11605. raw_printf(out,"X'");
  11606. for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
  11607. raw_printf(out,"'");
  11608. }
  11609. /*
  11610. ** Find a string that is not found anywhere in z[]. Return a pointer
  11611. ** to that string.
  11612. **
  11613. ** Try to use zA and zB first. If both of those are already found in z[]
  11614. ** then make up some string and store it in the buffer zBuf.
  11615. */
  11616. static const char *unused_string(
  11617. const char *z, /* Result must not appear anywhere in z */
  11618. const char *zA, const char *zB, /* Try these first */
  11619. char *zBuf /* Space to store a generated string */
  11620. ){
  11621. unsigned i = 0;
  11622. if( strstr(z, zA)==0 ) return zA;
  11623. if( strstr(z, zB)==0 ) return zB;
  11624. do{
  11625. sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
  11626. }while( strstr(z,zBuf)!=0 );
  11627. return zBuf;
  11628. }
  11629. /*
  11630. ** Output the given string as a quoted string using SQL quoting conventions.
  11631. **
  11632. ** See also: output_quoted_escaped_string()
  11633. */
  11634. static void output_quoted_string(FILE *out, const char *z){
  11635. int i;
  11636. char c;
  11637. setBinaryMode(out, 1);
  11638. for(i=0; (c = z[i])!=0 && c!='\''; i++){}
  11639. if( c==0 ){
  11640. utf8_printf(out,"'%s'",z);
  11641. }else{
  11642. raw_printf(out, "'");
  11643. while( *z ){
  11644. for(i=0; (c = z[i])!=0 && c!='\''; i++){}
  11645. if( c=='\'' ) i++;
  11646. if( i ){
  11647. utf8_printf(out, "%.*s", i, z);
  11648. z += i;
  11649. }
  11650. if( c=='\'' ){
  11651. raw_printf(out, "'");
  11652. continue;
  11653. }
  11654. if( c==0 ){
  11655. break;
  11656. }
  11657. z++;
  11658. }
  11659. raw_printf(out, "'");
  11660. }
  11661. setTextMode(out, 1);
  11662. }
  11663. /*
  11664. ** Output the given string as a quoted string using SQL quoting conventions.
  11665. ** Additionallly , escape the "\n" and "\r" characters so that they do not
  11666. ** get corrupted by end-of-line translation facilities in some operating
  11667. ** systems.
  11668. **
  11669. ** This is like output_quoted_string() but with the addition of the \r\n
  11670. ** escape mechanism.
  11671. */
  11672. static void output_quoted_escaped_string(FILE *out, const char *z){
  11673. int i;
  11674. char c;
  11675. setBinaryMode(out, 1);
  11676. for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
  11677. if( c==0 ){
  11678. utf8_printf(out,"'%s'",z);
  11679. }else{
  11680. const char *zNL = 0;
  11681. const char *zCR = 0;
  11682. int nNL = 0;
  11683. int nCR = 0;
  11684. char zBuf1[20], zBuf2[20];
  11685. for(i=0; z[i]; i++){
  11686. if( z[i]=='\n' ) nNL++;
  11687. if( z[i]=='\r' ) nCR++;
  11688. }
  11689. if( nNL ){
  11690. raw_printf(out, "replace(");
  11691. zNL = unused_string(z, "\\n", "\\012", zBuf1);
  11692. }
  11693. if( nCR ){
  11694. raw_printf(out, "replace(");
  11695. zCR = unused_string(z, "\\r", "\\015", zBuf2);
  11696. }
  11697. raw_printf(out, "'");
  11698. while( *z ){
  11699. for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
  11700. if( c=='\'' ) i++;
  11701. if( i ){
  11702. utf8_printf(out, "%.*s", i, z);
  11703. z += i;
  11704. }
  11705. if( c=='\'' ){
  11706. raw_printf(out, "'");
  11707. continue;
  11708. }
  11709. if( c==0 ){
  11710. break;
  11711. }
  11712. z++;
  11713. if( c=='\n' ){
  11714. raw_printf(out, "%s", zNL);
  11715. continue;
  11716. }
  11717. raw_printf(out, "%s", zCR);
  11718. }
  11719. raw_printf(out, "'");
  11720. if( nCR ){
  11721. raw_printf(out, ",'%s',char(13))", zCR);
  11722. }
  11723. if( nNL ){
  11724. raw_printf(out, ",'%s',char(10))", zNL);
  11725. }
  11726. }
  11727. setTextMode(out, 1);
  11728. }
  11729. /*
  11730. ** Output the given string as a quoted according to C or TCL quoting rules.
  11731. */
  11732. static void output_c_string(FILE *out, const char *z){
  11733. unsigned int c;
  11734. fputc('"', out);
  11735. while( (c = *(z++))!=0 ){
  11736. if( c=='\\' ){
  11737. fputc(c, out);
  11738. fputc(c, out);
  11739. }else if( c=='"' ){
  11740. fputc('\\', out);
  11741. fputc('"', out);
  11742. }else if( c=='\t' ){
  11743. fputc('\\', out);
  11744. fputc('t', out);
  11745. }else if( c=='\n' ){
  11746. fputc('\\', out);
  11747. fputc('n', out);
  11748. }else if( c=='\r' ){
  11749. fputc('\\', out);
  11750. fputc('r', out);
  11751. }else if( !isprint(c&0xff) ){
  11752. raw_printf(out, "\\%03o", c&0xff);
  11753. }else{
  11754. fputc(c, out);
  11755. }
  11756. }
  11757. fputc('"', out);
  11758. }
  11759. /*
  11760. ** Output the given string as a quoted according to JSON quoting rules.
  11761. */
  11762. static void output_json_string(FILE *out, const char *z, int n){
  11763. unsigned int c;
  11764. if( n<0 ) n = (int)strlen(z);
  11765. fputc('"', out);
  11766. while( n-- ){
  11767. c = *(z++);
  11768. if( c=='\\' || c=='"' ){
  11769. fputc('\\', out);
  11770. fputc(c, out);
  11771. }else if( c<=0x1f ){
  11772. fputc('\\', out);
  11773. if( c=='\b' ){
  11774. fputc('b', out);
  11775. }else if( c=='\f' ){
  11776. fputc('f', out);
  11777. }else if( c=='\n' ){
  11778. fputc('n', out);
  11779. }else if( c=='\r' ){
  11780. fputc('r', out);
  11781. }else if( c=='\t' ){
  11782. fputc('t', out);
  11783. }else{
  11784. raw_printf(out, "u%04x",c);
  11785. }
  11786. }else{
  11787. fputc(c, out);
  11788. }
  11789. }
  11790. fputc('"', out);
  11791. }
  11792. /*
  11793. ** Output the given string with characters that are special to
  11794. ** HTML escaped.
  11795. */
  11796. static void output_html_string(FILE *out, const char *z){
  11797. int i;
  11798. if( z==0 ) z = "";
  11799. while( *z ){
  11800. for(i=0; z[i]
  11801. && z[i]!='<'
  11802. && z[i]!='&'
  11803. && z[i]!='>'
  11804. && z[i]!='\"'
  11805. && z[i]!='\'';
  11806. i++){}
  11807. if( i>0 ){
  11808. utf8_printf(out,"%.*s",i,z);
  11809. }
  11810. if( z[i]=='<' ){
  11811. raw_printf(out,"&lt;");
  11812. }else if( z[i]=='&' ){
  11813. raw_printf(out,"&amp;");
  11814. }else if( z[i]=='>' ){
  11815. raw_printf(out,"&gt;");
  11816. }else if( z[i]=='\"' ){
  11817. raw_printf(out,"&quot;");
  11818. }else if( z[i]=='\'' ){
  11819. raw_printf(out,"&#39;");
  11820. }else{
  11821. break;
  11822. }
  11823. z += i + 1;
  11824. }
  11825. }
  11826. /*
  11827. ** If a field contains any character identified by a 1 in the following
  11828. ** array, then the string must be quoted for CSV.
  11829. */
  11830. static const char needCsvQuote[] = {
  11831. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  11832. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  11833. 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  11834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  11835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  11836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  11837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  11838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  11839. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  11840. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  11841. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  11842. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  11843. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  11844. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  11845. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  11846. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  11847. };
  11848. /*
  11849. ** Output a single term of CSV. Actually, p->colSeparator is used for
  11850. ** the separator, which may or may not be a comma. p->nullValue is
  11851. ** the null value. Strings are quoted if necessary. The separator
  11852. ** is only issued if bSep is true.
  11853. */
  11854. static void output_csv(ShellState *p, const char *z, int bSep){
  11855. FILE *out = p->out;
  11856. if( z==0 ){
  11857. utf8_printf(out,"%s",p->nullValue);
  11858. }else{
  11859. unsigned i;
  11860. for(i=0; z[i]; i++){
  11861. if( needCsvQuote[((unsigned char*)z)[i]] ){
  11862. i = 0;
  11863. break;
  11864. }
  11865. }
  11866. if( i==0 || strstr(z, p->colSeparator)!=0 ){
  11867. char *zQuoted = sqlite3_mprintf("\"%w\"", z);
  11868. shell_check_oom(zQuoted);
  11869. utf8_printf(out, "%s", zQuoted);
  11870. sqlite3_free(zQuoted);
  11871. }else{
  11872. utf8_printf(out, "%s", z);
  11873. }
  11874. }
  11875. if( bSep ){
  11876. utf8_printf(p->out, "%s", p->colSeparator);
  11877. }
  11878. }
  11879. /*
  11880. ** This routine runs when the user presses Ctrl-C
  11881. */
  11882. static void interrupt_handler(int NotUsed){
  11883. UNUSED_PARAMETER(NotUsed);
  11884. seenInterrupt++;
  11885. if( seenInterrupt>2 ) exit(1);
  11886. if( globalDb ) sqlite3_interrupt(globalDb);
  11887. }
  11888. #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
  11889. /*
  11890. ** This routine runs for console events (e.g. Ctrl-C) on Win32
  11891. */
  11892. static BOOL WINAPI ConsoleCtrlHandler(
  11893. DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
  11894. ){
  11895. if( dwCtrlType==CTRL_C_EVENT ){
  11896. interrupt_handler(0);
  11897. return TRUE;
  11898. }
  11899. return FALSE;
  11900. }
  11901. #endif
  11902. #ifndef SQLITE_OMIT_AUTHORIZATION
  11903. /*
  11904. ** This authorizer runs in safe mode.
  11905. */
  11906. static int safeModeAuth(
  11907. void *pClientData,
  11908. int op,
  11909. const char *zA1,
  11910. const char *zA2,
  11911. const char *zA3,
  11912. const char *zA4
  11913. ){
  11914. ShellState *p = (ShellState*)pClientData;
  11915. static const char *azProhibitedFunctions[] = {
  11916. "edit",
  11917. "fts3_tokenizer",
  11918. "load_extension",
  11919. "readfile",
  11920. "writefile",
  11921. "zipfile",
  11922. "zipfile_cds",
  11923. };
  11924. UNUSED_PARAMETER(zA2);
  11925. UNUSED_PARAMETER(zA3);
  11926. UNUSED_PARAMETER(zA4);
  11927. switch( op ){
  11928. case SQLITE_ATTACH: {
  11929. failIfSafeMode(p, "cannot run ATTACH in safe mode");
  11930. break;
  11931. }
  11932. case SQLITE_FUNCTION: {
  11933. int i;
  11934. for(i=0; i<ArraySize(azProhibitedFunctions); i++){
  11935. if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
  11936. failIfSafeMode(p, "cannot use the %s() function in safe mode",
  11937. azProhibitedFunctions[i]);
  11938. }
  11939. }
  11940. break;
  11941. }
  11942. }
  11943. return SQLITE_OK;
  11944. }
  11945. /*
  11946. ** When the ".auth ON" is set, the following authorizer callback is
  11947. ** invoked. It always returns SQLITE_OK.
  11948. */
  11949. static int shellAuth(
  11950. void *pClientData,
  11951. int op,
  11952. const char *zA1,
  11953. const char *zA2,
  11954. const char *zA3,
  11955. const char *zA4
  11956. ){
  11957. ShellState *p = (ShellState*)pClientData;
  11958. static const char *azAction[] = { 0,
  11959. "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
  11960. "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
  11961. "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
  11962. "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
  11963. "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
  11964. "DROP_TRIGGER", "DROP_VIEW", "INSERT",
  11965. "PRAGMA", "READ", "SELECT",
  11966. "TRANSACTION", "UPDATE", "ATTACH",
  11967. "DETACH", "ALTER_TABLE", "REINDEX",
  11968. "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
  11969. "FUNCTION", "SAVEPOINT", "RECURSIVE"
  11970. };
  11971. int i;
  11972. const char *az[4];
  11973. az[0] = zA1;
  11974. az[1] = zA2;
  11975. az[2] = zA3;
  11976. az[3] = zA4;
  11977. utf8_printf(p->out, "authorizer: %s", azAction[op]);
  11978. for(i=0; i<4; i++){
  11979. raw_printf(p->out, " ");
  11980. if( az[i] ){
  11981. output_c_string(p->out, az[i]);
  11982. }else{
  11983. raw_printf(p->out, "NULL");
  11984. }
  11985. }
  11986. raw_printf(p->out, "\n");
  11987. if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
  11988. return SQLITE_OK;
  11989. }
  11990. #endif
  11991. /*
  11992. ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
  11993. **
  11994. ** This routine converts some CREATE TABLE statements for shadow tables
  11995. ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
  11996. */
  11997. static void printSchemaLine(FILE *out, const char *z, const char *zTail){
  11998. if( z==0 ) return;
  11999. if( zTail==0 ) return;
  12000. if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
  12001. utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
  12002. }else{
  12003. utf8_printf(out, "%s%s", z, zTail);
  12004. }
  12005. }
  12006. static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
  12007. char c = z[n];
  12008. z[n] = 0;
  12009. printSchemaLine(out, z, zTail);
  12010. z[n] = c;
  12011. }
  12012. /*
  12013. ** Return true if string z[] has nothing but whitespace and comments to the
  12014. ** end of the first line.
  12015. */
  12016. static int wsToEol(const char *z){
  12017. int i;
  12018. for(i=0; z[i]; i++){
  12019. if( z[i]=='\n' ) return 1;
  12020. if( IsSpace(z[i]) ) continue;
  12021. if( z[i]=='-' && z[i+1]=='-' ) return 1;
  12022. return 0;
  12023. }
  12024. return 1;
  12025. }
  12026. /*
  12027. ** Add a new entry to the EXPLAIN QUERY PLAN data
  12028. */
  12029. static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
  12030. EQPGraphRow *pNew;
  12031. int nText = strlen30(zText);
  12032. if( p->autoEQPtest ){
  12033. utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
  12034. }
  12035. pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
  12036. shell_check_oom(pNew);
  12037. pNew->iEqpId = iEqpId;
  12038. pNew->iParentId = p2;
  12039. memcpy(pNew->zText, zText, nText+1);
  12040. pNew->pNext = 0;
  12041. if( p->sGraph.pLast ){
  12042. p->sGraph.pLast->pNext = pNew;
  12043. }else{
  12044. p->sGraph.pRow = pNew;
  12045. }
  12046. p->sGraph.pLast = pNew;
  12047. }
  12048. /*
  12049. ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
  12050. ** in p->sGraph.
  12051. */
  12052. static void eqp_reset(ShellState *p){
  12053. EQPGraphRow *pRow, *pNext;
  12054. for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
  12055. pNext = pRow->pNext;
  12056. sqlite3_free(pRow);
  12057. }
  12058. memset(&p->sGraph, 0, sizeof(p->sGraph));
  12059. }
  12060. /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
  12061. ** pOld, or return the first such line if pOld is NULL
  12062. */
  12063. static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
  12064. EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
  12065. while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
  12066. return pRow;
  12067. }
  12068. /* Render a single level of the graph that has iEqpId as its parent. Called
  12069. ** recursively to render sublevels.
  12070. */
  12071. static void eqp_render_level(ShellState *p, int iEqpId){
  12072. EQPGraphRow *pRow, *pNext;
  12073. int n = strlen30(p->sGraph.zPrefix);
  12074. char *z;
  12075. for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
  12076. pNext = eqp_next_row(p, iEqpId, pRow);
  12077. z = pRow->zText;
  12078. utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
  12079. pNext ? "|--" : "`--", z);
  12080. if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
  12081. memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
  12082. eqp_render_level(p, pRow->iEqpId);
  12083. p->sGraph.zPrefix[n] = 0;
  12084. }
  12085. }
  12086. }
  12087. /*
  12088. ** Display and reset the EXPLAIN QUERY PLAN data
  12089. */
  12090. static void eqp_render(ShellState *p){
  12091. EQPGraphRow *pRow = p->sGraph.pRow;
  12092. if( pRow ){
  12093. if( pRow->zText[0]=='-' ){
  12094. if( pRow->pNext==0 ){
  12095. eqp_reset(p);
  12096. return;
  12097. }
  12098. utf8_printf(p->out, "%s\n", pRow->zText+3);
  12099. p->sGraph.pRow = pRow->pNext;
  12100. sqlite3_free(pRow);
  12101. }else{
  12102. utf8_printf(p->out, "QUERY PLAN\n");
  12103. }
  12104. p->sGraph.zPrefix[0] = 0;
  12105. eqp_render_level(p, 0);
  12106. eqp_reset(p);
  12107. }
  12108. }
  12109. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  12110. /*
  12111. ** Progress handler callback.
  12112. */
  12113. static int progress_handler(void *pClientData) {
  12114. ShellState *p = (ShellState*)pClientData;
  12115. p->nProgress++;
  12116. if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
  12117. raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
  12118. if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
  12119. if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
  12120. return 1;
  12121. }
  12122. if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
  12123. raw_printf(p->out, "Progress %u\n", p->nProgress);
  12124. }
  12125. return 0;
  12126. }
  12127. #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
  12128. /*
  12129. ** Print N dashes
  12130. */
  12131. static void print_dashes(FILE *out, int N){
  12132. const char zDash[] = "--------------------------------------------------";
  12133. const int nDash = sizeof(zDash) - 1;
  12134. while( N>nDash ){
  12135. fputs(zDash, out);
  12136. N -= nDash;
  12137. }
  12138. raw_printf(out, "%.*s", N, zDash);
  12139. }
  12140. /*
  12141. ** Print a markdown or table-style row separator using ascii-art
  12142. */
  12143. static void print_row_separator(
  12144. ShellState *p,
  12145. int nArg,
  12146. const char *zSep
  12147. ){
  12148. int i;
  12149. if( nArg>0 ){
  12150. fputs(zSep, p->out);
  12151. print_dashes(p->out, p->actualWidth[0]+2);
  12152. for(i=1; i<nArg; i++){
  12153. fputs(zSep, p->out);
  12154. print_dashes(p->out, p->actualWidth[i]+2);
  12155. }
  12156. fputs(zSep, p->out);
  12157. }
  12158. fputs("\n", p->out);
  12159. }
  12160. /*
  12161. ** This is the callback routine that the shell
  12162. ** invokes for each row of a query result.
  12163. */
  12164. static int shell_callback(
  12165. void *pArg,
  12166. int nArg, /* Number of result columns */
  12167. char **azArg, /* Text of each result column */
  12168. char **azCol, /* Column names */
  12169. int *aiType /* Column types. Might be NULL */
  12170. ){
  12171. int i;
  12172. ShellState *p = (ShellState*)pArg;
  12173. if( azArg==0 ) return 0;
  12174. switch( p->cMode ){
  12175. case MODE_Count:
  12176. case MODE_Off: {
  12177. break;
  12178. }
  12179. case MODE_Line: {
  12180. int w = 5;
  12181. if( azArg==0 ) break;
  12182. for(i=0; i<nArg; i++){
  12183. int len = strlen30(azCol[i] ? azCol[i] : "");
  12184. if( len>w ) w = len;
  12185. }
  12186. if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
  12187. for(i=0; i<nArg; i++){
  12188. utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
  12189. azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
  12190. }
  12191. break;
  12192. }
  12193. case MODE_Explain: {
  12194. static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
  12195. if( nArg>ArraySize(aExplainWidth) ){
  12196. nArg = ArraySize(aExplainWidth);
  12197. }
  12198. if( p->cnt++==0 ){
  12199. for(i=0; i<nArg; i++){
  12200. int w = aExplainWidth[i];
  12201. utf8_width_print(p->out, w, azCol[i]);
  12202. fputs(i==nArg-1 ? "\n" : " ", p->out);
  12203. }
  12204. for(i=0; i<nArg; i++){
  12205. int w = aExplainWidth[i];
  12206. print_dashes(p->out, w);
  12207. fputs(i==nArg-1 ? "\n" : " ", p->out);
  12208. }
  12209. }
  12210. if( azArg==0 ) break;
  12211. for(i=0; i<nArg; i++){
  12212. int w = aExplainWidth[i];
  12213. if( i==nArg-1 ) w = 0;
  12214. if( azArg[i] && strlenChar(azArg[i])>w ){
  12215. w = strlenChar(azArg[i]);
  12216. }
  12217. if( i==1 && p->aiIndent && p->pStmt ){
  12218. if( p->iIndent<p->nIndent ){
  12219. utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
  12220. }
  12221. p->iIndent++;
  12222. }
  12223. utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
  12224. fputs(i==nArg-1 ? "\n" : " ", p->out);
  12225. }
  12226. break;
  12227. }
  12228. case MODE_Semi: { /* .schema and .fullschema output */
  12229. printSchemaLine(p->out, azArg[0], ";\n");
  12230. break;
  12231. }
  12232. case MODE_Pretty: { /* .schema and .fullschema with --indent */
  12233. char *z;
  12234. int j;
  12235. int nParen = 0;
  12236. char cEnd = 0;
  12237. char c;
  12238. int nLine = 0;
  12239. assert( nArg==1 );
  12240. if( azArg[0]==0 ) break;
  12241. if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
  12242. || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
  12243. ){
  12244. utf8_printf(p->out, "%s;\n", azArg[0]);
  12245. break;
  12246. }
  12247. z = sqlite3_mprintf("%s", azArg[0]);
  12248. shell_check_oom(z);
  12249. j = 0;
  12250. for(i=0; IsSpace(z[i]); i++){}
  12251. for(; (c = z[i])!=0; i++){
  12252. if( IsSpace(c) ){
  12253. if( z[j-1]=='\r' ) z[j-1] = '\n';
  12254. if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
  12255. }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
  12256. j--;
  12257. }
  12258. z[j++] = c;
  12259. }
  12260. while( j>0 && IsSpace(z[j-1]) ){ j--; }
  12261. z[j] = 0;
  12262. if( strlen30(z)>=79 ){
  12263. for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
  12264. if( c==cEnd ){
  12265. cEnd = 0;
  12266. }else if( c=='"' || c=='\'' || c=='`' ){
  12267. cEnd = c;
  12268. }else if( c=='[' ){
  12269. cEnd = ']';
  12270. }else if( c=='-' && z[i+1]=='-' ){
  12271. cEnd = '\n';
  12272. }else if( c=='(' ){
  12273. nParen++;
  12274. }else if( c==')' ){
  12275. nParen--;
  12276. if( nLine>0 && nParen==0 && j>0 ){
  12277. printSchemaLineN(p->out, z, j, "\n");
  12278. j = 0;
  12279. }
  12280. }
  12281. z[j++] = c;
  12282. if( nParen==1 && cEnd==0
  12283. && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
  12284. ){
  12285. if( c=='\n' ) j--;
  12286. printSchemaLineN(p->out, z, j, "\n ");
  12287. j = 0;
  12288. nLine++;
  12289. while( IsSpace(z[i+1]) ){ i++; }
  12290. }
  12291. }
  12292. z[j] = 0;
  12293. }
  12294. printSchemaLine(p->out, z, ";\n");
  12295. sqlite3_free(z);
  12296. break;
  12297. }
  12298. case MODE_List: {
  12299. if( p->cnt++==0 && p->showHeader ){
  12300. for(i=0; i<nArg; i++){
  12301. utf8_printf(p->out,"%s%s",azCol[i],
  12302. i==nArg-1 ? p->rowSeparator : p->colSeparator);
  12303. }
  12304. }
  12305. if( azArg==0 ) break;
  12306. for(i=0; i<nArg; i++){
  12307. char *z = azArg[i];
  12308. if( z==0 ) z = p->nullValue;
  12309. utf8_printf(p->out, "%s", z);
  12310. if( i<nArg-1 ){
  12311. utf8_printf(p->out, "%s", p->colSeparator);
  12312. }else{
  12313. utf8_printf(p->out, "%s", p->rowSeparator);
  12314. }
  12315. }
  12316. break;
  12317. }
  12318. case MODE_Html: {
  12319. if( p->cnt++==0 && p->showHeader ){
  12320. raw_printf(p->out,"<TR>");
  12321. for(i=0; i<nArg; i++){
  12322. raw_printf(p->out,"<TH>");
  12323. output_html_string(p->out, azCol[i]);
  12324. raw_printf(p->out,"</TH>\n");
  12325. }
  12326. raw_printf(p->out,"</TR>\n");
  12327. }
  12328. if( azArg==0 ) break;
  12329. raw_printf(p->out,"<TR>");
  12330. for(i=0; i<nArg; i++){
  12331. raw_printf(p->out,"<TD>");
  12332. output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  12333. raw_printf(p->out,"</TD>\n");
  12334. }
  12335. raw_printf(p->out,"</TR>\n");
  12336. break;
  12337. }
  12338. case MODE_Tcl: {
  12339. if( p->cnt++==0 && p->showHeader ){
  12340. for(i=0; i<nArg; i++){
  12341. output_c_string(p->out,azCol[i] ? azCol[i] : "");
  12342. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  12343. }
  12344. utf8_printf(p->out, "%s", p->rowSeparator);
  12345. }
  12346. if( azArg==0 ) break;
  12347. for(i=0; i<nArg; i++){
  12348. output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  12349. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  12350. }
  12351. utf8_printf(p->out, "%s", p->rowSeparator);
  12352. break;
  12353. }
  12354. case MODE_Csv: {
  12355. setBinaryMode(p->out, 1);
  12356. if( p->cnt++==0 && p->showHeader ){
  12357. for(i=0; i<nArg; i++){
  12358. output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  12359. }
  12360. utf8_printf(p->out, "%s", p->rowSeparator);
  12361. }
  12362. if( nArg>0 ){
  12363. for(i=0; i<nArg; i++){
  12364. output_csv(p, azArg[i], i<nArg-1);
  12365. }
  12366. utf8_printf(p->out, "%s", p->rowSeparator);
  12367. }
  12368. setTextMode(p->out, 1);
  12369. break;
  12370. }
  12371. case MODE_Insert: {
  12372. if( azArg==0 ) break;
  12373. utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
  12374. if( p->showHeader ){
  12375. raw_printf(p->out,"(");
  12376. for(i=0; i<nArg; i++){
  12377. if( i>0 ) raw_printf(p->out, ",");
  12378. if( quoteChar(azCol[i]) ){
  12379. char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
  12380. shell_check_oom(z);
  12381. utf8_printf(p->out, "%s", z);
  12382. sqlite3_free(z);
  12383. }else{
  12384. raw_printf(p->out, "%s", azCol[i]);
  12385. }
  12386. }
  12387. raw_printf(p->out,")");
  12388. }
  12389. p->cnt++;
  12390. for(i=0; i<nArg; i++){
  12391. raw_printf(p->out, i>0 ? "," : " VALUES(");
  12392. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  12393. utf8_printf(p->out,"NULL");
  12394. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  12395. if( ShellHasFlag(p, SHFLG_Newlines) ){
  12396. output_quoted_string(p->out, azArg[i]);
  12397. }else{
  12398. output_quoted_escaped_string(p->out, azArg[i]);
  12399. }
  12400. }else if( aiType && aiType[i]==SQLITE_INTEGER ){
  12401. utf8_printf(p->out,"%s", azArg[i]);
  12402. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  12403. char z[50];
  12404. double r = sqlite3_column_double(p->pStmt, i);
  12405. sqlite3_uint64 ur;
  12406. memcpy(&ur,&r,sizeof(r));
  12407. if( ur==0x7ff0000000000000LL ){
  12408. raw_printf(p->out, "1e999");
  12409. }else if( ur==0xfff0000000000000LL ){
  12410. raw_printf(p->out, "-1e999");
  12411. }else{
  12412. sqlite3_int64 ir = (sqlite3_int64)r;
  12413. if( r==(double)ir ){
  12414. sqlite3_snprintf(50,z,"%lld.0", ir);
  12415. }else{
  12416. sqlite3_snprintf(50,z,"%!.20g", r);
  12417. }
  12418. raw_printf(p->out, "%s", z);
  12419. }
  12420. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  12421. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  12422. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  12423. output_hex_blob(p->out, pBlob, nBlob);
  12424. }else if( isNumber(azArg[i], 0) ){
  12425. utf8_printf(p->out,"%s", azArg[i]);
  12426. }else if( ShellHasFlag(p, SHFLG_Newlines) ){
  12427. output_quoted_string(p->out, azArg[i]);
  12428. }else{
  12429. output_quoted_escaped_string(p->out, azArg[i]);
  12430. }
  12431. }
  12432. raw_printf(p->out,");\n");
  12433. break;
  12434. }
  12435. case MODE_Json: {
  12436. if( azArg==0 ) break;
  12437. if( p->cnt==0 ){
  12438. fputs("[{", p->out);
  12439. }else{
  12440. fputs(",\n{", p->out);
  12441. }
  12442. p->cnt++;
  12443. for(i=0; i<nArg; i++){
  12444. output_json_string(p->out, azCol[i], -1);
  12445. putc(':', p->out);
  12446. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  12447. fputs("null",p->out);
  12448. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  12449. char z[50];
  12450. double r = sqlite3_column_double(p->pStmt, i);
  12451. sqlite3_uint64 ur;
  12452. memcpy(&ur,&r,sizeof(r));
  12453. if( ur==0x7ff0000000000000LL ){
  12454. raw_printf(p->out, "1e999");
  12455. }else if( ur==0xfff0000000000000LL ){
  12456. raw_printf(p->out, "-1e999");
  12457. }else{
  12458. sqlite3_snprintf(50,z,"%!.20g", r);
  12459. raw_printf(p->out, "%s", z);
  12460. }
  12461. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  12462. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  12463. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  12464. output_json_string(p->out, pBlob, nBlob);
  12465. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  12466. output_json_string(p->out, azArg[i], -1);
  12467. }else{
  12468. utf8_printf(p->out,"%s", azArg[i]);
  12469. }
  12470. if( i<nArg-1 ){
  12471. putc(',', p->out);
  12472. }
  12473. }
  12474. putc('}', p->out);
  12475. break;
  12476. }
  12477. case MODE_Quote: {
  12478. if( azArg==0 ) break;
  12479. if( p->cnt==0 && p->showHeader ){
  12480. for(i=0; i<nArg; i++){
  12481. if( i>0 ) fputs(p->colSeparator, p->out);
  12482. output_quoted_string(p->out, azCol[i]);
  12483. }
  12484. fputs(p->rowSeparator, p->out);
  12485. }
  12486. p->cnt++;
  12487. for(i=0; i<nArg; i++){
  12488. if( i>0 ) fputs(p->colSeparator, p->out);
  12489. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  12490. utf8_printf(p->out,"NULL");
  12491. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  12492. output_quoted_string(p->out, azArg[i]);
  12493. }else if( aiType && aiType[i]==SQLITE_INTEGER ){
  12494. utf8_printf(p->out,"%s", azArg[i]);
  12495. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  12496. char z[50];
  12497. double r = sqlite3_column_double(p->pStmt, i);
  12498. sqlite3_snprintf(50,z,"%!.20g", r);
  12499. raw_printf(p->out, "%s", z);
  12500. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  12501. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  12502. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  12503. output_hex_blob(p->out, pBlob, nBlob);
  12504. }else if( isNumber(azArg[i], 0) ){
  12505. utf8_printf(p->out,"%s", azArg[i]);
  12506. }else{
  12507. output_quoted_string(p->out, azArg[i]);
  12508. }
  12509. }
  12510. fputs(p->rowSeparator, p->out);
  12511. break;
  12512. }
  12513. case MODE_Ascii: {
  12514. if( p->cnt++==0 && p->showHeader ){
  12515. for(i=0; i<nArg; i++){
  12516. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  12517. utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
  12518. }
  12519. utf8_printf(p->out, "%s", p->rowSeparator);
  12520. }
  12521. if( azArg==0 ) break;
  12522. for(i=0; i<nArg; i++){
  12523. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  12524. utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
  12525. }
  12526. utf8_printf(p->out, "%s", p->rowSeparator);
  12527. break;
  12528. }
  12529. case MODE_EQP: {
  12530. eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
  12531. break;
  12532. }
  12533. }
  12534. return 0;
  12535. }
  12536. /*
  12537. ** This is the callback routine that the SQLite library
  12538. ** invokes for each row of a query result.
  12539. */
  12540. static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  12541. /* since we don't have type info, call the shell_callback with a NULL value */
  12542. return shell_callback(pArg, nArg, azArg, azCol, NULL);
  12543. }
  12544. /*
  12545. ** This is the callback routine from sqlite3_exec() that appends all
  12546. ** output onto the end of a ShellText object.
  12547. */
  12548. static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
  12549. ShellText *p = (ShellText*)pArg;
  12550. int i;
  12551. UNUSED_PARAMETER(az);
  12552. if( azArg==0 ) return 0;
  12553. if( p->n ) appendText(p, "|", 0);
  12554. for(i=0; i<nArg; i++){
  12555. if( i ) appendText(p, ",", 0);
  12556. if( azArg[i] ) appendText(p, azArg[i], 0);
  12557. }
  12558. return 0;
  12559. }
  12560. /*
  12561. ** Generate an appropriate SELFTEST table in the main database.
  12562. */
  12563. static void createSelftestTable(ShellState *p){
  12564. char *zErrMsg = 0;
  12565. sqlite3_exec(p->db,
  12566. "SAVEPOINT selftest_init;\n"
  12567. "CREATE TABLE IF NOT EXISTS selftest(\n"
  12568. " tno INTEGER PRIMARY KEY,\n" /* Test number */
  12569. " op TEXT,\n" /* Operator: memo run */
  12570. " cmd TEXT,\n" /* Command text */
  12571. " ans TEXT\n" /* Desired answer */
  12572. ");"
  12573. "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
  12574. "INSERT INTO [_shell$self](rowid,op,cmd)\n"
  12575. " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
  12576. " 'memo','Tests generated by --init');\n"
  12577. "INSERT INTO [_shell$self]\n"
  12578. " SELECT 'run',\n"
  12579. " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
  12580. "FROM sqlite_schema ORDER BY 2'',224))',\n"
  12581. " hex(sha3_query('SELECT type,name,tbl_name,sql "
  12582. "FROM sqlite_schema ORDER BY 2',224));\n"
  12583. "INSERT INTO [_shell$self]\n"
  12584. " SELECT 'run',"
  12585. " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
  12586. " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
  12587. " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
  12588. " FROM (\n"
  12589. " SELECT name FROM sqlite_schema\n"
  12590. " WHERE type='table'\n"
  12591. " AND name<>'selftest'\n"
  12592. " AND coalesce(rootpage,0)>0\n"
  12593. " )\n"
  12594. " ORDER BY name;\n"
  12595. "INSERT INTO [_shell$self]\n"
  12596. " VALUES('run','PRAGMA integrity_check','ok');\n"
  12597. "INSERT INTO selftest(tno,op,cmd,ans)"
  12598. " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
  12599. "DROP TABLE [_shell$self];"
  12600. ,0,0,&zErrMsg);
  12601. if( zErrMsg ){
  12602. utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
  12603. sqlite3_free(zErrMsg);
  12604. }
  12605. sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
  12606. }
  12607. /*
  12608. ** Set the destination table field of the ShellState structure to
  12609. ** the name of the table given. Escape any quote characters in the
  12610. ** table name.
  12611. */
  12612. static void set_table_name(ShellState *p, const char *zName){
  12613. int i, n;
  12614. char cQuote;
  12615. char *z;
  12616. if( p->zDestTable ){
  12617. free(p->zDestTable);
  12618. p->zDestTable = 0;
  12619. }
  12620. if( zName==0 ) return;
  12621. cQuote = quoteChar(zName);
  12622. n = strlen30(zName);
  12623. if( cQuote ) n += n+2;
  12624. z = p->zDestTable = malloc( n+1 );
  12625. shell_check_oom(z);
  12626. n = 0;
  12627. if( cQuote ) z[n++] = cQuote;
  12628. for(i=0; zName[i]; i++){
  12629. z[n++] = zName[i];
  12630. if( zName[i]==cQuote ) z[n++] = cQuote;
  12631. }
  12632. if( cQuote ) z[n++] = cQuote;
  12633. z[n] = 0;
  12634. }
  12635. /*
  12636. ** Maybe construct two lines of text that point out the position of a
  12637. ** syntax error. Return a pointer to the text, in memory obtained from
  12638. ** sqlite3_malloc(). Or, if the most recent error does not involve a
  12639. ** specific token that we can point to, return an empty string.
  12640. **
  12641. ** In all cases, the memory returned is obtained from sqlite3_malloc64()
  12642. ** and should be released by the caller invoking sqlite3_free().
  12643. */
  12644. static char *shell_error_context(const char *zSql, sqlite3 *db){
  12645. int iOffset;
  12646. size_t len;
  12647. char *zCode;
  12648. char *zMsg;
  12649. int i;
  12650. if( db==0
  12651. || zSql==0
  12652. || (iOffset = sqlite3_error_offset(db))<0
  12653. ){
  12654. return sqlite3_mprintf("");
  12655. }
  12656. while( iOffset>50 ){
  12657. iOffset--;
  12658. zSql++;
  12659. while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
  12660. }
  12661. len = strlen(zSql);
  12662. if( len>78 ){
  12663. len = 78;
  12664. while( (zSql[len]&0xc0)==0x80 ) len--;
  12665. }
  12666. zCode = sqlite3_mprintf("%.*s", len, zSql);
  12667. for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
  12668. if( iOffset<25 ){
  12669. zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode, iOffset, "");
  12670. }else{
  12671. zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode, iOffset-14, "");
  12672. }
  12673. return zMsg;
  12674. }
  12675. /*
  12676. ** Execute a query statement that will generate SQL output. Print
  12677. ** the result columns, comma-separated, on a line and then add a
  12678. ** semicolon terminator to the end of that line.
  12679. **
  12680. ** If the number of columns is 1 and that column contains text "--"
  12681. ** then write the semicolon on a separate line. That way, if a
  12682. ** "--" comment occurs at the end of the statement, the comment
  12683. ** won't consume the semicolon terminator.
  12684. */
  12685. static int run_table_dump_query(
  12686. ShellState *p, /* Query context */
  12687. const char *zSelect /* SELECT statement to extract content */
  12688. ){
  12689. sqlite3_stmt *pSelect;
  12690. int rc;
  12691. int nResult;
  12692. int i;
  12693. const char *z;
  12694. rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
  12695. if( rc!=SQLITE_OK || !pSelect ){
  12696. char *zContext = shell_error_context(zSelect, p->db);
  12697. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
  12698. sqlite3_errmsg(p->db), zContext);
  12699. sqlite3_free(zContext);
  12700. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  12701. return rc;
  12702. }
  12703. rc = sqlite3_step(pSelect);
  12704. nResult = sqlite3_column_count(pSelect);
  12705. while( rc==SQLITE_ROW ){
  12706. z = (const char*)sqlite3_column_text(pSelect, 0);
  12707. utf8_printf(p->out, "%s", z);
  12708. for(i=1; i<nResult; i++){
  12709. utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
  12710. }
  12711. if( z==0 ) z = "";
  12712. while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
  12713. if( z[0] ){
  12714. raw_printf(p->out, "\n;\n");
  12715. }else{
  12716. raw_printf(p->out, ";\n");
  12717. }
  12718. rc = sqlite3_step(pSelect);
  12719. }
  12720. rc = sqlite3_finalize(pSelect);
  12721. if( rc!=SQLITE_OK ){
  12722. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  12723. sqlite3_errmsg(p->db));
  12724. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  12725. }
  12726. return rc;
  12727. }
  12728. /*
  12729. ** Allocate space and save off string indicating current error.
  12730. */
  12731. static char *save_err_msg(
  12732. sqlite3 *db, /* Database to query */
  12733. const char *zPhase, /* When the error occcurs */
  12734. int rc, /* Error code returned from API */
  12735. const char *zSql /* SQL string, or NULL */
  12736. ){
  12737. char *zErr;
  12738. char *zContext;
  12739. sqlite3_str *pStr = sqlite3_str_new(0);
  12740. sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
  12741. if( rc>1 ){
  12742. sqlite3_str_appendf(pStr, " (%d)", rc);
  12743. }
  12744. zContext = shell_error_context(zSql, db);
  12745. if( zContext ){
  12746. sqlite3_str_appendall(pStr, zContext);
  12747. sqlite3_free(zContext);
  12748. }
  12749. zErr = sqlite3_str_finish(pStr);
  12750. shell_check_oom(zErr);
  12751. return zErr;
  12752. }
  12753. #ifdef __linux__
  12754. /*
  12755. ** Attempt to display I/O stats on Linux using /proc/PID/io
  12756. */
  12757. static void displayLinuxIoStats(FILE *out){
  12758. FILE *in;
  12759. char z[200];
  12760. sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
  12761. in = fopen(z, "rb");
  12762. if( in==0 ) return;
  12763. while( fgets(z, sizeof(z), in)!=0 ){
  12764. static const struct {
  12765. const char *zPattern;
  12766. const char *zDesc;
  12767. } aTrans[] = {
  12768. { "rchar: ", "Bytes received by read():" },
  12769. { "wchar: ", "Bytes sent to write():" },
  12770. { "syscr: ", "Read() system calls:" },
  12771. { "syscw: ", "Write() system calls:" },
  12772. { "read_bytes: ", "Bytes read from storage:" },
  12773. { "write_bytes: ", "Bytes written to storage:" },
  12774. { "cancelled_write_bytes: ", "Cancelled write bytes:" },
  12775. };
  12776. int i;
  12777. for(i=0; i<ArraySize(aTrans); i++){
  12778. int n = strlen30(aTrans[i].zPattern);
  12779. if( strncmp(aTrans[i].zPattern, z, n)==0 ){
  12780. utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
  12781. break;
  12782. }
  12783. }
  12784. }
  12785. fclose(in);
  12786. }
  12787. #endif
  12788. /*
  12789. ** Display a single line of status using 64-bit values.
  12790. */
  12791. static void displayStatLine(
  12792. ShellState *p, /* The shell context */
  12793. char *zLabel, /* Label for this one line */
  12794. char *zFormat, /* Format for the result */
  12795. int iStatusCtrl, /* Which status to display */
  12796. int bReset /* True to reset the stats */
  12797. ){
  12798. sqlite3_int64 iCur = -1;
  12799. sqlite3_int64 iHiwtr = -1;
  12800. int i, nPercent;
  12801. char zLine[200];
  12802. sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
  12803. for(i=0, nPercent=0; zFormat[i]; i++){
  12804. if( zFormat[i]=='%' ) nPercent++;
  12805. }
  12806. if( nPercent>1 ){
  12807. sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
  12808. }else{
  12809. sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
  12810. }
  12811. raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
  12812. }
  12813. /*
  12814. ** Display memory stats.
  12815. */
  12816. static int display_stats(
  12817. sqlite3 *db, /* Database to query */
  12818. ShellState *pArg, /* Pointer to ShellState */
  12819. int bReset /* True to reset the stats */
  12820. ){
  12821. int iCur;
  12822. int iHiwtr;
  12823. FILE *out;
  12824. if( pArg==0 || pArg->out==0 ) return 0;
  12825. out = pArg->out;
  12826. if( pArg->pStmt && pArg->statsOn==2 ){
  12827. int nCol, i, x;
  12828. sqlite3_stmt *pStmt = pArg->pStmt;
  12829. char z[100];
  12830. nCol = sqlite3_column_count(pStmt);
  12831. raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
  12832. for(i=0; i<nCol; i++){
  12833. sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
  12834. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
  12835. #ifndef SQLITE_OMIT_DECLTYPE
  12836. sqlite3_snprintf(30, z+x, "declared type:");
  12837. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
  12838. #endif
  12839. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  12840. sqlite3_snprintf(30, z+x, "database name:");
  12841. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
  12842. sqlite3_snprintf(30, z+x, "table name:");
  12843. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
  12844. sqlite3_snprintf(30, z+x, "origin name:");
  12845. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
  12846. #endif
  12847. }
  12848. }
  12849. if( pArg->statsOn==3 ){
  12850. if( pArg->pStmt ){
  12851. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
  12852. raw_printf(pArg->out, "VM-steps: %d\n", iCur);
  12853. }
  12854. return 0;
  12855. }
  12856. displayStatLine(pArg, "Memory Used:",
  12857. "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
  12858. displayStatLine(pArg, "Number of Outstanding Allocations:",
  12859. "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
  12860. if( pArg->shellFlgs & SHFLG_Pagecache ){
  12861. displayStatLine(pArg, "Number of Pcache Pages Used:",
  12862. "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
  12863. }
  12864. displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
  12865. "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
  12866. displayStatLine(pArg, "Largest Allocation:",
  12867. "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
  12868. displayStatLine(pArg, "Largest Pcache Allocation:",
  12869. "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
  12870. #ifdef YYTRACKMAXSTACKDEPTH
  12871. displayStatLine(pArg, "Deepest Parser Stack:",
  12872. "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
  12873. #endif
  12874. if( db ){
  12875. if( pArg->shellFlgs & SHFLG_Lookaside ){
  12876. iHiwtr = iCur = -1;
  12877. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
  12878. &iCur, &iHiwtr, bReset);
  12879. raw_printf(pArg->out,
  12880. "Lookaside Slots Used: %d (max %d)\n",
  12881. iCur, iHiwtr);
  12882. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
  12883. &iCur, &iHiwtr, bReset);
  12884. raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
  12885. iHiwtr);
  12886. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
  12887. &iCur, &iHiwtr, bReset);
  12888. raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
  12889. iHiwtr);
  12890. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
  12891. &iCur, &iHiwtr, bReset);
  12892. raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
  12893. iHiwtr);
  12894. }
  12895. iHiwtr = iCur = -1;
  12896. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
  12897. raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
  12898. iCur);
  12899. iHiwtr = iCur = -1;
  12900. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
  12901. raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
  12902. iHiwtr = iCur = -1;
  12903. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
  12904. raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
  12905. iHiwtr = iCur = -1;
  12906. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
  12907. raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
  12908. iHiwtr = iCur = -1;
  12909. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
  12910. raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
  12911. iHiwtr = iCur = -1;
  12912. sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
  12913. raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
  12914. iCur);
  12915. iHiwtr = iCur = -1;
  12916. sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
  12917. raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
  12918. iCur);
  12919. }
  12920. if( pArg->pStmt ){
  12921. int iHit, iMiss;
  12922. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
  12923. bReset);
  12924. raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
  12925. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
  12926. raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
  12927. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
  12928. raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
  12929. iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
  12930. iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
  12931. if( iHit || iMiss ){
  12932. raw_printf(pArg->out, "Bloom filter bypass taken: %d/%d\n",
  12933. iHit, iHit+iMiss);
  12934. }
  12935. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
  12936. raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
  12937. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
  12938. raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
  12939. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
  12940. raw_printf(pArg->out, "Number of times run: %d\n", iCur);
  12941. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
  12942. raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
  12943. }
  12944. #ifdef __linux__
  12945. displayLinuxIoStats(pArg->out);
  12946. #endif
  12947. /* Do not remove this machine readable comment: extra-stats-output-here */
  12948. return 0;
  12949. }
  12950. /*
  12951. ** Display scan stats.
  12952. */
  12953. static void display_scanstats(
  12954. sqlite3 *db, /* Database to query */
  12955. ShellState *pArg /* Pointer to ShellState */
  12956. ){
  12957. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  12958. UNUSED_PARAMETER(db);
  12959. UNUSED_PARAMETER(pArg);
  12960. #else
  12961. int i, k, n, mx;
  12962. raw_printf(pArg->out, "-------- scanstats --------\n");
  12963. mx = 0;
  12964. for(k=0; k<=mx; k++){
  12965. double rEstLoop = 1.0;
  12966. for(i=n=0; 1; i++){
  12967. sqlite3_stmt *p = pArg->pStmt;
  12968. sqlite3_int64 nLoop, nVisit;
  12969. double rEst;
  12970. int iSid;
  12971. const char *zExplain;
  12972. if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
  12973. break;
  12974. }
  12975. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
  12976. if( iSid>mx ) mx = iSid;
  12977. if( iSid!=k ) continue;
  12978. if( n==0 ){
  12979. rEstLoop = (double)nLoop;
  12980. if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
  12981. }
  12982. n++;
  12983. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
  12984. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
  12985. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
  12986. utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
  12987. rEstLoop *= rEst;
  12988. raw_printf(pArg->out,
  12989. " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
  12990. nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
  12991. );
  12992. }
  12993. }
  12994. raw_printf(pArg->out, "---------------------------\n");
  12995. #endif
  12996. }
  12997. /*
  12998. ** Parameter azArray points to a zero-terminated array of strings. zStr
  12999. ** points to a single nul-terminated string. Return non-zero if zStr
  13000. ** is equal, according to strcmp(), to any of the strings in the array.
  13001. ** Otherwise, return zero.
  13002. */
  13003. static int str_in_array(const char *zStr, const char **azArray){
  13004. int i;
  13005. for(i=0; azArray[i]; i++){
  13006. if( 0==strcmp(zStr, azArray[i]) ) return 1;
  13007. }
  13008. return 0;
  13009. }
  13010. /*
  13011. ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
  13012. ** and populate the ShellState.aiIndent[] array with the number of
  13013. ** spaces each opcode should be indented before it is output.
  13014. **
  13015. ** The indenting rules are:
  13016. **
  13017. ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
  13018. ** all opcodes that occur between the p2 jump destination and the opcode
  13019. ** itself by 2 spaces.
  13020. **
  13021. ** * For each "Goto", if the jump destination is earlier in the program
  13022. ** and ends on one of:
  13023. ** Yield SeekGt SeekLt RowSetRead Rewind
  13024. ** or if the P1 parameter is one instead of zero,
  13025. ** then indent all opcodes between the earlier instruction
  13026. ** and "Goto" by 2 spaces.
  13027. */
  13028. static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
  13029. const char *zSql; /* The text of the SQL statement */
  13030. const char *z; /* Used to check if this is an EXPLAIN */
  13031. int *abYield = 0; /* True if op is an OP_Yield */
  13032. int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
  13033. int iOp; /* Index of operation in p->aiIndent[] */
  13034. const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
  13035. const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
  13036. "Rewind", 0 };
  13037. const char *azGoto[] = { "Goto", 0 };
  13038. /* Try to figure out if this is really an EXPLAIN statement. If this
  13039. ** cannot be verified, return early. */
  13040. if( sqlite3_column_count(pSql)!=8 ){
  13041. p->cMode = p->mode;
  13042. return;
  13043. }
  13044. zSql = sqlite3_sql(pSql);
  13045. if( zSql==0 ) return;
  13046. for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
  13047. if( sqlite3_strnicmp(z, "explain", 7) ){
  13048. p->cMode = p->mode;
  13049. return;
  13050. }
  13051. for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
  13052. int i;
  13053. int iAddr = sqlite3_column_int(pSql, 0);
  13054. const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
  13055. /* Set p2 to the P2 field of the current opcode. Then, assuming that
  13056. ** p2 is an instruction address, set variable p2op to the index of that
  13057. ** instruction in the aiIndent[] array. p2 and p2op may be different if
  13058. ** the current instruction is part of a sub-program generated by an
  13059. ** SQL trigger or foreign key. */
  13060. int p2 = sqlite3_column_int(pSql, 3);
  13061. int p2op = (p2 + (iOp-iAddr));
  13062. /* Grow the p->aiIndent array as required */
  13063. if( iOp>=nAlloc ){
  13064. if( iOp==0 ){
  13065. /* Do further verfication that this is explain output. Abort if
  13066. ** it is not */
  13067. static const char *explainCols[] = {
  13068. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
  13069. int jj;
  13070. for(jj=0; jj<ArraySize(explainCols); jj++){
  13071. if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
  13072. p->cMode = p->mode;
  13073. sqlite3_reset(pSql);
  13074. return;
  13075. }
  13076. }
  13077. }
  13078. nAlloc += 100;
  13079. p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
  13080. shell_check_oom(p->aiIndent);
  13081. abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
  13082. shell_check_oom(abYield);
  13083. }
  13084. abYield[iOp] = str_in_array(zOp, azYield);
  13085. p->aiIndent[iOp] = 0;
  13086. p->nIndent = iOp+1;
  13087. if( str_in_array(zOp, azNext) ){
  13088. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  13089. }
  13090. if( str_in_array(zOp, azGoto) && p2op<p->nIndent
  13091. && (abYield[p2op] || sqlite3_column_int(pSql, 2))
  13092. ){
  13093. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  13094. }
  13095. }
  13096. p->iIndent = 0;
  13097. sqlite3_free(abYield);
  13098. sqlite3_reset(pSql);
  13099. }
  13100. /*
  13101. ** Free the array allocated by explain_data_prepare().
  13102. */
  13103. static void explain_data_delete(ShellState *p){
  13104. sqlite3_free(p->aiIndent);
  13105. p->aiIndent = 0;
  13106. p->nIndent = 0;
  13107. p->iIndent = 0;
  13108. }
  13109. /*
  13110. ** Disable and restore .wheretrace and .selecttrace settings.
  13111. */
  13112. static unsigned int savedSelectTrace;
  13113. static unsigned int savedWhereTrace;
  13114. static void disable_debug_trace_modes(void){
  13115. unsigned int zero = 0;
  13116. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
  13117. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
  13118. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
  13119. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
  13120. }
  13121. static void restore_debug_trace_modes(void){
  13122. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
  13123. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
  13124. }
  13125. /* Create the TEMP table used to store parameter bindings */
  13126. static void bind_table_init(ShellState *p){
  13127. int wrSchema = 0;
  13128. int defensiveMode = 0;
  13129. sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
  13130. sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
  13131. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
  13132. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
  13133. sqlite3_exec(p->db,
  13134. "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
  13135. " key TEXT PRIMARY KEY,\n"
  13136. " value\n"
  13137. ") WITHOUT ROWID;",
  13138. 0, 0, 0);
  13139. sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
  13140. sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
  13141. }
  13142. /*
  13143. ** Bind parameters on a prepared statement.
  13144. **
  13145. ** Parameter bindings are taken from a TEMP table of the form:
  13146. **
  13147. ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
  13148. ** WITHOUT ROWID;
  13149. **
  13150. ** No bindings occur if this table does not exist. The name of the table
  13151. ** begins with "sqlite_" so that it will not collide with ordinary application
  13152. ** tables. The table must be in the TEMP schema.
  13153. */
  13154. static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
  13155. int nVar;
  13156. int i;
  13157. int rc;
  13158. sqlite3_stmt *pQ = 0;
  13159. nVar = sqlite3_bind_parameter_count(pStmt);
  13160. if( nVar==0 ) return; /* Nothing to do */
  13161. if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
  13162. "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
  13163. return; /* Parameter table does not exist */
  13164. }
  13165. rc = sqlite3_prepare_v2(pArg->db,
  13166. "SELECT value FROM temp.sqlite_parameters"
  13167. " WHERE key=?1", -1, &pQ, 0);
  13168. if( rc || pQ==0 ) return;
  13169. for(i=1; i<=nVar; i++){
  13170. char zNum[30];
  13171. const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
  13172. if( zVar==0 ){
  13173. sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
  13174. zVar = zNum;
  13175. }
  13176. sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
  13177. if( sqlite3_step(pQ)==SQLITE_ROW ){
  13178. sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
  13179. }else{
  13180. sqlite3_bind_null(pStmt, i);
  13181. }
  13182. sqlite3_reset(pQ);
  13183. }
  13184. sqlite3_finalize(pQ);
  13185. }
  13186. /*
  13187. ** UTF8 box-drawing characters. Imagine box lines like this:
  13188. **
  13189. ** 1
  13190. ** |
  13191. ** 4 --+-- 2
  13192. ** |
  13193. ** 3
  13194. **
  13195. ** Each box characters has between 2 and 4 of the lines leading from
  13196. ** the center. The characters are here identified by the numbers of
  13197. ** their corresponding lines.
  13198. */
  13199. #define BOX_24 "\342\224\200" /* U+2500 --- */
  13200. #define BOX_13 "\342\224\202" /* U+2502 | */
  13201. #define BOX_23 "\342\224\214" /* U+250c ,- */
  13202. #define BOX_34 "\342\224\220" /* U+2510 -, */
  13203. #define BOX_12 "\342\224\224" /* U+2514 '- */
  13204. #define BOX_14 "\342\224\230" /* U+2518 -' */
  13205. #define BOX_123 "\342\224\234" /* U+251c |- */
  13206. #define BOX_134 "\342\224\244" /* U+2524 -| */
  13207. #define BOX_234 "\342\224\254" /* U+252c -,- */
  13208. #define BOX_124 "\342\224\264" /* U+2534 -'- */
  13209. #define BOX_1234 "\342\224\274" /* U+253c -|- */
  13210. /* Draw horizontal line N characters long using unicode box
  13211. ** characters
  13212. */
  13213. static void print_box_line(FILE *out, int N){
  13214. const char zDash[] =
  13215. BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
  13216. BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
  13217. const int nDash = sizeof(zDash) - 1;
  13218. N *= 3;
  13219. while( N>nDash ){
  13220. utf8_printf(out, zDash);
  13221. N -= nDash;
  13222. }
  13223. utf8_printf(out, "%.*s", N, zDash);
  13224. }
  13225. /*
  13226. ** Draw a horizontal separator for a MODE_Box table.
  13227. */
  13228. static void print_box_row_separator(
  13229. ShellState *p,
  13230. int nArg,
  13231. const char *zSep1,
  13232. const char *zSep2,
  13233. const char *zSep3
  13234. ){
  13235. int i;
  13236. if( nArg>0 ){
  13237. utf8_printf(p->out, "%s", zSep1);
  13238. print_box_line(p->out, p->actualWidth[0]+2);
  13239. for(i=1; i<nArg; i++){
  13240. utf8_printf(p->out, "%s", zSep2);
  13241. print_box_line(p->out, p->actualWidth[i]+2);
  13242. }
  13243. utf8_printf(p->out, "%s", zSep3);
  13244. }
  13245. fputs("\n", p->out);
  13246. }
  13247. /*
  13248. ** z[] is a line of text that is to be displayed the .mode box or table or
  13249. ** similar tabular formats. z[] might contain control characters such
  13250. ** as \n, \t, \f, or \r.
  13251. **
  13252. ** Compute characters to display on the first line of z[]. Stop at the
  13253. ** first \r, \n, or \f. Expand \t into spaces. Return a copy (obtained
  13254. ** from malloc()) of that first line, which caller should free sometime.
  13255. ** Write anything to display on the next line into *pzTail. If this is
  13256. ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
  13257. */
  13258. static char *translateForDisplayAndDup(
  13259. const unsigned char *z, /* Input text to be transformed */
  13260. const unsigned char **pzTail, /* OUT: Tail of the input for next line */
  13261. int mxWidth, /* Max width. 0 means no limit */
  13262. u8 bWordWrap /* If true, avoid breaking mid-word */
  13263. ){
  13264. int i; /* Input bytes consumed */
  13265. int j; /* Output bytes generated */
  13266. int k; /* Input bytes to be displayed */
  13267. int n; /* Output column number */
  13268. unsigned char *zOut; /* Output text */
  13269. if( z==0 ){
  13270. *pzTail = 0;
  13271. return 0;
  13272. }
  13273. if( mxWidth<0 ) mxWidth = -mxWidth;
  13274. if( mxWidth==0 ) mxWidth = 1000000;
  13275. i = j = n = 0;
  13276. while( n<mxWidth ){
  13277. if( z[i]>=' ' ){
  13278. n++;
  13279. do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
  13280. continue;
  13281. }
  13282. if( z[i]=='\t' ){
  13283. do{
  13284. n++;
  13285. j++;
  13286. }while( (n&7)!=0 && n<mxWidth );
  13287. i++;
  13288. continue;
  13289. }
  13290. break;
  13291. }
  13292. if( n>=mxWidth && bWordWrap ){
  13293. /* Perhaps try to back up to a better place to break the line */
  13294. for(k=i; k>i/2; k--){
  13295. if( isspace(z[k-1]) ) break;
  13296. }
  13297. if( k<=i/2 ){
  13298. for(k=i; k>i/2; k--){
  13299. if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
  13300. }
  13301. }
  13302. if( k<=i/2 ){
  13303. k = i;
  13304. }else{
  13305. i = k;
  13306. while( z[i]==' ' ) i++;
  13307. }
  13308. }else{
  13309. k = i;
  13310. }
  13311. if( n>=mxWidth && z[i]>=' ' ){
  13312. *pzTail = &z[i];
  13313. }else if( z[i]=='\r' && z[i+1]=='\n' ){
  13314. *pzTail = z[i+2] ? &z[i+2] : 0;
  13315. }else if( z[i]==0 || z[i+1]==0 ){
  13316. *pzTail = 0;
  13317. }else{
  13318. *pzTail = &z[i+1];
  13319. }
  13320. zOut = malloc( j+1 );
  13321. shell_check_oom(zOut);
  13322. i = j = n = 0;
  13323. while( i<k ){
  13324. if( z[i]>=' ' ){
  13325. n++;
  13326. do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
  13327. continue;
  13328. }
  13329. if( z[i]=='\t' ){
  13330. do{
  13331. n++;
  13332. zOut[j++] = ' ';
  13333. }while( (n&7)!=0 && n<mxWidth );
  13334. i++;
  13335. continue;
  13336. }
  13337. break;
  13338. }
  13339. zOut[j] = 0;
  13340. return (char*)zOut;
  13341. }
  13342. /* Extract the value of the i-th current column for pStmt as an SQL literal
  13343. ** value. Memory is obtained from sqlite3_malloc64() and must be freed by
  13344. ** the caller.
  13345. */
  13346. static char *quoted_column(sqlite3_stmt *pStmt, int i){
  13347. switch( sqlite3_column_type(pStmt, i) ){
  13348. case SQLITE_NULL: {
  13349. return sqlite3_mprintf("NULL");
  13350. }
  13351. case SQLITE_INTEGER:
  13352. case SQLITE_FLOAT: {
  13353. return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
  13354. }
  13355. case SQLITE_TEXT: {
  13356. return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
  13357. }
  13358. case SQLITE_BLOB: {
  13359. int j;
  13360. sqlite3_str *pStr = sqlite3_str_new(0);
  13361. const unsigned char *a = sqlite3_column_blob(pStmt,i);
  13362. int n = sqlite3_column_bytes(pStmt,i);
  13363. sqlite3_str_append(pStr, "x'", 2);
  13364. for(j=0; j<n; j++){
  13365. sqlite3_str_appendf(pStr, "%02x", a[j]);
  13366. }
  13367. sqlite3_str_append(pStr, "'", 1);
  13368. return sqlite3_str_finish(pStr);
  13369. }
  13370. }
  13371. return 0; /* Not reached */
  13372. }
  13373. /*
  13374. ** Run a prepared statement and output the result in one of the
  13375. ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
  13376. ** or MODE_Box.
  13377. **
  13378. ** This is different from ordinary exec_prepared_stmt() in that
  13379. ** it has to run the entire query and gather the results into memory
  13380. ** first, in order to determine column widths, before providing
  13381. ** any output.
  13382. */
  13383. static void exec_prepared_stmt_columnar(
  13384. ShellState *p, /* Pointer to ShellState */
  13385. sqlite3_stmt *pStmt /* Statment to run */
  13386. ){
  13387. sqlite3_int64 nRow = 0;
  13388. int nColumn = 0;
  13389. char **azData = 0;
  13390. sqlite3_int64 nAlloc = 0;
  13391. char *abRowDiv = 0;
  13392. const unsigned char *uz;
  13393. const char *z;
  13394. char **azQuoted = 0;
  13395. int rc;
  13396. sqlite3_int64 i, nData;
  13397. int j, nTotal, w, n;
  13398. const char *colSep = 0;
  13399. const char *rowSep = 0;
  13400. const unsigned char **azNextLine = 0;
  13401. int bNextLine = 0;
  13402. int bMultiLineRowExists = 0;
  13403. int bw = p->cmOpts.bWordWrap;
  13404. const char *zEmpty = "";
  13405. const char *zShowNull = p->nullValue;
  13406. rc = sqlite3_step(pStmt);
  13407. if( rc!=SQLITE_ROW ) return;
  13408. nColumn = sqlite3_column_count(pStmt);
  13409. nAlloc = nColumn*4;
  13410. if( nAlloc<=0 ) nAlloc = 1;
  13411. azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
  13412. shell_check_oom(azData);
  13413. azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
  13414. shell_check_oom((void*)azNextLine);
  13415. memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
  13416. if( p->cmOpts.bQuote ){
  13417. azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
  13418. shell_check_oom(azQuoted);
  13419. memset(azQuoted, 0, nColumn*sizeof(char*) );
  13420. }
  13421. abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
  13422. shell_check_oom(abRowDiv);
  13423. if( nColumn>p->nWidth ){
  13424. p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
  13425. shell_check_oom(p->colWidth);
  13426. for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
  13427. p->nWidth = nColumn;
  13428. p->actualWidth = &p->colWidth[nColumn];
  13429. }
  13430. memset(p->actualWidth, 0, nColumn*sizeof(int));
  13431. for(i=0; i<nColumn; i++){
  13432. w = p->colWidth[i];
  13433. if( w<0 ) w = -w;
  13434. p->actualWidth[i] = w;
  13435. }
  13436. for(i=0; i<nColumn; i++){
  13437. const unsigned char *zNotUsed;
  13438. int wx = p->colWidth[i];
  13439. if( wx==0 ){
  13440. wx = p->cmOpts.iWrap;
  13441. }
  13442. if( wx<0 ) wx = -wx;
  13443. uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
  13444. azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
  13445. }
  13446. do{
  13447. int useNextLine = bNextLine;
  13448. bNextLine = 0;
  13449. if( (nRow+2)*nColumn >= nAlloc ){
  13450. nAlloc *= 2;
  13451. azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
  13452. shell_check_oom(azData);
  13453. abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
  13454. shell_check_oom(abRowDiv);
  13455. }
  13456. abRowDiv[nRow] = 1;
  13457. nRow++;
  13458. for(i=0; i<nColumn; i++){
  13459. int wx = p->colWidth[i];
  13460. if( wx==0 ){
  13461. wx = p->cmOpts.iWrap;
  13462. }
  13463. if( wx<0 ) wx = -wx;
  13464. if( useNextLine ){
  13465. uz = azNextLine[i];
  13466. if( uz==0 ) uz = (u8*)zEmpty;
  13467. }else if( p->cmOpts.bQuote ){
  13468. sqlite3_free(azQuoted[i]);
  13469. azQuoted[i] = quoted_column(pStmt,i);
  13470. uz = (const unsigned char*)azQuoted[i];
  13471. }else{
  13472. uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
  13473. if( uz==0 ) uz = (u8*)zShowNull;
  13474. }
  13475. azData[nRow*nColumn + i]
  13476. = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
  13477. if( azNextLine[i] ){
  13478. bNextLine = 1;
  13479. abRowDiv[nRow-1] = 0;
  13480. bMultiLineRowExists = 1;
  13481. }
  13482. }
  13483. }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
  13484. nTotal = nColumn*(nRow+1);
  13485. for(i=0; i<nTotal; i++){
  13486. z = azData[i];
  13487. if( z==0 ) z = (char*)zEmpty;
  13488. n = strlenChar(z);
  13489. j = i%nColumn;
  13490. if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
  13491. }
  13492. if( seenInterrupt ) goto columnar_end;
  13493. if( nColumn==0 ) goto columnar_end;
  13494. switch( p->cMode ){
  13495. case MODE_Column: {
  13496. colSep = " ";
  13497. rowSep = "\n";
  13498. if( p->showHeader ){
  13499. for(i=0; i<nColumn; i++){
  13500. w = p->actualWidth[i];
  13501. if( p->colWidth[i]<0 ) w = -w;
  13502. utf8_width_print(p->out, w, azData[i]);
  13503. fputs(i==nColumn-1?"\n":" ", p->out);
  13504. }
  13505. for(i=0; i<nColumn; i++){
  13506. print_dashes(p->out, p->actualWidth[i]);
  13507. fputs(i==nColumn-1?"\n":" ", p->out);
  13508. }
  13509. }
  13510. break;
  13511. }
  13512. case MODE_Table: {
  13513. colSep = " | ";
  13514. rowSep = " |\n";
  13515. print_row_separator(p, nColumn, "+");
  13516. fputs("| ", p->out);
  13517. for(i=0; i<nColumn; i++){
  13518. w = p->actualWidth[i];
  13519. n = strlenChar(azData[i]);
  13520. utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
  13521. fputs(i==nColumn-1?" |\n":" | ", p->out);
  13522. }
  13523. print_row_separator(p, nColumn, "+");
  13524. break;
  13525. }
  13526. case MODE_Markdown: {
  13527. colSep = " | ";
  13528. rowSep = " |\n";
  13529. fputs("| ", p->out);
  13530. for(i=0; i<nColumn; i++){
  13531. w = p->actualWidth[i];
  13532. n = strlenChar(azData[i]);
  13533. utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
  13534. fputs(i==nColumn-1?" |\n":" | ", p->out);
  13535. }
  13536. print_row_separator(p, nColumn, "|");
  13537. break;
  13538. }
  13539. case MODE_Box: {
  13540. colSep = " " BOX_13 " ";
  13541. rowSep = " " BOX_13 "\n";
  13542. print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
  13543. utf8_printf(p->out, BOX_13 " ");
  13544. for(i=0; i<nColumn; i++){
  13545. w = p->actualWidth[i];
  13546. n = strlenChar(azData[i]);
  13547. utf8_printf(p->out, "%*s%s%*s%s",
  13548. (w-n)/2, "", azData[i], (w-n+1)/2, "",
  13549. i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
  13550. }
  13551. print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
  13552. break;
  13553. }
  13554. }
  13555. for(i=nColumn, j=0; i<nTotal; i++, j++){
  13556. if( j==0 && p->cMode!=MODE_Column ){
  13557. utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
  13558. }
  13559. z = azData[i];
  13560. if( z==0 ) z = p->nullValue;
  13561. w = p->actualWidth[j];
  13562. if( p->colWidth[j]<0 ) w = -w;
  13563. utf8_width_print(p->out, w, z);
  13564. if( j==nColumn-1 ){
  13565. utf8_printf(p->out, "%s", rowSep);
  13566. if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
  13567. if( p->cMode==MODE_Table ){
  13568. print_row_separator(p, nColumn, "+");
  13569. }else if( p->cMode==MODE_Box ){
  13570. print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
  13571. }else if( p->cMode==MODE_Column ){
  13572. raw_printf(p->out, "\n");
  13573. }
  13574. }
  13575. j = -1;
  13576. if( seenInterrupt ) goto columnar_end;
  13577. }else{
  13578. utf8_printf(p->out, "%s", colSep);
  13579. }
  13580. }
  13581. if( p->cMode==MODE_Table ){
  13582. print_row_separator(p, nColumn, "+");
  13583. }else if( p->cMode==MODE_Box ){
  13584. print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
  13585. }
  13586. columnar_end:
  13587. if( seenInterrupt ){
  13588. utf8_printf(p->out, "Interrupt\n");
  13589. }
  13590. nData = (nRow+1)*nColumn;
  13591. for(i=0; i<nData; i++){
  13592. z = azData[i];
  13593. if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
  13594. }
  13595. sqlite3_free(azData);
  13596. sqlite3_free((void*)azNextLine);
  13597. sqlite3_free(abRowDiv);
  13598. if( azQuoted ){
  13599. for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
  13600. sqlite3_free(azQuoted);
  13601. }
  13602. }
  13603. /*
  13604. ** Run a prepared statement
  13605. */
  13606. static void exec_prepared_stmt(
  13607. ShellState *pArg, /* Pointer to ShellState */
  13608. sqlite3_stmt *pStmt /* Statment to run */
  13609. ){
  13610. int rc;
  13611. sqlite3_uint64 nRow = 0;
  13612. if( pArg->cMode==MODE_Column
  13613. || pArg->cMode==MODE_Table
  13614. || pArg->cMode==MODE_Box
  13615. || pArg->cMode==MODE_Markdown
  13616. ){
  13617. exec_prepared_stmt_columnar(pArg, pStmt);
  13618. return;
  13619. }
  13620. /* perform the first step. this will tell us if we
  13621. ** have a result set or not and how wide it is.
  13622. */
  13623. rc = sqlite3_step(pStmt);
  13624. /* if we have a result set... */
  13625. if( SQLITE_ROW == rc ){
  13626. /* allocate space for col name ptr, value ptr, and type */
  13627. int nCol = sqlite3_column_count(pStmt);
  13628. void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
  13629. if( !pData ){
  13630. shell_out_of_memory();
  13631. }else{
  13632. char **azCols = (char **)pData; /* Names of result columns */
  13633. char **azVals = &azCols[nCol]; /* Results */
  13634. int *aiTypes = (int *)&azVals[nCol]; /* Result types */
  13635. int i, x;
  13636. assert(sizeof(int) <= sizeof(char *));
  13637. /* save off ptrs to column names */
  13638. for(i=0; i<nCol; i++){
  13639. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  13640. }
  13641. do{
  13642. nRow++;
  13643. /* extract the data and data types */
  13644. for(i=0; i<nCol; i++){
  13645. aiTypes[i] = x = sqlite3_column_type(pStmt, i);
  13646. if( x==SQLITE_BLOB
  13647. && pArg
  13648. && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
  13649. ){
  13650. azVals[i] = "";
  13651. }else{
  13652. azVals[i] = (char*)sqlite3_column_text(pStmt, i);
  13653. }
  13654. if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
  13655. rc = SQLITE_NOMEM;
  13656. break; /* from for */
  13657. }
  13658. } /* end for */
  13659. /* if data and types extracted successfully... */
  13660. if( SQLITE_ROW == rc ){
  13661. /* call the supplied callback with the result row data */
  13662. if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
  13663. rc = SQLITE_ABORT;
  13664. }else{
  13665. rc = sqlite3_step(pStmt);
  13666. }
  13667. }
  13668. } while( SQLITE_ROW == rc );
  13669. sqlite3_free(pData);
  13670. if( pArg->cMode==MODE_Json ){
  13671. fputs("]\n", pArg->out);
  13672. }else if( pArg->cMode==MODE_Count ){
  13673. char zBuf[200];
  13674. sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
  13675. nRow, nRow!=1 ? "s" : "");
  13676. printf("%s", zBuf);
  13677. }
  13678. }
  13679. }
  13680. }
  13681. #ifndef SQLITE_OMIT_VIRTUALTABLE
  13682. /*
  13683. ** This function is called to process SQL if the previous shell command
  13684. ** was ".expert". It passes the SQL in the second argument directly to
  13685. ** the sqlite3expert object.
  13686. **
  13687. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
  13688. ** code. In this case, (*pzErr) may be set to point to a buffer containing
  13689. ** an English language error message. It is the responsibility of the
  13690. ** caller to eventually free this buffer using sqlite3_free().
  13691. */
  13692. static int expertHandleSQL(
  13693. ShellState *pState,
  13694. const char *zSql,
  13695. char **pzErr
  13696. ){
  13697. assert( pState->expert.pExpert );
  13698. assert( pzErr==0 || *pzErr==0 );
  13699. return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
  13700. }
  13701. /*
  13702. ** This function is called either to silently clean up the object
  13703. ** created by the ".expert" command (if bCancel==1), or to generate a
  13704. ** report from it and then clean it up (if bCancel==0).
  13705. **
  13706. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
  13707. ** code. In this case, (*pzErr) may be set to point to a buffer containing
  13708. ** an English language error message. It is the responsibility of the
  13709. ** caller to eventually free this buffer using sqlite3_free().
  13710. */
  13711. static int expertFinish(
  13712. ShellState *pState,
  13713. int bCancel,
  13714. char **pzErr
  13715. ){
  13716. int rc = SQLITE_OK;
  13717. sqlite3expert *p = pState->expert.pExpert;
  13718. assert( p );
  13719. assert( bCancel || pzErr==0 || *pzErr==0 );
  13720. if( bCancel==0 ){
  13721. FILE *out = pState->out;
  13722. int bVerbose = pState->expert.bVerbose;
  13723. rc = sqlite3_expert_analyze(p, pzErr);
  13724. if( rc==SQLITE_OK ){
  13725. int nQuery = sqlite3_expert_count(p);
  13726. int i;
  13727. if( bVerbose ){
  13728. const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
  13729. raw_printf(out, "-- Candidates -----------------------------\n");
  13730. raw_printf(out, "%s\n", zCand);
  13731. }
  13732. for(i=0; i<nQuery; i++){
  13733. const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
  13734. const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
  13735. const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
  13736. if( zIdx==0 ) zIdx = "(no new indexes)\n";
  13737. if( bVerbose ){
  13738. raw_printf(out, "-- Query %d --------------------------------\n",i+1);
  13739. raw_printf(out, "%s\n\n", zSql);
  13740. }
  13741. raw_printf(out, "%s\n", zIdx);
  13742. raw_printf(out, "%s\n", zEQP);
  13743. }
  13744. }
  13745. }
  13746. sqlite3_expert_destroy(p);
  13747. pState->expert.pExpert = 0;
  13748. return rc;
  13749. }
  13750. /*
  13751. ** Implementation of ".expert" dot command.
  13752. */
  13753. static int expertDotCommand(
  13754. ShellState *pState, /* Current shell tool state */
  13755. char **azArg, /* Array of arguments passed to dot command */
  13756. int nArg /* Number of entries in azArg[] */
  13757. ){
  13758. int rc = SQLITE_OK;
  13759. char *zErr = 0;
  13760. int i;
  13761. int iSample = 0;
  13762. assert( pState->expert.pExpert==0 );
  13763. memset(&pState->expert, 0, sizeof(ExpertInfo));
  13764. for(i=1; rc==SQLITE_OK && i<nArg; i++){
  13765. char *z = azArg[i];
  13766. int n;
  13767. if( z[0]=='-' && z[1]=='-' ) z++;
  13768. n = strlen30(z);
  13769. if( n>=2 && 0==strncmp(z, "-verbose", n) ){
  13770. pState->expert.bVerbose = 1;
  13771. }
  13772. else if( n>=2 && 0==strncmp(z, "-sample", n) ){
  13773. if( i==(nArg-1) ){
  13774. raw_printf(stderr, "option requires an argument: %s\n", z);
  13775. rc = SQLITE_ERROR;
  13776. }else{
  13777. iSample = (int)integerValue(azArg[++i]);
  13778. if( iSample<0 || iSample>100 ){
  13779. raw_printf(stderr, "value out of range: %s\n", azArg[i]);
  13780. rc = SQLITE_ERROR;
  13781. }
  13782. }
  13783. }
  13784. else{
  13785. raw_printf(stderr, "unknown option: %s\n", z);
  13786. rc = SQLITE_ERROR;
  13787. }
  13788. }
  13789. if( rc==SQLITE_OK ){
  13790. pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
  13791. if( pState->expert.pExpert==0 ){
  13792. raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
  13793. rc = SQLITE_ERROR;
  13794. }else{
  13795. sqlite3_expert_config(
  13796. pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
  13797. );
  13798. }
  13799. }
  13800. sqlite3_free(zErr);
  13801. return rc;
  13802. }
  13803. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  13804. /*
  13805. ** Execute a statement or set of statements. Print
  13806. ** any result rows/columns depending on the current mode
  13807. ** set via the supplied callback.
  13808. **
  13809. ** This is very similar to SQLite's built-in sqlite3_exec()
  13810. ** function except it takes a slightly different callback
  13811. ** and callback data argument.
  13812. */
  13813. static int shell_exec(
  13814. ShellState *pArg, /* Pointer to ShellState */
  13815. const char *zSql, /* SQL to be evaluated */
  13816. char **pzErrMsg /* Error msg written here */
  13817. ){
  13818. sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
  13819. int rc = SQLITE_OK; /* Return Code */
  13820. int rc2;
  13821. const char *zLeftover; /* Tail of unprocessed SQL */
  13822. sqlite3 *db = pArg->db;
  13823. if( pzErrMsg ){
  13824. *pzErrMsg = NULL;
  13825. }
  13826. #ifndef SQLITE_OMIT_VIRTUALTABLE
  13827. if( pArg->expert.pExpert ){
  13828. rc = expertHandleSQL(pArg, zSql, pzErrMsg);
  13829. return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
  13830. }
  13831. #endif
  13832. while( zSql[0] && (SQLITE_OK == rc) ){
  13833. static const char *zStmtSql;
  13834. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  13835. if( SQLITE_OK != rc ){
  13836. if( pzErrMsg ){
  13837. *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
  13838. }
  13839. }else{
  13840. if( !pStmt ){
  13841. /* this happens for a comment or white-space */
  13842. zSql = zLeftover;
  13843. while( IsSpace(zSql[0]) ) zSql++;
  13844. continue;
  13845. }
  13846. zStmtSql = sqlite3_sql(pStmt);
  13847. if( zStmtSql==0 ) zStmtSql = "";
  13848. while( IsSpace(zStmtSql[0]) ) zStmtSql++;
  13849. /* save off the prepared statment handle and reset row count */
  13850. if( pArg ){
  13851. pArg->pStmt = pStmt;
  13852. pArg->cnt = 0;
  13853. }
  13854. /* echo the sql statement if echo on */
  13855. if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
  13856. utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  13857. }
  13858. /* Show the EXPLAIN QUERY PLAN if .eqp is on */
  13859. if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
  13860. sqlite3_stmt *pExplain;
  13861. char *zEQP;
  13862. int triggerEQP = 0;
  13863. disable_debug_trace_modes();
  13864. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
  13865. if( pArg->autoEQP>=AUTOEQP_trigger ){
  13866. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
  13867. }
  13868. zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
  13869. shell_check_oom(zEQP);
  13870. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  13871. if( rc==SQLITE_OK ){
  13872. while( sqlite3_step(pExplain)==SQLITE_ROW ){
  13873. const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
  13874. int iEqpId = sqlite3_column_int(pExplain, 0);
  13875. int iParentId = sqlite3_column_int(pExplain, 1);
  13876. if( zEQPLine==0 ) zEQPLine = "";
  13877. if( zEQPLine[0]=='-' ) eqp_render(pArg);
  13878. eqp_append(pArg, iEqpId, iParentId, zEQPLine);
  13879. }
  13880. eqp_render(pArg);
  13881. }
  13882. sqlite3_finalize(pExplain);
  13883. sqlite3_free(zEQP);
  13884. if( pArg->autoEQP>=AUTOEQP_full ){
  13885. /* Also do an EXPLAIN for ".eqp full" mode */
  13886. zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
  13887. shell_check_oom(zEQP);
  13888. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  13889. if( rc==SQLITE_OK ){
  13890. pArg->cMode = MODE_Explain;
  13891. explain_data_prepare(pArg, pExplain);
  13892. exec_prepared_stmt(pArg, pExplain);
  13893. explain_data_delete(pArg);
  13894. }
  13895. sqlite3_finalize(pExplain);
  13896. sqlite3_free(zEQP);
  13897. }
  13898. if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
  13899. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
  13900. /* Reprepare pStmt before reactiving trace modes */
  13901. sqlite3_finalize(pStmt);
  13902. sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  13903. if( pArg ) pArg->pStmt = pStmt;
  13904. }
  13905. restore_debug_trace_modes();
  13906. }
  13907. if( pArg ){
  13908. pArg->cMode = pArg->mode;
  13909. if( pArg->autoExplain ){
  13910. if( sqlite3_stmt_isexplain(pStmt)==1 ){
  13911. pArg->cMode = MODE_Explain;
  13912. }
  13913. if( sqlite3_stmt_isexplain(pStmt)==2 ){
  13914. pArg->cMode = MODE_EQP;
  13915. }
  13916. }
  13917. /* If the shell is currently in ".explain" mode, gather the extra
  13918. ** data required to add indents to the output.*/
  13919. if( pArg->cMode==MODE_Explain ){
  13920. explain_data_prepare(pArg, pStmt);
  13921. }
  13922. }
  13923. bind_prepared_stmt(pArg, pStmt);
  13924. exec_prepared_stmt(pArg, pStmt);
  13925. explain_data_delete(pArg);
  13926. eqp_render(pArg);
  13927. /* print usage stats if stats on */
  13928. if( pArg && pArg->statsOn ){
  13929. display_stats(db, pArg, 0);
  13930. }
  13931. /* print loop-counters if required */
  13932. if( pArg && pArg->scanstatsOn ){
  13933. display_scanstats(db, pArg);
  13934. }
  13935. /* Finalize the statement just executed. If this fails, save a
  13936. ** copy of the error message. Otherwise, set zSql to point to the
  13937. ** next statement to execute. */
  13938. rc2 = sqlite3_finalize(pStmt);
  13939. if( rc!=SQLITE_NOMEM ) rc = rc2;
  13940. if( rc==SQLITE_OK ){
  13941. zSql = zLeftover;
  13942. while( IsSpace(zSql[0]) ) zSql++;
  13943. }else if( pzErrMsg ){
  13944. *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
  13945. }
  13946. /* clear saved stmt handle */
  13947. if( pArg ){
  13948. pArg->pStmt = NULL;
  13949. }
  13950. }
  13951. } /* end while */
  13952. return rc;
  13953. }
  13954. /*
  13955. ** Release memory previously allocated by tableColumnList().
  13956. */
  13957. static void freeColumnList(char **azCol){
  13958. int i;
  13959. for(i=1; azCol[i]; i++){
  13960. sqlite3_free(azCol[i]);
  13961. }
  13962. /* azCol[0] is a static string */
  13963. sqlite3_free(azCol);
  13964. }
  13965. /*
  13966. ** Return a list of pointers to strings which are the names of all
  13967. ** columns in table zTab. The memory to hold the names is dynamically
  13968. ** allocated and must be released by the caller using a subsequent call
  13969. ** to freeColumnList().
  13970. **
  13971. ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
  13972. ** value that needs to be preserved, then azCol[0] is filled in with the
  13973. ** name of the rowid column.
  13974. **
  13975. ** The first regular column in the table is azCol[1]. The list is terminated
  13976. ** by an entry with azCol[i]==0.
  13977. */
  13978. static char **tableColumnList(ShellState *p, const char *zTab){
  13979. char **azCol = 0;
  13980. sqlite3_stmt *pStmt;
  13981. char *zSql;
  13982. int nCol = 0;
  13983. int nAlloc = 0;
  13984. int nPK = 0; /* Number of PRIMARY KEY columns seen */
  13985. int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
  13986. int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
  13987. int rc;
  13988. zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
  13989. shell_check_oom(zSql);
  13990. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  13991. sqlite3_free(zSql);
  13992. if( rc ) return 0;
  13993. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  13994. if( nCol>=nAlloc-2 ){
  13995. nAlloc = nAlloc*2 + nCol + 10;
  13996. azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
  13997. shell_check_oom(azCol);
  13998. }
  13999. azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
  14000. shell_check_oom(azCol[nCol]);
  14001. if( sqlite3_column_int(pStmt, 5) ){
  14002. nPK++;
  14003. if( nPK==1
  14004. && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
  14005. "INTEGER")==0
  14006. ){
  14007. isIPK = 1;
  14008. }else{
  14009. isIPK = 0;
  14010. }
  14011. }
  14012. }
  14013. sqlite3_finalize(pStmt);
  14014. if( azCol==0 ) return 0;
  14015. azCol[0] = 0;
  14016. azCol[nCol+1] = 0;
  14017. /* The decision of whether or not a rowid really needs to be preserved
  14018. ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
  14019. ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
  14020. ** rowids on tables where the rowid is inaccessible because there are other
  14021. ** columns in the table named "rowid", "_rowid_", and "oid".
  14022. */
  14023. if( preserveRowid && isIPK ){
  14024. /* If a single PRIMARY KEY column with type INTEGER was seen, then it
  14025. ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
  14026. ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
  14027. ** ROWID aliases. To distinguish these cases, check to see if
  14028. ** there is a "pk" entry in "PRAGMA index_list". There will be
  14029. ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
  14030. */
  14031. zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
  14032. " WHERE origin='pk'", zTab);
  14033. shell_check_oom(zSql);
  14034. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  14035. sqlite3_free(zSql);
  14036. if( rc ){
  14037. freeColumnList(azCol);
  14038. return 0;
  14039. }
  14040. rc = sqlite3_step(pStmt);
  14041. sqlite3_finalize(pStmt);
  14042. preserveRowid = rc==SQLITE_ROW;
  14043. }
  14044. if( preserveRowid ){
  14045. /* Only preserve the rowid if we can find a name to use for the
  14046. ** rowid */
  14047. static char *azRowid[] = { "rowid", "_rowid_", "oid" };
  14048. int i, j;
  14049. for(j=0; j<3; j++){
  14050. for(i=1; i<=nCol; i++){
  14051. if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
  14052. }
  14053. if( i>nCol ){
  14054. /* At this point, we know that azRowid[j] is not the name of any
  14055. ** ordinary column in the table. Verify that azRowid[j] is a valid
  14056. ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
  14057. ** tables will fail this last check */
  14058. rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
  14059. if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
  14060. break;
  14061. }
  14062. }
  14063. }
  14064. return azCol;
  14065. }
  14066. /*
  14067. ** Toggle the reverse_unordered_selects setting.
  14068. */
  14069. static void toggleSelectOrder(sqlite3 *db){
  14070. sqlite3_stmt *pStmt = 0;
  14071. int iSetting = 0;
  14072. char zStmt[100];
  14073. sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
  14074. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  14075. iSetting = sqlite3_column_int(pStmt, 0);
  14076. }
  14077. sqlite3_finalize(pStmt);
  14078. sqlite3_snprintf(sizeof(zStmt), zStmt,
  14079. "PRAGMA reverse_unordered_selects(%d)", !iSetting);
  14080. sqlite3_exec(db, zStmt, 0, 0, 0);
  14081. }
  14082. /*
  14083. ** This is a different callback routine used for dumping the database.
  14084. ** Each row received by this callback consists of a table name,
  14085. ** the table type ("index" or "table") and SQL to create the table.
  14086. ** This routine should print text sufficient to recreate the table.
  14087. */
  14088. static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
  14089. int rc;
  14090. const char *zTable;
  14091. const char *zType;
  14092. const char *zSql;
  14093. ShellState *p = (ShellState *)pArg;
  14094. int dataOnly;
  14095. int noSys;
  14096. UNUSED_PARAMETER(azNotUsed);
  14097. if( nArg!=3 || azArg==0 ) return 0;
  14098. zTable = azArg[0];
  14099. zType = azArg[1];
  14100. zSql = azArg[2];
  14101. dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
  14102. noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
  14103. if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
  14104. if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
  14105. }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
  14106. if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
  14107. }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  14108. return 0;
  14109. }else if( dataOnly ){
  14110. /* no-op */
  14111. }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  14112. char *zIns;
  14113. if( !p->writableSchema ){
  14114. raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
  14115. p->writableSchema = 1;
  14116. }
  14117. zIns = sqlite3_mprintf(
  14118. "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
  14119. "VALUES('table','%q','%q',0,'%q');",
  14120. zTable, zTable, zSql);
  14121. shell_check_oom(zIns);
  14122. utf8_printf(p->out, "%s\n", zIns);
  14123. sqlite3_free(zIns);
  14124. return 0;
  14125. }else{
  14126. printSchemaLine(p->out, zSql, ";\n");
  14127. }
  14128. if( strcmp(zType, "table")==0 ){
  14129. ShellText sSelect;
  14130. ShellText sTable;
  14131. char **azCol;
  14132. int i;
  14133. char *savedDestTable;
  14134. int savedMode;
  14135. azCol = tableColumnList(p, zTable);
  14136. if( azCol==0 ){
  14137. p->nErr++;
  14138. return 0;
  14139. }
  14140. /* Always quote the table name, even if it appears to be pure ascii,
  14141. ** in case it is a keyword. Ex: INSERT INTO "table" ... */
  14142. initText(&sTable);
  14143. appendText(&sTable, zTable, quoteChar(zTable));
  14144. /* If preserving the rowid, add a column list after the table name.
  14145. ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
  14146. ** instead of the usual "INSERT INTO tab VALUES(...)".
  14147. */
  14148. if( azCol[0] ){
  14149. appendText(&sTable, "(", 0);
  14150. appendText(&sTable, azCol[0], 0);
  14151. for(i=1; azCol[i]; i++){
  14152. appendText(&sTable, ",", 0);
  14153. appendText(&sTable, azCol[i], quoteChar(azCol[i]));
  14154. }
  14155. appendText(&sTable, ")", 0);
  14156. }
  14157. /* Build an appropriate SELECT statement */
  14158. initText(&sSelect);
  14159. appendText(&sSelect, "SELECT ", 0);
  14160. if( azCol[0] ){
  14161. appendText(&sSelect, azCol[0], 0);
  14162. appendText(&sSelect, ",", 0);
  14163. }
  14164. for(i=1; azCol[i]; i++){
  14165. appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
  14166. if( azCol[i+1] ){
  14167. appendText(&sSelect, ",", 0);
  14168. }
  14169. }
  14170. freeColumnList(azCol);
  14171. appendText(&sSelect, " FROM ", 0);
  14172. appendText(&sSelect, zTable, quoteChar(zTable));
  14173. savedDestTable = p->zDestTable;
  14174. savedMode = p->mode;
  14175. p->zDestTable = sTable.z;
  14176. p->mode = p->cMode = MODE_Insert;
  14177. rc = shell_exec(p, sSelect.z, 0);
  14178. if( (rc&0xff)==SQLITE_CORRUPT ){
  14179. raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  14180. toggleSelectOrder(p->db);
  14181. shell_exec(p, sSelect.z, 0);
  14182. toggleSelectOrder(p->db);
  14183. }
  14184. p->zDestTable = savedDestTable;
  14185. p->mode = savedMode;
  14186. freeText(&sTable);
  14187. freeText(&sSelect);
  14188. if( rc ) p->nErr++;
  14189. }
  14190. return 0;
  14191. }
  14192. /*
  14193. ** Run zQuery. Use dump_callback() as the callback routine so that
  14194. ** the contents of the query are output as SQL statements.
  14195. **
  14196. ** If we get a SQLITE_CORRUPT error, rerun the query after appending
  14197. ** "ORDER BY rowid DESC" to the end.
  14198. */
  14199. static int run_schema_dump_query(
  14200. ShellState *p,
  14201. const char *zQuery
  14202. ){
  14203. int rc;
  14204. char *zErr = 0;
  14205. rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
  14206. if( rc==SQLITE_CORRUPT ){
  14207. char *zQ2;
  14208. int len = strlen30(zQuery);
  14209. raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  14210. if( zErr ){
  14211. utf8_printf(p->out, "/****** %s ******/\n", zErr);
  14212. sqlite3_free(zErr);
  14213. zErr = 0;
  14214. }
  14215. zQ2 = malloc( len+100 );
  14216. if( zQ2==0 ) return rc;
  14217. sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
  14218. rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
  14219. if( rc ){
  14220. utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
  14221. }else{
  14222. rc = SQLITE_CORRUPT;
  14223. }
  14224. sqlite3_free(zErr);
  14225. free(zQ2);
  14226. }
  14227. return rc;
  14228. }
  14229. /*
  14230. ** Text of help messages.
  14231. **
  14232. ** The help text for each individual command begins with a line that starts
  14233. ** with ".". Subsequent lines are supplimental information.
  14234. **
  14235. ** There must be two or more spaces between the end of the command and the
  14236. ** start of the description of what that command does.
  14237. */
  14238. static const char *(azHelp[]) = {
  14239. #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
  14240. ".archive ... Manage SQL archives",
  14241. " Each command must have exactly one of the following options:",
  14242. " -c, --create Create a new archive",
  14243. " -u, --update Add or update files with changed mtime",
  14244. " -i, --insert Like -u but always add even if unchanged",
  14245. " -r, --remove Remove files from archive",
  14246. " -t, --list List contents of archive",
  14247. " -x, --extract Extract files from archive",
  14248. " Optional arguments:",
  14249. " -v, --verbose Print each filename as it is processed",
  14250. " -f FILE, --file FILE Use archive FILE (default is current db)",
  14251. " -a FILE, --append FILE Open FILE using the apndvfs VFS",
  14252. " -C DIR, --directory DIR Read/extract files from directory DIR",
  14253. " -g, --glob Use glob matching for names in archive",
  14254. " -n, --dryrun Show the SQL that would have occurred",
  14255. " Examples:",
  14256. " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
  14257. " .ar -tf ARCHIVE # List members of ARCHIVE",
  14258. " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
  14259. " See also:",
  14260. " http://sqlite.org/cli.html#sqlite_archive_support",
  14261. #endif
  14262. #ifndef SQLITE_OMIT_AUTHORIZATION
  14263. ".auth ON|OFF Show authorizer callbacks",
  14264. #endif
  14265. ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
  14266. " Options:",
  14267. " --append Use the appendvfs",
  14268. " --async Write to FILE without journal and fsync()",
  14269. ".bail on|off Stop after hitting an error. Default OFF",
  14270. ".binary on|off Turn binary output on or off. Default OFF",
  14271. ".cd DIRECTORY Change the working directory to DIRECTORY",
  14272. ".changes on|off Show number of rows changed by SQL",
  14273. ".check GLOB Fail if output since .testcase does not match",
  14274. ".clone NEWDB Clone data into NEWDB from the existing database",
  14275. ".connection [close] [#] Open or close an auxiliary database connection",
  14276. ".databases List names and files of attached databases",
  14277. ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
  14278. ".dbinfo ?DB? Show status information about the database",
  14279. ".dump ?OBJECTS? Render database content as SQL",
  14280. " Options:",
  14281. " --data-only Output only INSERT statements",
  14282. " --newlines Allow unescaped newline characters in output",
  14283. " --nosys Omit system tables (ex: \"sqlite_stat1\")",
  14284. " --preserve-rowids Include ROWID values in the output",
  14285. " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
  14286. " Additional LIKE patterns can be given in subsequent arguments",
  14287. ".echo on|off Turn command echo on or off",
  14288. ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
  14289. " Other Modes:",
  14290. #ifdef SQLITE_DEBUG
  14291. " test Show raw EXPLAIN QUERY PLAN output",
  14292. " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
  14293. #endif
  14294. " trigger Like \"full\" but also show trigger bytecode",
  14295. ".excel Display the output of next command in spreadsheet",
  14296. " --bom Put a UTF8 byte-order mark on intermediate file",
  14297. ".exit ?CODE? Exit this program with return-code CODE",
  14298. ".expert EXPERIMENTAL. Suggest indexes for queries",
  14299. ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
  14300. ".filectrl CMD ... Run various sqlite3_file_control() operations",
  14301. " --schema SCHEMA Use SCHEMA instead of \"main\"",
  14302. " --help Show CMD details",
  14303. ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
  14304. ".headers on|off Turn display of headers on or off",
  14305. ".help ?-all? ?PATTERN? Show help text for PATTERN",
  14306. ".import FILE TABLE Import data from FILE into TABLE",
  14307. " Options:",
  14308. " --ascii Use \\037 and \\036 as column and row separators",
  14309. " --csv Use , and \\n as column and row separators",
  14310. " --skip N Skip the first N rows of input",
  14311. " --schema S Target table to be S.TABLE",
  14312. " -v \"Verbose\" - increase auxiliary output",
  14313. " Notes:",
  14314. " * If TABLE does not exist, it is created. The first row of input",
  14315. " determines the column names.",
  14316. " * If neither --csv or --ascii are used, the input mode is derived",
  14317. " from the \".mode\" output mode",
  14318. " * If FILE begins with \"|\" then it is a command that generates the",
  14319. " input text.",
  14320. #ifndef SQLITE_OMIT_TEST_CONTROL
  14321. ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
  14322. #endif
  14323. ".indexes ?TABLE? Show names of indexes",
  14324. " If TABLE is specified, only show indexes for",
  14325. " tables matching TABLE using the LIKE operator.",
  14326. #ifdef SQLITE_ENABLE_IOTRACE
  14327. ".iotrace FILE Enable I/O diagnostic logging to FILE",
  14328. #endif
  14329. ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
  14330. ".lint OPTIONS Report potential schema issues.",
  14331. " Options:",
  14332. " fkey-indexes Find missing foreign key indexes",
  14333. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  14334. ".load FILE ?ENTRY? Load an extension library",
  14335. #endif
  14336. ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
  14337. ".mode MODE ?OPTIONS? Set output mode",
  14338. " MODE is one of:",
  14339. " ascii Columns/rows delimited by 0x1F and 0x1E",
  14340. " box Tables using unicode box-drawing characters",
  14341. " csv Comma-separated values",
  14342. " column Output in columns. (See .width)",
  14343. " html HTML <table> code",
  14344. " insert SQL insert statements for TABLE",
  14345. " json Results in a JSON array",
  14346. " line One value per line",
  14347. " list Values delimited by \"|\"",
  14348. " markdown Markdown table format",
  14349. " qbox Shorthand for \"box --width 60 --quote\"",
  14350. " quote Escape answers as for SQL",
  14351. " table ASCII-art table",
  14352. " tabs Tab-separated values",
  14353. " tcl TCL list elements",
  14354. " OPTIONS: (for columnar modes or insert mode):",
  14355. " --wrap N Wrap output lines to no longer than N characters",
  14356. " --wordwrap B Wrap or not at word boundaries per B (on/off)",
  14357. " --ww Shorthand for \"--wordwrap 1\"",
  14358. " --quote Quote output text as SQL literals",
  14359. " --noquote Do not quote output text",
  14360. " TABLE The name of SQL table used for \"insert\" mode",
  14361. ".nonce STRING Suspend safe mode for one command if nonce matches",
  14362. ".nullvalue STRING Use STRING in place of NULL values",
  14363. ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
  14364. " If FILE begins with '|' then open as a pipe",
  14365. " --bom Put a UTF8 byte-order mark at the beginning",
  14366. " -e Send output to the system text editor",
  14367. " -x Send output as CSV to a spreadsheet (same as \".excel\")",
  14368. ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
  14369. " Options:",
  14370. " --append Use appendvfs to append database to the end of FILE",
  14371. #ifndef SQLITE_OMIT_DESERIALIZE
  14372. " --deserialize Load into memory using sqlite3_deserialize()",
  14373. " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
  14374. " --maxsize N Maximum size for --hexdb or --deserialized database",
  14375. #endif
  14376. " --new Initialize FILE to an empty database",
  14377. " --nofollow Do not follow symbolic links",
  14378. " --readonly Open FILE readonly",
  14379. " --zip FILE is a ZIP archive",
  14380. ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
  14381. " If FILE begins with '|' then open it as a pipe.",
  14382. " Options:",
  14383. " --bom Prefix output with a UTF8 byte-order mark",
  14384. " -e Send output to the system text editor",
  14385. " -x Send output as CSV to a spreadsheet",
  14386. ".parameter CMD ... Manage SQL parameter bindings",
  14387. " clear Erase all bindings",
  14388. " init Initialize the TEMP table that holds bindings",
  14389. " list List the current parameter bindings",
  14390. " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
  14391. " PARAMETER should start with one of: $ : @ ?",
  14392. " unset PARAMETER Remove PARAMETER from the binding table",
  14393. ".print STRING... Print literal STRING",
  14394. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  14395. ".progress N Invoke progress handler after every N opcodes",
  14396. " --limit N Interrupt after N progress callbacks",
  14397. " --once Do no more than one progress interrupt",
  14398. " --quiet|-q No output except at interrupts",
  14399. " --reset Reset the count for each input and interrupt",
  14400. #endif
  14401. ".prompt MAIN CONTINUE Replace the standard prompts",
  14402. ".quit Exit this program",
  14403. ".read FILE Read input from FILE or command output",
  14404. " If FILE begins with \"|\", it is a command that generates the input.",
  14405. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
  14406. ".recover Recover as much data as possible from corrupt db.",
  14407. " --freelist-corrupt Assume the freelist is corrupt",
  14408. " --recovery-db NAME Store recovery metadata in database file NAME",
  14409. " --lost-and-found TABLE Alternative name for the lost-and-found table",
  14410. " --no-rowids Do not attempt to recover rowid values",
  14411. " that are not also INTEGER PRIMARY KEYs",
  14412. #endif
  14413. ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
  14414. ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)",
  14415. ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
  14416. ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
  14417. " Options:",
  14418. " --indent Try to pretty-print the schema",
  14419. " --nosys Omit objects whose names start with \"sqlite_\"",
  14420. ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
  14421. " Options:",
  14422. " --init Create a new SELFTEST table",
  14423. " -v Verbose output",
  14424. ".separator COL ?ROW? Change the column and row separators",
  14425. #if defined(SQLITE_ENABLE_SESSION)
  14426. ".session ?NAME? CMD ... Create or control sessions",
  14427. " Subcommands:",
  14428. " attach TABLE Attach TABLE",
  14429. " changeset FILE Write a changeset into FILE",
  14430. " close Close one session",
  14431. " enable ?BOOLEAN? Set or query the enable bit",
  14432. " filter GLOB... Reject tables matching GLOBs",
  14433. " indirect ?BOOLEAN? Mark or query the indirect status",
  14434. " isempty Query whether the session is empty",
  14435. " list List currently open session names",
  14436. " open DB NAME Open a new session on DB",
  14437. " patchset FILE Write a patchset into FILE",
  14438. " If ?NAME? is omitted, the first defined session is used.",
  14439. #endif
  14440. ".sha3sum ... Compute a SHA3 hash of database content",
  14441. " Options:",
  14442. " --schema Also hash the sqlite_schema table",
  14443. " --sha3-224 Use the sha3-224 algorithm",
  14444. " --sha3-256 Use the sha3-256 algorithm (default)",
  14445. " --sha3-384 Use the sha3-384 algorithm",
  14446. " --sha3-512 Use the sha3-512 algorithm",
  14447. " Any other argument is a LIKE pattern for tables to hash",
  14448. #ifndef SQLITE_NOHAVE_SYSTEM
  14449. ".shell CMD ARGS... Run CMD ARGS... in a system shell",
  14450. #endif
  14451. ".show Show the current values for various settings",
  14452. ".stats ?ARG? Show stats or turn stats on or off",
  14453. " off Turn off automatic stat display",
  14454. " on Turn on automatic stat display",
  14455. " stmt Show statement stats",
  14456. " vmstep Show the virtual machine step count only",
  14457. #ifndef SQLITE_NOHAVE_SYSTEM
  14458. ".system CMD ARGS... Run CMD ARGS... in a system shell",
  14459. #endif
  14460. ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
  14461. ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
  14462. ".testctrl CMD ... Run various sqlite3_test_control() operations",
  14463. " Run \".testctrl\" with no arguments for details",
  14464. ".timeout MS Try opening locked tables for MS milliseconds",
  14465. ".timer on|off Turn SQL timer on or off",
  14466. #ifndef SQLITE_OMIT_TRACE
  14467. ".trace ?OPTIONS? Output each SQL statement as it is run",
  14468. " FILE Send output to FILE",
  14469. " stdout Send output to stdout",
  14470. " stderr Send output to stderr",
  14471. " off Disable tracing",
  14472. " --expanded Expand query parameters",
  14473. #ifdef SQLITE_ENABLE_NORMALIZE
  14474. " --normalized Normal the SQL statements",
  14475. #endif
  14476. " --plain Show SQL as it is input",
  14477. " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
  14478. " --profile Profile statements (SQLITE_TRACE_PROFILE)",
  14479. " --row Trace each row (SQLITE_TRACE_ROW)",
  14480. " --close Trace connection close (SQLITE_TRACE_CLOSE)",
  14481. #endif /* SQLITE_OMIT_TRACE */
  14482. #ifdef SQLITE_DEBUG
  14483. ".unmodule NAME ... Unregister virtual table modules",
  14484. " --allexcept Unregister everything except those named",
  14485. #endif
  14486. ".vfsinfo ?AUX? Information about the top-level VFS",
  14487. ".vfslist List all available VFSes",
  14488. ".vfsname ?AUX? Print the name of the VFS stack",
  14489. ".width NUM1 NUM2 ... Set minimum column widths for columnar output",
  14490. " Negative values right-justify",
  14491. };
  14492. /*
  14493. ** Output help text.
  14494. **
  14495. ** zPattern describes the set of commands for which help text is provided.
  14496. ** If zPattern is NULL, then show all commands, but only give a one-line
  14497. ** description of each.
  14498. **
  14499. ** Return the number of matches.
  14500. */
  14501. static int showHelp(FILE *out, const char *zPattern){
  14502. int i = 0;
  14503. int j = 0;
  14504. int n = 0;
  14505. char *zPat;
  14506. if( zPattern==0
  14507. || zPattern[0]=='0'
  14508. || strcmp(zPattern,"-a")==0
  14509. || strcmp(zPattern,"-all")==0
  14510. || strcmp(zPattern,"--all")==0
  14511. ){
  14512. /* Show all commands, but only one line per command */
  14513. if( zPattern==0 ) zPattern = "";
  14514. for(i=0; i<ArraySize(azHelp); i++){
  14515. if( azHelp[i][0]=='.' || zPattern[0] ){
  14516. utf8_printf(out, "%s\n", azHelp[i]);
  14517. n++;
  14518. }
  14519. }
  14520. }else{
  14521. /* Look for commands that for which zPattern is an exact prefix */
  14522. zPat = sqlite3_mprintf(".%s*", zPattern);
  14523. shell_check_oom(zPat);
  14524. for(i=0; i<ArraySize(azHelp); i++){
  14525. if( sqlite3_strglob(zPat, azHelp[i])==0 ){
  14526. utf8_printf(out, "%s\n", azHelp[i]);
  14527. j = i+1;
  14528. n++;
  14529. }
  14530. }
  14531. sqlite3_free(zPat);
  14532. if( n ){
  14533. if( n==1 ){
  14534. /* when zPattern is a prefix of exactly one command, then include the
  14535. ** details of that command, which should begin at offset j */
  14536. while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
  14537. utf8_printf(out, "%s\n", azHelp[j]);
  14538. j++;
  14539. }
  14540. }
  14541. return n;
  14542. }
  14543. /* Look for commands that contain zPattern anywhere. Show the complete
  14544. ** text of all commands that match. */
  14545. zPat = sqlite3_mprintf("%%%s%%", zPattern);
  14546. shell_check_oom(zPat);
  14547. for(i=0; i<ArraySize(azHelp); i++){
  14548. if( azHelp[i][0]=='.' ) j = i;
  14549. if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
  14550. utf8_printf(out, "%s\n", azHelp[j]);
  14551. while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
  14552. j++;
  14553. utf8_printf(out, "%s\n", azHelp[j]);
  14554. }
  14555. i = j;
  14556. n++;
  14557. }
  14558. }
  14559. sqlite3_free(zPat);
  14560. }
  14561. return n;
  14562. }
  14563. /* Forward reference */
  14564. static int process_input(ShellState *p);
  14565. /*
  14566. ** Read the content of file zName into memory obtained from sqlite3_malloc64()
  14567. ** and return a pointer to the buffer. The caller is responsible for freeing
  14568. ** the memory.
  14569. **
  14570. ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
  14571. ** read.
  14572. **
  14573. ** For convenience, a nul-terminator byte is always appended to the data read
  14574. ** from the file before the buffer is returned. This byte is not included in
  14575. ** the final value of (*pnByte), if applicable.
  14576. **
  14577. ** NULL is returned if any error is encountered. The final value of *pnByte
  14578. ** is undefined in this case.
  14579. */
  14580. static char *readFile(const char *zName, int *pnByte){
  14581. FILE *in = fopen(zName, "rb");
  14582. long nIn;
  14583. size_t nRead;
  14584. char *pBuf;
  14585. if( in==0 ) return 0;
  14586. fseek(in, 0, SEEK_END);
  14587. nIn = ftell(in);
  14588. rewind(in);
  14589. pBuf = sqlite3_malloc64( nIn+1 );
  14590. if( pBuf==0 ){ fclose(in); return 0; }
  14591. nRead = fread(pBuf, nIn, 1, in);
  14592. fclose(in);
  14593. if( nRead!=1 ){
  14594. sqlite3_free(pBuf);
  14595. return 0;
  14596. }
  14597. pBuf[nIn] = 0;
  14598. if( pnByte ) *pnByte = nIn;
  14599. return pBuf;
  14600. }
  14601. #if defined(SQLITE_ENABLE_SESSION)
  14602. /*
  14603. ** Close a single OpenSession object and release all of its associated
  14604. ** resources.
  14605. */
  14606. static void session_close(OpenSession *pSession){
  14607. int i;
  14608. sqlite3session_delete(pSession->p);
  14609. sqlite3_free(pSession->zName);
  14610. for(i=0; i<pSession->nFilter; i++){
  14611. sqlite3_free(pSession->azFilter[i]);
  14612. }
  14613. sqlite3_free(pSession->azFilter);
  14614. memset(pSession, 0, sizeof(OpenSession));
  14615. }
  14616. #endif
  14617. /*
  14618. ** Close all OpenSession objects and release all associated resources.
  14619. */
  14620. #if defined(SQLITE_ENABLE_SESSION)
  14621. static void session_close_all(ShellState *p, int i){
  14622. int j;
  14623. struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
  14624. for(j=0; j<pAuxDb->nSession; j++){
  14625. session_close(&pAuxDb->aSession[j]);
  14626. }
  14627. pAuxDb->nSession = 0;
  14628. }
  14629. #else
  14630. # define session_close_all(X,Y)
  14631. #endif
  14632. /*
  14633. ** Implementation of the xFilter function for an open session. Omit
  14634. ** any tables named by ".session filter" but let all other table through.
  14635. */
  14636. #if defined(SQLITE_ENABLE_SESSION)
  14637. static int session_filter(void *pCtx, const char *zTab){
  14638. OpenSession *pSession = (OpenSession*)pCtx;
  14639. int i;
  14640. for(i=0; i<pSession->nFilter; i++){
  14641. if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
  14642. }
  14643. return 1;
  14644. }
  14645. #endif
  14646. /*
  14647. ** Try to deduce the type of file for zName based on its content. Return
  14648. ** one of the SHELL_OPEN_* constants.
  14649. **
  14650. ** If the file does not exist or is empty but its name looks like a ZIP
  14651. ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
  14652. ** Otherwise, assume an ordinary database regardless of the filename if
  14653. ** the type cannot be determined from content.
  14654. */
  14655. int deduceDatabaseType(const char *zName, int dfltZip){
  14656. FILE *f = fopen(zName, "rb");
  14657. size_t n;
  14658. int rc = SHELL_OPEN_UNSPEC;
  14659. char zBuf[100];
  14660. if( f==0 ){
  14661. if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
  14662. return SHELL_OPEN_ZIPFILE;
  14663. }else{
  14664. return SHELL_OPEN_NORMAL;
  14665. }
  14666. }
  14667. n = fread(zBuf, 16, 1, f);
  14668. if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
  14669. fclose(f);
  14670. return SHELL_OPEN_NORMAL;
  14671. }
  14672. fseek(f, -25, SEEK_END);
  14673. n = fread(zBuf, 25, 1, f);
  14674. if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
  14675. rc = SHELL_OPEN_APPENDVFS;
  14676. }else{
  14677. fseek(f, -22, SEEK_END);
  14678. n = fread(zBuf, 22, 1, f);
  14679. if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
  14680. && zBuf[3]==0x06 ){
  14681. rc = SHELL_OPEN_ZIPFILE;
  14682. }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
  14683. rc = SHELL_OPEN_ZIPFILE;
  14684. }
  14685. }
  14686. fclose(f);
  14687. return rc;
  14688. }
  14689. #ifndef SQLITE_OMIT_DESERIALIZE
  14690. /*
  14691. ** Reconstruct an in-memory database using the output from the "dbtotxt"
  14692. ** program. Read content from the file in p->aAuxDb[].zDbFilename.
  14693. ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
  14694. */
  14695. static unsigned char *readHexDb(ShellState *p, int *pnData){
  14696. unsigned char *a = 0;
  14697. int nLine;
  14698. int n = 0;
  14699. int pgsz = 0;
  14700. int iOffset = 0;
  14701. int j, k;
  14702. int rc;
  14703. FILE *in;
  14704. const char *zDbFilename = p->pAuxDb->zDbFilename;
  14705. unsigned int x[16];
  14706. char zLine[1000];
  14707. if( zDbFilename ){
  14708. in = fopen(zDbFilename, "r");
  14709. if( in==0 ){
  14710. utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
  14711. return 0;
  14712. }
  14713. nLine = 0;
  14714. }else{
  14715. in = p->in;
  14716. nLine = p->lineno;
  14717. if( in==0 ) in = stdin;
  14718. }
  14719. *pnData = 0;
  14720. nLine++;
  14721. if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
  14722. rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
  14723. if( rc!=2 ) goto readHexDb_error;
  14724. if( n<0 ) goto readHexDb_error;
  14725. if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
  14726. n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */
  14727. a = sqlite3_malloc( n ? n : 1 );
  14728. shell_check_oom(a);
  14729. memset(a, 0, n);
  14730. if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
  14731. utf8_printf(stderr, "invalid pagesize\n");
  14732. goto readHexDb_error;
  14733. }
  14734. for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
  14735. rc = sscanf(zLine, "| page %d offset %d", &j, &k);
  14736. if( rc==2 ){
  14737. iOffset = k;
  14738. continue;
  14739. }
  14740. if( strncmp(zLine, "| end ", 6)==0 ){
  14741. break;
  14742. }
  14743. rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
  14744. &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
  14745. &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
  14746. if( rc==17 ){
  14747. k = iOffset+j;
  14748. if( k+16<=n && k>=0 ){
  14749. int ii;
  14750. for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
  14751. }
  14752. }
  14753. }
  14754. *pnData = n;
  14755. if( in!=p->in ){
  14756. fclose(in);
  14757. }else{
  14758. p->lineno = nLine;
  14759. }
  14760. return a;
  14761. readHexDb_error:
  14762. if( in!=p->in ){
  14763. fclose(in);
  14764. }else{
  14765. while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
  14766. nLine++;
  14767. if(strncmp(zLine, "| end ", 6)==0 ) break;
  14768. }
  14769. p->lineno = nLine;
  14770. }
  14771. sqlite3_free(a);
  14772. utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
  14773. return 0;
  14774. }
  14775. #endif /* SQLITE_OMIT_DESERIALIZE */
  14776. /*
  14777. ** Scalar function "shell_int32". The first argument to this function
  14778. ** must be a blob. The second a non-negative integer. This function
  14779. ** reads and returns a 32-bit big-endian integer from byte
  14780. ** offset (4*<arg2>) of the blob.
  14781. */
  14782. static void shellInt32(
  14783. sqlite3_context *context,
  14784. int argc,
  14785. sqlite3_value **argv
  14786. ){
  14787. const unsigned char *pBlob;
  14788. int nBlob;
  14789. int iInt;
  14790. UNUSED_PARAMETER(argc);
  14791. nBlob = sqlite3_value_bytes(argv[0]);
  14792. pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
  14793. iInt = sqlite3_value_int(argv[1]);
  14794. if( iInt>=0 && (iInt+1)*4<=nBlob ){
  14795. const unsigned char *a = &pBlob[iInt*4];
  14796. sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
  14797. + ((sqlite3_int64)a[1]<<16)
  14798. + ((sqlite3_int64)a[2]<< 8)
  14799. + ((sqlite3_int64)a[3]<< 0);
  14800. sqlite3_result_int64(context, iVal);
  14801. }
  14802. }
  14803. /*
  14804. ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
  14805. ** using "..." with internal double-quote characters doubled.
  14806. */
  14807. static void shellIdQuote(
  14808. sqlite3_context *context,
  14809. int argc,
  14810. sqlite3_value **argv
  14811. ){
  14812. const char *zName = (const char*)sqlite3_value_text(argv[0]);
  14813. UNUSED_PARAMETER(argc);
  14814. if( zName ){
  14815. char *z = sqlite3_mprintf("\"%w\"", zName);
  14816. sqlite3_result_text(context, z, -1, sqlite3_free);
  14817. }
  14818. }
  14819. /*
  14820. ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
  14821. */
  14822. static void shellUSleepFunc(
  14823. sqlite3_context *context,
  14824. int argcUnused,
  14825. sqlite3_value **argv
  14826. ){
  14827. int sleep = sqlite3_value_int(argv[0]);
  14828. (void)argcUnused;
  14829. sqlite3_sleep(sleep/1000);
  14830. sqlite3_result_int(context, sleep);
  14831. }
  14832. /*
  14833. ** Scalar function "shell_escape_crnl" used by the .recover command.
  14834. ** The argument passed to this function is the output of built-in
  14835. ** function quote(). If the first character of the input is "'",
  14836. ** indicating that the value passed to quote() was a text value,
  14837. ** then this function searches the input for "\n" and "\r" characters
  14838. ** and adds a wrapper similar to the following:
  14839. **
  14840. ** replace(replace(<input>, '\n', char(10), '\r', char(13));
  14841. **
  14842. ** Or, if the first character of the input is not "'", then a copy
  14843. ** of the input is returned.
  14844. */
  14845. static void shellEscapeCrnl(
  14846. sqlite3_context *context,
  14847. int argc,
  14848. sqlite3_value **argv
  14849. ){
  14850. const char *zText = (const char*)sqlite3_value_text(argv[0]);
  14851. UNUSED_PARAMETER(argc);
  14852. if( zText && zText[0]=='\'' ){
  14853. int nText = sqlite3_value_bytes(argv[0]);
  14854. int i;
  14855. char zBuf1[20];
  14856. char zBuf2[20];
  14857. const char *zNL = 0;
  14858. const char *zCR = 0;
  14859. int nCR = 0;
  14860. int nNL = 0;
  14861. for(i=0; zText[i]; i++){
  14862. if( zNL==0 && zText[i]=='\n' ){
  14863. zNL = unused_string(zText, "\\n", "\\012", zBuf1);
  14864. nNL = (int)strlen(zNL);
  14865. }
  14866. if( zCR==0 && zText[i]=='\r' ){
  14867. zCR = unused_string(zText, "\\r", "\\015", zBuf2);
  14868. nCR = (int)strlen(zCR);
  14869. }
  14870. }
  14871. if( zNL || zCR ){
  14872. int iOut = 0;
  14873. i64 nMax = (nNL > nCR) ? nNL : nCR;
  14874. i64 nAlloc = nMax * nText + (nMax+64)*2;
  14875. char *zOut = (char*)sqlite3_malloc64(nAlloc);
  14876. if( zOut==0 ){
  14877. sqlite3_result_error_nomem(context);
  14878. return;
  14879. }
  14880. if( zNL && zCR ){
  14881. memcpy(&zOut[iOut], "replace(replace(", 16);
  14882. iOut += 16;
  14883. }else{
  14884. memcpy(&zOut[iOut], "replace(", 8);
  14885. iOut += 8;
  14886. }
  14887. for(i=0; zText[i]; i++){
  14888. if( zText[i]=='\n' ){
  14889. memcpy(&zOut[iOut], zNL, nNL);
  14890. iOut += nNL;
  14891. }else if( zText[i]=='\r' ){
  14892. memcpy(&zOut[iOut], zCR, nCR);
  14893. iOut += nCR;
  14894. }else{
  14895. zOut[iOut] = zText[i];
  14896. iOut++;
  14897. }
  14898. }
  14899. if( zNL ){
  14900. memcpy(&zOut[iOut], ",'", 2); iOut += 2;
  14901. memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
  14902. memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
  14903. }
  14904. if( zCR ){
  14905. memcpy(&zOut[iOut], ",'", 2); iOut += 2;
  14906. memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
  14907. memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
  14908. }
  14909. sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
  14910. sqlite3_free(zOut);
  14911. return;
  14912. }
  14913. }
  14914. sqlite3_result_value(context, argv[0]);
  14915. }
  14916. /* Flags for open_db().
  14917. **
  14918. ** The default behavior of open_db() is to exit(1) if the database fails to
  14919. ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
  14920. ** but still returns without calling exit.
  14921. **
  14922. ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
  14923. ** ZIP archive if the file does not exist or is empty and its name matches
  14924. ** the *.zip pattern.
  14925. */
  14926. #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
  14927. #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
  14928. /*
  14929. ** Make sure the database is open. If it is not, then open it. If
  14930. ** the database fails to open, print an error message and exit.
  14931. */
  14932. static void open_db(ShellState *p, int openFlags){
  14933. if( p->db==0 ){
  14934. const char *zDbFilename = p->pAuxDb->zDbFilename;
  14935. if( p->openMode==SHELL_OPEN_UNSPEC ){
  14936. if( zDbFilename==0 || zDbFilename[0]==0 ){
  14937. p->openMode = SHELL_OPEN_NORMAL;
  14938. }else{
  14939. p->openMode = (u8)deduceDatabaseType(zDbFilename,
  14940. (openFlags & OPEN_DB_ZIPFILE)!=0);
  14941. }
  14942. }
  14943. switch( p->openMode ){
  14944. case SHELL_OPEN_APPENDVFS: {
  14945. sqlite3_open_v2(zDbFilename, &p->db,
  14946. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
  14947. break;
  14948. }
  14949. case SHELL_OPEN_HEXDB:
  14950. case SHELL_OPEN_DESERIALIZE: {
  14951. sqlite3_open(0, &p->db);
  14952. break;
  14953. }
  14954. case SHELL_OPEN_ZIPFILE: {
  14955. sqlite3_open(":memory:", &p->db);
  14956. break;
  14957. }
  14958. case SHELL_OPEN_READONLY: {
  14959. sqlite3_open_v2(zDbFilename, &p->db,
  14960. SQLITE_OPEN_READONLY|p->openFlags, 0);
  14961. break;
  14962. }
  14963. case SHELL_OPEN_UNSPEC:
  14964. case SHELL_OPEN_NORMAL: {
  14965. sqlite3_open_v2(zDbFilename, &p->db,
  14966. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
  14967. break;
  14968. }
  14969. }
  14970. globalDb = p->db;
  14971. if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
  14972. utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
  14973. zDbFilename, sqlite3_errmsg(p->db));
  14974. if( openFlags & OPEN_DB_KEEPALIVE ){
  14975. sqlite3_open(":memory:", &p->db);
  14976. return;
  14977. }
  14978. exit(1);
  14979. }
  14980. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  14981. sqlite3_enable_load_extension(p->db, 1);
  14982. #endif
  14983. sqlite3_fileio_init(p->db, 0, 0);
  14984. sqlite3_shathree_init(p->db, 0, 0);
  14985. sqlite3_completion_init(p->db, 0, 0);
  14986. sqlite3_uint_init(p->db, 0, 0);
  14987. sqlite3_decimal_init(p->db, 0, 0);
  14988. sqlite3_regexp_init(p->db, 0, 0);
  14989. sqlite3_ieee_init(p->db, 0, 0);
  14990. sqlite3_series_init(p->db, 0, 0);
  14991. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
  14992. sqlite3_dbdata_init(p->db, 0, 0);
  14993. #endif
  14994. #ifdef SQLITE_HAVE_ZLIB
  14995. sqlite3_zipfile_init(p->db, 0, 0);
  14996. sqlite3_sqlar_init(p->db, 0, 0);
  14997. #endif
  14998. sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
  14999. shellAddSchemaName, 0, 0);
  15000. sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
  15001. shellModuleSchema, 0, 0);
  15002. sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
  15003. shellPutsFunc, 0, 0);
  15004. sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
  15005. shellEscapeCrnl, 0, 0);
  15006. sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
  15007. shellInt32, 0, 0);
  15008. sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
  15009. shellIdQuote, 0, 0);
  15010. sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
  15011. shellUSleepFunc, 0, 0);
  15012. #ifndef SQLITE_NOHAVE_SYSTEM
  15013. sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
  15014. editFunc, 0, 0);
  15015. sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
  15016. editFunc, 0, 0);
  15017. #endif
  15018. if( p->openMode==SHELL_OPEN_ZIPFILE ){
  15019. char *zSql = sqlite3_mprintf(
  15020. "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
  15021. shell_check_oom(zSql);
  15022. sqlite3_exec(p->db, zSql, 0, 0, 0);
  15023. sqlite3_free(zSql);
  15024. }
  15025. #ifndef SQLITE_OMIT_DESERIALIZE
  15026. else
  15027. if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
  15028. int rc;
  15029. int nData = 0;
  15030. unsigned char *aData;
  15031. if( p->openMode==SHELL_OPEN_DESERIALIZE ){
  15032. aData = (unsigned char*)readFile(zDbFilename, &nData);
  15033. }else{
  15034. aData = readHexDb(p, &nData);
  15035. if( aData==0 ){
  15036. return;
  15037. }
  15038. }
  15039. rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
  15040. SQLITE_DESERIALIZE_RESIZEABLE |
  15041. SQLITE_DESERIALIZE_FREEONCLOSE);
  15042. if( rc ){
  15043. utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
  15044. }
  15045. if( p->szMax>0 ){
  15046. sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
  15047. }
  15048. }
  15049. #endif
  15050. }
  15051. if( p->bSafeModePersist && p->db!=0 ){
  15052. sqlite3_set_authorizer(p->db, safeModeAuth, p);
  15053. }
  15054. }
  15055. /*
  15056. ** Attempt to close the databaes connection. Report errors.
  15057. */
  15058. void close_db(sqlite3 *db){
  15059. int rc = sqlite3_close(db);
  15060. if( rc ){
  15061. utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
  15062. rc, sqlite3_errmsg(db));
  15063. }
  15064. }
  15065. #if HAVE_READLINE || HAVE_EDITLINE
  15066. /*
  15067. ** Readline completion callbacks
  15068. */
  15069. static char *readline_completion_generator(const char *text, int state){
  15070. static sqlite3_stmt *pStmt = 0;
  15071. char *zRet;
  15072. if( state==0 ){
  15073. char *zSql;
  15074. sqlite3_finalize(pStmt);
  15075. zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
  15076. " FROM completion(%Q) ORDER BY 1", text);
  15077. shell_check_oom(zSql);
  15078. sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
  15079. sqlite3_free(zSql);
  15080. }
  15081. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  15082. const char *z = (const char*)sqlite3_column_text(pStmt,0);
  15083. zRet = z ? strdup(z) : 0;
  15084. }else{
  15085. sqlite3_finalize(pStmt);
  15086. pStmt = 0;
  15087. zRet = 0;
  15088. }
  15089. return zRet;
  15090. }
  15091. static char **readline_completion(const char *zText, int iStart, int iEnd){
  15092. rl_attempted_completion_over = 1;
  15093. return rl_completion_matches(zText, readline_completion_generator);
  15094. }
  15095. #elif HAVE_LINENOISE
  15096. /*
  15097. ** Linenoise completion callback
  15098. */
  15099. static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
  15100. int nLine = strlen30(zLine);
  15101. int i, iStart;
  15102. sqlite3_stmt *pStmt = 0;
  15103. char *zSql;
  15104. char zBuf[1000];
  15105. if( nLine>sizeof(zBuf)-30 ) return;
  15106. if( zLine[0]=='.' || zLine[0]=='#') return;
  15107. for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
  15108. if( i==nLine-1 ) return;
  15109. iStart = i+1;
  15110. memcpy(zBuf, zLine, iStart);
  15111. zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
  15112. " FROM completion(%Q,%Q) ORDER BY 1",
  15113. &zLine[iStart], zLine);
  15114. shell_check_oom(zSql);
  15115. sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
  15116. sqlite3_free(zSql);
  15117. sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
  15118. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  15119. const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
  15120. int nCompletion = sqlite3_column_bytes(pStmt, 0);
  15121. if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
  15122. memcpy(zBuf+iStart, zCompletion, nCompletion+1);
  15123. linenoiseAddCompletion(lc, zBuf);
  15124. }
  15125. }
  15126. sqlite3_finalize(pStmt);
  15127. }
  15128. #endif
  15129. /*
  15130. ** Do C-language style dequoting.
  15131. **
  15132. ** \a -> alarm
  15133. ** \b -> backspace
  15134. ** \t -> tab
  15135. ** \n -> newline
  15136. ** \v -> vertical tab
  15137. ** \f -> form feed
  15138. ** \r -> carriage return
  15139. ** \s -> space
  15140. ** \" -> "
  15141. ** \' -> '
  15142. ** \\ -> backslash
  15143. ** \NNN -> ascii character NNN in octal
  15144. */
  15145. static void resolve_backslashes(char *z){
  15146. int i, j;
  15147. char c;
  15148. while( *z && *z!='\\' ) z++;
  15149. for(i=j=0; (c = z[i])!=0; i++, j++){
  15150. if( c=='\\' && z[i+1]!=0 ){
  15151. c = z[++i];
  15152. if( c=='a' ){
  15153. c = '\a';
  15154. }else if( c=='b' ){
  15155. c = '\b';
  15156. }else if( c=='t' ){
  15157. c = '\t';
  15158. }else if( c=='n' ){
  15159. c = '\n';
  15160. }else if( c=='v' ){
  15161. c = '\v';
  15162. }else if( c=='f' ){
  15163. c = '\f';
  15164. }else if( c=='r' ){
  15165. c = '\r';
  15166. }else if( c=='"' ){
  15167. c = '"';
  15168. }else if( c=='\'' ){
  15169. c = '\'';
  15170. }else if( c=='\\' ){
  15171. c = '\\';
  15172. }else if( c>='0' && c<='7' ){
  15173. c -= '0';
  15174. if( z[i+1]>='0' && z[i+1]<='7' ){
  15175. i++;
  15176. c = (c<<3) + z[i] - '0';
  15177. if( z[i+1]>='0' && z[i+1]<='7' ){
  15178. i++;
  15179. c = (c<<3) + z[i] - '0';
  15180. }
  15181. }
  15182. }
  15183. }
  15184. z[j] = c;
  15185. }
  15186. if( j<i ) z[j] = 0;
  15187. }
  15188. /*
  15189. ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
  15190. ** for TRUE and FALSE. Return the integer value if appropriate.
  15191. */
  15192. static int booleanValue(const char *zArg){
  15193. int i;
  15194. if( zArg[0]=='0' && zArg[1]=='x' ){
  15195. for(i=2; hexDigitValue(zArg[i])>=0; i++){}
  15196. }else{
  15197. for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
  15198. }
  15199. if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
  15200. if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
  15201. return 1;
  15202. }
  15203. if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
  15204. return 0;
  15205. }
  15206. utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
  15207. zArg);
  15208. return 0;
  15209. }
  15210. /*
  15211. ** Set or clear a shell flag according to a boolean value.
  15212. */
  15213. static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
  15214. if( booleanValue(zArg) ){
  15215. ShellSetFlag(p, mFlag);
  15216. }else{
  15217. ShellClearFlag(p, mFlag);
  15218. }
  15219. }
  15220. /*
  15221. ** Close an output file, assuming it is not stderr or stdout
  15222. */
  15223. static void output_file_close(FILE *f){
  15224. if( f && f!=stdout && f!=stderr ) fclose(f);
  15225. }
  15226. /*
  15227. ** Try to open an output file. The names "stdout" and "stderr" are
  15228. ** recognized and do the right thing. NULL is returned if the output
  15229. ** filename is "off".
  15230. */
  15231. static FILE *output_file_open(const char *zFile, int bTextMode){
  15232. FILE *f;
  15233. if( strcmp(zFile,"stdout")==0 ){
  15234. f = stdout;
  15235. }else if( strcmp(zFile, "stderr")==0 ){
  15236. f = stderr;
  15237. }else if( strcmp(zFile, "off")==0 ){
  15238. f = 0;
  15239. }else{
  15240. f = fopen(zFile, bTextMode ? "w" : "wb");
  15241. if( f==0 ){
  15242. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  15243. }
  15244. }
  15245. return f;
  15246. }
  15247. #ifndef SQLITE_OMIT_TRACE
  15248. /*
  15249. ** A routine for handling output from sqlite3_trace().
  15250. */
  15251. static int sql_trace_callback(
  15252. unsigned mType, /* The trace type */
  15253. void *pArg, /* The ShellState pointer */
  15254. void *pP, /* Usually a pointer to sqlite_stmt */
  15255. void *pX /* Auxiliary output */
  15256. ){
  15257. ShellState *p = (ShellState*)pArg;
  15258. sqlite3_stmt *pStmt;
  15259. const char *zSql;
  15260. int nSql;
  15261. if( p->traceOut==0 ) return 0;
  15262. if( mType==SQLITE_TRACE_CLOSE ){
  15263. utf8_printf(p->traceOut, "-- closing database connection\n");
  15264. return 0;
  15265. }
  15266. if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
  15267. zSql = (const char*)pX;
  15268. }else{
  15269. pStmt = (sqlite3_stmt*)pP;
  15270. switch( p->eTraceType ){
  15271. case SHELL_TRACE_EXPANDED: {
  15272. zSql = sqlite3_expanded_sql(pStmt);
  15273. break;
  15274. }
  15275. #ifdef SQLITE_ENABLE_NORMALIZE
  15276. case SHELL_TRACE_NORMALIZED: {
  15277. zSql = sqlite3_normalized_sql(pStmt);
  15278. break;
  15279. }
  15280. #endif
  15281. default: {
  15282. zSql = sqlite3_sql(pStmt);
  15283. break;
  15284. }
  15285. }
  15286. }
  15287. if( zSql==0 ) return 0;
  15288. nSql = strlen30(zSql);
  15289. while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
  15290. switch( mType ){
  15291. case SQLITE_TRACE_ROW:
  15292. case SQLITE_TRACE_STMT: {
  15293. utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
  15294. break;
  15295. }
  15296. case SQLITE_TRACE_PROFILE: {
  15297. sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
  15298. utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
  15299. break;
  15300. }
  15301. }
  15302. return 0;
  15303. }
  15304. #endif
  15305. /*
  15306. ** A no-op routine that runs with the ".breakpoint" doc-command. This is
  15307. ** a useful spot to set a debugger breakpoint.
  15308. */
  15309. static void test_breakpoint(void){
  15310. static int nCall = 0;
  15311. nCall++;
  15312. }
  15313. /*
  15314. ** An object used to read a CSV and other files for import.
  15315. */
  15316. typedef struct ImportCtx ImportCtx;
  15317. struct ImportCtx {
  15318. const char *zFile; /* Name of the input file */
  15319. FILE *in; /* Read the CSV text from this input stream */
  15320. int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */
  15321. char *z; /* Accumulated text for a field */
  15322. int n; /* Number of bytes in z */
  15323. int nAlloc; /* Space allocated for z[] */
  15324. int nLine; /* Current line number */
  15325. int nRow; /* Number of rows imported */
  15326. int nErr; /* Number of errors encountered */
  15327. int bNotFirst; /* True if one or more bytes already read */
  15328. int cTerm; /* Character that terminated the most recent field */
  15329. int cColSep; /* The column separator character. (Usually ",") */
  15330. int cRowSep; /* The row separator character. (Usually "\n") */
  15331. };
  15332. /* Clean up resourced used by an ImportCtx */
  15333. static void import_cleanup(ImportCtx *p){
  15334. if( p->in!=0 && p->xCloser!=0 ){
  15335. p->xCloser(p->in);
  15336. p->in = 0;
  15337. }
  15338. sqlite3_free(p->z);
  15339. p->z = 0;
  15340. }
  15341. /* Append a single byte to z[] */
  15342. static void import_append_char(ImportCtx *p, int c){
  15343. if( p->n+1>=p->nAlloc ){
  15344. p->nAlloc += p->nAlloc + 100;
  15345. p->z = sqlite3_realloc64(p->z, p->nAlloc);
  15346. shell_check_oom(p->z);
  15347. }
  15348. p->z[p->n++] = (char)c;
  15349. }
  15350. /* Read a single field of CSV text. Compatible with rfc4180 and extended
  15351. ** with the option of having a separator other than ",".
  15352. **
  15353. ** + Input comes from p->in.
  15354. ** + Store results in p->z of length p->n. Space to hold p->z comes
  15355. ** from sqlite3_malloc64().
  15356. ** + Use p->cSep as the column separator. The default is ",".
  15357. ** + Use p->rSep as the row separator. The default is "\n".
  15358. ** + Keep track of the line number in p->nLine.
  15359. ** + Store the character that terminates the field in p->cTerm. Store
  15360. ** EOF on end-of-file.
  15361. ** + Report syntax errors on stderr
  15362. */
  15363. static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
  15364. int c;
  15365. int cSep = p->cColSep;
  15366. int rSep = p->cRowSep;
  15367. p->n = 0;
  15368. c = fgetc(p->in);
  15369. if( c==EOF || seenInterrupt ){
  15370. p->cTerm = EOF;
  15371. return 0;
  15372. }
  15373. if( c=='"' ){
  15374. int pc, ppc;
  15375. int startLine = p->nLine;
  15376. int cQuote = c;
  15377. pc = ppc = 0;
  15378. while( 1 ){
  15379. c = fgetc(p->in);
  15380. if( c==rSep ) p->nLine++;
  15381. if( c==cQuote ){
  15382. if( pc==cQuote ){
  15383. pc = 0;
  15384. continue;
  15385. }
  15386. }
  15387. if( (c==cSep && pc==cQuote)
  15388. || (c==rSep && pc==cQuote)
  15389. || (c==rSep && pc=='\r' && ppc==cQuote)
  15390. || (c==EOF && pc==cQuote)
  15391. ){
  15392. do{ p->n--; }while( p->z[p->n]!=cQuote );
  15393. p->cTerm = c;
  15394. break;
  15395. }
  15396. if( pc==cQuote && c!='\r' ){
  15397. utf8_printf(stderr, "%s:%d: unescaped %c character\n",
  15398. p->zFile, p->nLine, cQuote);
  15399. }
  15400. if( c==EOF ){
  15401. utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
  15402. p->zFile, startLine, cQuote);
  15403. p->cTerm = c;
  15404. break;
  15405. }
  15406. import_append_char(p, c);
  15407. ppc = pc;
  15408. pc = c;
  15409. }
  15410. }else{
  15411. /* If this is the first field being parsed and it begins with the
  15412. ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
  15413. if( (c&0xff)==0xef && p->bNotFirst==0 ){
  15414. import_append_char(p, c);
  15415. c = fgetc(p->in);
  15416. if( (c&0xff)==0xbb ){
  15417. import_append_char(p, c);
  15418. c = fgetc(p->in);
  15419. if( (c&0xff)==0xbf ){
  15420. p->bNotFirst = 1;
  15421. p->n = 0;
  15422. return csv_read_one_field(p);
  15423. }
  15424. }
  15425. }
  15426. while( c!=EOF && c!=cSep && c!=rSep ){
  15427. import_append_char(p, c);
  15428. c = fgetc(p->in);
  15429. }
  15430. if( c==rSep ){
  15431. p->nLine++;
  15432. if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
  15433. }
  15434. p->cTerm = c;
  15435. }
  15436. if( p->z ) p->z[p->n] = 0;
  15437. p->bNotFirst = 1;
  15438. return p->z;
  15439. }
  15440. /* Read a single field of ASCII delimited text.
  15441. **
  15442. ** + Input comes from p->in.
  15443. ** + Store results in p->z of length p->n. Space to hold p->z comes
  15444. ** from sqlite3_malloc64().
  15445. ** + Use p->cSep as the column separator. The default is "\x1F".
  15446. ** + Use p->rSep as the row separator. The default is "\x1E".
  15447. ** + Keep track of the row number in p->nLine.
  15448. ** + Store the character that terminates the field in p->cTerm. Store
  15449. ** EOF on end-of-file.
  15450. ** + Report syntax errors on stderr
  15451. */
  15452. static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
  15453. int c;
  15454. int cSep = p->cColSep;
  15455. int rSep = p->cRowSep;
  15456. p->n = 0;
  15457. c = fgetc(p->in);
  15458. if( c==EOF || seenInterrupt ){
  15459. p->cTerm = EOF;
  15460. return 0;
  15461. }
  15462. while( c!=EOF && c!=cSep && c!=rSep ){
  15463. import_append_char(p, c);
  15464. c = fgetc(p->in);
  15465. }
  15466. if( c==rSep ){
  15467. p->nLine++;
  15468. }
  15469. p->cTerm = c;
  15470. if( p->z ) p->z[p->n] = 0;
  15471. return p->z;
  15472. }
  15473. /*
  15474. ** Try to transfer data for table zTable. If an error is seen while
  15475. ** moving forward, try to go backwards. The backwards movement won't
  15476. ** work for WITHOUT ROWID tables.
  15477. */
  15478. static void tryToCloneData(
  15479. ShellState *p,
  15480. sqlite3 *newDb,
  15481. const char *zTable
  15482. ){
  15483. sqlite3_stmt *pQuery = 0;
  15484. sqlite3_stmt *pInsert = 0;
  15485. char *zQuery = 0;
  15486. char *zInsert = 0;
  15487. int rc;
  15488. int i, j, n;
  15489. int nTable = strlen30(zTable);
  15490. int k = 0;
  15491. int cnt = 0;
  15492. const int spinRate = 10000;
  15493. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
  15494. shell_check_oom(zQuery);
  15495. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  15496. if( rc ){
  15497. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  15498. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  15499. zQuery);
  15500. goto end_data_xfer;
  15501. }
  15502. n = sqlite3_column_count(pQuery);
  15503. zInsert = sqlite3_malloc64(200 + nTable + n*3);
  15504. shell_check_oom(zInsert);
  15505. sqlite3_snprintf(200+nTable,zInsert,
  15506. "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
  15507. i = strlen30(zInsert);
  15508. for(j=1; j<n; j++){
  15509. memcpy(zInsert+i, ",?", 2);
  15510. i += 2;
  15511. }
  15512. memcpy(zInsert+i, ");", 3);
  15513. rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
  15514. if( rc ){
  15515. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  15516. sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
  15517. zQuery);
  15518. goto end_data_xfer;
  15519. }
  15520. for(k=0; k<2; k++){
  15521. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  15522. for(i=0; i<n; i++){
  15523. switch( sqlite3_column_type(pQuery, i) ){
  15524. case SQLITE_NULL: {
  15525. sqlite3_bind_null(pInsert, i+1);
  15526. break;
  15527. }
  15528. case SQLITE_INTEGER: {
  15529. sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
  15530. break;
  15531. }
  15532. case SQLITE_FLOAT: {
  15533. sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
  15534. break;
  15535. }
  15536. case SQLITE_TEXT: {
  15537. sqlite3_bind_text(pInsert, i+1,
  15538. (const char*)sqlite3_column_text(pQuery,i),
  15539. -1, SQLITE_STATIC);
  15540. break;
  15541. }
  15542. case SQLITE_BLOB: {
  15543. sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
  15544. sqlite3_column_bytes(pQuery,i),
  15545. SQLITE_STATIC);
  15546. break;
  15547. }
  15548. }
  15549. } /* End for */
  15550. rc = sqlite3_step(pInsert);
  15551. if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  15552. utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
  15553. sqlite3_errmsg(newDb));
  15554. }
  15555. sqlite3_reset(pInsert);
  15556. cnt++;
  15557. if( (cnt%spinRate)==0 ){
  15558. printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
  15559. fflush(stdout);
  15560. }
  15561. } /* End while */
  15562. if( rc==SQLITE_DONE ) break;
  15563. sqlite3_finalize(pQuery);
  15564. sqlite3_free(zQuery);
  15565. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
  15566. zTable);
  15567. shell_check_oom(zQuery);
  15568. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  15569. if( rc ){
  15570. utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
  15571. break;
  15572. }
  15573. } /* End for(k=0...) */
  15574. end_data_xfer:
  15575. sqlite3_finalize(pQuery);
  15576. sqlite3_finalize(pInsert);
  15577. sqlite3_free(zQuery);
  15578. sqlite3_free(zInsert);
  15579. }
  15580. /*
  15581. ** Try to transfer all rows of the schema that match zWhere. For
  15582. ** each row, invoke xForEach() on the object defined by that row.
  15583. ** If an error is encountered while moving forward through the
  15584. ** sqlite_schema table, try again moving backwards.
  15585. */
  15586. static void tryToCloneSchema(
  15587. ShellState *p,
  15588. sqlite3 *newDb,
  15589. const char *zWhere,
  15590. void (*xForEach)(ShellState*,sqlite3*,const char*)
  15591. ){
  15592. sqlite3_stmt *pQuery = 0;
  15593. char *zQuery = 0;
  15594. int rc;
  15595. const unsigned char *zName;
  15596. const unsigned char *zSql;
  15597. char *zErrMsg = 0;
  15598. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
  15599. " WHERE %s", zWhere);
  15600. shell_check_oom(zQuery);
  15601. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  15602. if( rc ){
  15603. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  15604. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  15605. zQuery);
  15606. goto end_schema_xfer;
  15607. }
  15608. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  15609. zName = sqlite3_column_text(pQuery, 0);
  15610. zSql = sqlite3_column_text(pQuery, 1);
  15611. if( zName==0 || zSql==0 ) continue;
  15612. printf("%s... ", zName); fflush(stdout);
  15613. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  15614. if( zErrMsg ){
  15615. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  15616. sqlite3_free(zErrMsg);
  15617. zErrMsg = 0;
  15618. }
  15619. if( xForEach ){
  15620. xForEach(p, newDb, (const char*)zName);
  15621. }
  15622. printf("done\n");
  15623. }
  15624. if( rc!=SQLITE_DONE ){
  15625. sqlite3_finalize(pQuery);
  15626. sqlite3_free(zQuery);
  15627. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
  15628. " WHERE %s ORDER BY rowid DESC", zWhere);
  15629. shell_check_oom(zQuery);
  15630. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  15631. if( rc ){
  15632. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  15633. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  15634. zQuery);
  15635. goto end_schema_xfer;
  15636. }
  15637. while( sqlite3_step(pQuery)==SQLITE_ROW ){
  15638. zName = sqlite3_column_text(pQuery, 0);
  15639. zSql = sqlite3_column_text(pQuery, 1);
  15640. if( zName==0 || zSql==0 ) continue;
  15641. printf("%s... ", zName); fflush(stdout);
  15642. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  15643. if( zErrMsg ){
  15644. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  15645. sqlite3_free(zErrMsg);
  15646. zErrMsg = 0;
  15647. }
  15648. if( xForEach ){
  15649. xForEach(p, newDb, (const char*)zName);
  15650. }
  15651. printf("done\n");
  15652. }
  15653. }
  15654. end_schema_xfer:
  15655. sqlite3_finalize(pQuery);
  15656. sqlite3_free(zQuery);
  15657. }
  15658. /*
  15659. ** Open a new database file named "zNewDb". Try to recover as much information
  15660. ** as possible out of the main database (which might be corrupt) and write it
  15661. ** into zNewDb.
  15662. */
  15663. static void tryToClone(ShellState *p, const char *zNewDb){
  15664. int rc;
  15665. sqlite3 *newDb = 0;
  15666. if( access(zNewDb,0)==0 ){
  15667. utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
  15668. return;
  15669. }
  15670. rc = sqlite3_open(zNewDb, &newDb);
  15671. if( rc ){
  15672. utf8_printf(stderr, "Cannot create output database: %s\n",
  15673. sqlite3_errmsg(newDb));
  15674. }else{
  15675. sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
  15676. sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
  15677. tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
  15678. tryToCloneSchema(p, newDb, "type!='table'", 0);
  15679. sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
  15680. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  15681. }
  15682. close_db(newDb);
  15683. }
  15684. /*
  15685. ** Change the output file back to stdout.
  15686. **
  15687. ** If the p->doXdgOpen flag is set, that means the output was being
  15688. ** redirected to a temporary file named by p->zTempFile. In that case,
  15689. ** launch start/open/xdg-open on that temporary file.
  15690. */
  15691. static void output_reset(ShellState *p){
  15692. if( p->outfile[0]=='|' ){
  15693. #ifndef SQLITE_OMIT_POPEN
  15694. pclose(p->out);
  15695. #endif
  15696. }else{
  15697. output_file_close(p->out);
  15698. #ifndef SQLITE_NOHAVE_SYSTEM
  15699. if( p->doXdgOpen ){
  15700. const char *zXdgOpenCmd =
  15701. #if defined(_WIN32)
  15702. "start";
  15703. #elif defined(__APPLE__)
  15704. "open";
  15705. #else
  15706. "xdg-open";
  15707. #endif
  15708. char *zCmd;
  15709. zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
  15710. if( system(zCmd) ){
  15711. utf8_printf(stderr, "Failed: [%s]\n", zCmd);
  15712. }else{
  15713. /* Give the start/open/xdg-open command some time to get
  15714. ** going before we continue, and potential delete the
  15715. ** p->zTempFile data file out from under it */
  15716. sqlite3_sleep(2000);
  15717. }
  15718. sqlite3_free(zCmd);
  15719. outputModePop(p);
  15720. p->doXdgOpen = 0;
  15721. }
  15722. #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
  15723. }
  15724. p->outfile[0] = 0;
  15725. p->out = stdout;
  15726. }
  15727. /*
  15728. ** Run an SQL command and return the single integer result.
  15729. */
  15730. static int db_int(sqlite3 *db, const char *zSql){
  15731. sqlite3_stmt *pStmt;
  15732. int res = 0;
  15733. sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  15734. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  15735. res = sqlite3_column_int(pStmt,0);
  15736. }
  15737. sqlite3_finalize(pStmt);
  15738. return res;
  15739. }
  15740. /*
  15741. ** Convert a 2-byte or 4-byte big-endian integer into a native integer
  15742. */
  15743. static unsigned int get2byteInt(unsigned char *a){
  15744. return (a[0]<<8) + a[1];
  15745. }
  15746. static unsigned int get4byteInt(unsigned char *a){
  15747. return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
  15748. }
  15749. /*
  15750. ** Implementation of the ".dbinfo" command.
  15751. **
  15752. ** Return 1 on error, 2 to exit, and 0 otherwise.
  15753. */
  15754. static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
  15755. static const struct { const char *zName; int ofst; } aField[] = {
  15756. { "file change counter:", 24 },
  15757. { "database page count:", 28 },
  15758. { "freelist page count:", 36 },
  15759. { "schema cookie:", 40 },
  15760. { "schema format:", 44 },
  15761. { "default cache size:", 48 },
  15762. { "autovacuum top root:", 52 },
  15763. { "incremental vacuum:", 64 },
  15764. { "text encoding:", 56 },
  15765. { "user version:", 60 },
  15766. { "application id:", 68 },
  15767. { "software version:", 96 },
  15768. };
  15769. static const struct { const char *zName; const char *zSql; } aQuery[] = {
  15770. { "number of tables:",
  15771. "SELECT count(*) FROM %s WHERE type='table'" },
  15772. { "number of indexes:",
  15773. "SELECT count(*) FROM %s WHERE type='index'" },
  15774. { "number of triggers:",
  15775. "SELECT count(*) FROM %s WHERE type='trigger'" },
  15776. { "number of views:",
  15777. "SELECT count(*) FROM %s WHERE type='view'" },
  15778. { "schema size:",
  15779. "SELECT total(length(sql)) FROM %s" },
  15780. };
  15781. int i, rc;
  15782. unsigned iDataVersion;
  15783. char *zSchemaTab;
  15784. char *zDb = nArg>=2 ? azArg[1] : "main";
  15785. sqlite3_stmt *pStmt = 0;
  15786. unsigned char aHdr[100];
  15787. open_db(p, 0);
  15788. if( p->db==0 ) return 1;
  15789. rc = sqlite3_prepare_v2(p->db,
  15790. "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
  15791. -1, &pStmt, 0);
  15792. if( rc ){
  15793. utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
  15794. sqlite3_finalize(pStmt);
  15795. return 1;
  15796. }
  15797. sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
  15798. if( sqlite3_step(pStmt)==SQLITE_ROW
  15799. && sqlite3_column_bytes(pStmt,0)>100
  15800. ){
  15801. memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
  15802. sqlite3_finalize(pStmt);
  15803. }else{
  15804. raw_printf(stderr, "unable to read database header\n");
  15805. sqlite3_finalize(pStmt);
  15806. return 1;
  15807. }
  15808. i = get2byteInt(aHdr+16);
  15809. if( i==1 ) i = 65536;
  15810. utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
  15811. utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
  15812. utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
  15813. utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
  15814. for(i=0; i<ArraySize(aField); i++){
  15815. int ofst = aField[i].ofst;
  15816. unsigned int val = get4byteInt(aHdr + ofst);
  15817. utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
  15818. switch( ofst ){
  15819. case 56: {
  15820. if( val==1 ) raw_printf(p->out, " (utf8)");
  15821. if( val==2 ) raw_printf(p->out, " (utf16le)");
  15822. if( val==3 ) raw_printf(p->out, " (utf16be)");
  15823. }
  15824. }
  15825. raw_printf(p->out, "\n");
  15826. }
  15827. if( zDb==0 ){
  15828. zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
  15829. }else if( strcmp(zDb,"temp")==0 ){
  15830. zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
  15831. }else{
  15832. zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
  15833. }
  15834. for(i=0; i<ArraySize(aQuery); i++){
  15835. char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
  15836. int val = db_int(p->db, zSql);
  15837. sqlite3_free(zSql);
  15838. utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
  15839. }
  15840. sqlite3_free(zSchemaTab);
  15841. sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
  15842. utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
  15843. return 0;
  15844. }
  15845. /*
  15846. ** Print the current sqlite3_errmsg() value to stderr and return 1.
  15847. */
  15848. static int shellDatabaseError(sqlite3 *db){
  15849. const char *zErr = sqlite3_errmsg(db);
  15850. utf8_printf(stderr, "Error: %s\n", zErr);
  15851. return 1;
  15852. }
  15853. /*
  15854. ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
  15855. ** if they match and FALSE (0) if they do not match.
  15856. **
  15857. ** Globbing rules:
  15858. **
  15859. ** '*' Matches any sequence of zero or more characters.
  15860. **
  15861. ** '?' Matches exactly one character.
  15862. **
  15863. ** [...] Matches one character from the enclosed list of
  15864. ** characters.
  15865. **
  15866. ** [^...] Matches one character not in the enclosed list.
  15867. **
  15868. ** '#' Matches any sequence of one or more digits with an
  15869. ** optional + or - sign in front
  15870. **
  15871. ** ' ' Any span of whitespace matches any other span of
  15872. ** whitespace.
  15873. **
  15874. ** Extra whitespace at the end of z[] is ignored.
  15875. */
  15876. static int testcase_glob(const char *zGlob, const char *z){
  15877. int c, c2;
  15878. int invert;
  15879. int seen;
  15880. while( (c = (*(zGlob++)))!=0 ){
  15881. if( IsSpace(c) ){
  15882. if( !IsSpace(*z) ) return 0;
  15883. while( IsSpace(*zGlob) ) zGlob++;
  15884. while( IsSpace(*z) ) z++;
  15885. }else if( c=='*' ){
  15886. while( (c=(*(zGlob++))) == '*' || c=='?' ){
  15887. if( c=='?' && (*(z++))==0 ) return 0;
  15888. }
  15889. if( c==0 ){
  15890. return 1;
  15891. }else if( c=='[' ){
  15892. while( *z && testcase_glob(zGlob-1,z)==0 ){
  15893. z++;
  15894. }
  15895. return (*z)!=0;
  15896. }
  15897. while( (c2 = (*(z++)))!=0 ){
  15898. while( c2!=c ){
  15899. c2 = *(z++);
  15900. if( c2==0 ) return 0;
  15901. }
  15902. if( testcase_glob(zGlob,z) ) return 1;
  15903. }
  15904. return 0;
  15905. }else if( c=='?' ){
  15906. if( (*(z++))==0 ) return 0;
  15907. }else if( c=='[' ){
  15908. int prior_c = 0;
  15909. seen = 0;
  15910. invert = 0;
  15911. c = *(z++);
  15912. if( c==0 ) return 0;
  15913. c2 = *(zGlob++);
  15914. if( c2=='^' ){
  15915. invert = 1;
  15916. c2 = *(zGlob++);
  15917. }
  15918. if( c2==']' ){
  15919. if( c==']' ) seen = 1;
  15920. c2 = *(zGlob++);
  15921. }
  15922. while( c2 && c2!=']' ){
  15923. if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
  15924. c2 = *(zGlob++);
  15925. if( c>=prior_c && c<=c2 ) seen = 1;
  15926. prior_c = 0;
  15927. }else{
  15928. if( c==c2 ){
  15929. seen = 1;
  15930. }
  15931. prior_c = c2;
  15932. }
  15933. c2 = *(zGlob++);
  15934. }
  15935. if( c2==0 || (seen ^ invert)==0 ) return 0;
  15936. }else if( c=='#' ){
  15937. if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
  15938. if( !IsDigit(z[0]) ) return 0;
  15939. z++;
  15940. while( IsDigit(z[0]) ){ z++; }
  15941. }else{
  15942. if( c!=(*(z++)) ) return 0;
  15943. }
  15944. }
  15945. while( IsSpace(*z) ){ z++; }
  15946. return *z==0;
  15947. }
  15948. /*
  15949. ** Compare the string as a command-line option with either one or two
  15950. ** initial "-" characters.
  15951. */
  15952. static int optionMatch(const char *zStr, const char *zOpt){
  15953. if( zStr[0]!='-' ) return 0;
  15954. zStr++;
  15955. if( zStr[0]=='-' ) zStr++;
  15956. return strcmp(zStr, zOpt)==0;
  15957. }
  15958. /*
  15959. ** Delete a file.
  15960. */
  15961. int shellDeleteFile(const char *zFilename){
  15962. int rc;
  15963. #ifdef _WIN32
  15964. wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
  15965. rc = _wunlink(z);
  15966. sqlite3_free(z);
  15967. #else
  15968. rc = unlink(zFilename);
  15969. #endif
  15970. return rc;
  15971. }
  15972. /*
  15973. ** Try to delete the temporary file (if there is one) and free the
  15974. ** memory used to hold the name of the temp file.
  15975. */
  15976. static void clearTempFile(ShellState *p){
  15977. if( p->zTempFile==0 ) return;
  15978. if( p->doXdgOpen ) return;
  15979. if( shellDeleteFile(p->zTempFile) ) return;
  15980. sqlite3_free(p->zTempFile);
  15981. p->zTempFile = 0;
  15982. }
  15983. /*
  15984. ** Create a new temp file name with the given suffix.
  15985. */
  15986. static void newTempFile(ShellState *p, const char *zSuffix){
  15987. clearTempFile(p);
  15988. sqlite3_free(p->zTempFile);
  15989. p->zTempFile = 0;
  15990. if( p->db ){
  15991. sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
  15992. }
  15993. if( p->zTempFile==0 ){
  15994. /* If p->db is an in-memory database then the TEMPFILENAME file-control
  15995. ** will not work and we will need to fallback to guessing */
  15996. char *zTemp;
  15997. sqlite3_uint64 r;
  15998. sqlite3_randomness(sizeof(r), &r);
  15999. zTemp = getenv("TEMP");
  16000. if( zTemp==0 ) zTemp = getenv("TMP");
  16001. if( zTemp==0 ){
  16002. #ifdef _WIN32
  16003. zTemp = "\\tmp";
  16004. #else
  16005. zTemp = "/tmp";
  16006. #endif
  16007. }
  16008. p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
  16009. }else{
  16010. p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
  16011. }
  16012. shell_check_oom(p->zTempFile);
  16013. }
  16014. /*
  16015. ** The implementation of SQL scalar function fkey_collate_clause(), used
  16016. ** by the ".lint fkey-indexes" command. This scalar function is always
  16017. ** called with four arguments - the parent table name, the parent column name,
  16018. ** the child table name and the child column name.
  16019. **
  16020. ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
  16021. **
  16022. ** If either of the named tables or columns do not exist, this function
  16023. ** returns an empty string. An empty string is also returned if both tables
  16024. ** and columns exist but have the same default collation sequence. Or,
  16025. ** if both exist but the default collation sequences are different, this
  16026. ** function returns the string " COLLATE <parent-collation>", where
  16027. ** <parent-collation> is the default collation sequence of the parent column.
  16028. */
  16029. static void shellFkeyCollateClause(
  16030. sqlite3_context *pCtx,
  16031. int nVal,
  16032. sqlite3_value **apVal
  16033. ){
  16034. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  16035. const char *zParent;
  16036. const char *zParentCol;
  16037. const char *zParentSeq;
  16038. const char *zChild;
  16039. const char *zChildCol;
  16040. const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
  16041. int rc;
  16042. assert( nVal==4 );
  16043. zParent = (const char*)sqlite3_value_text(apVal[0]);
  16044. zParentCol = (const char*)sqlite3_value_text(apVal[1]);
  16045. zChild = (const char*)sqlite3_value_text(apVal[2]);
  16046. zChildCol = (const char*)sqlite3_value_text(apVal[3]);
  16047. sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
  16048. rc = sqlite3_table_column_metadata(
  16049. db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
  16050. );
  16051. if( rc==SQLITE_OK ){
  16052. rc = sqlite3_table_column_metadata(
  16053. db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
  16054. );
  16055. }
  16056. if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
  16057. char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
  16058. sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
  16059. sqlite3_free(z);
  16060. }
  16061. }
  16062. /*
  16063. ** The implementation of dot-command ".lint fkey-indexes".
  16064. */
  16065. static int lintFkeyIndexes(
  16066. ShellState *pState, /* Current shell tool state */
  16067. char **azArg, /* Array of arguments passed to dot command */
  16068. int nArg /* Number of entries in azArg[] */
  16069. ){
  16070. sqlite3 *db = pState->db; /* Database handle to query "main" db of */
  16071. FILE *out = pState->out; /* Stream to write non-error output to */
  16072. int bVerbose = 0; /* If -verbose is present */
  16073. int bGroupByParent = 0; /* If -groupbyparent is present */
  16074. int i; /* To iterate through azArg[] */
  16075. const char *zIndent = ""; /* How much to indent CREATE INDEX by */
  16076. int rc; /* Return code */
  16077. sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
  16078. /*
  16079. ** This SELECT statement returns one row for each foreign key constraint
  16080. ** in the schema of the main database. The column values are:
  16081. **
  16082. ** 0. The text of an SQL statement similar to:
  16083. **
  16084. ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
  16085. **
  16086. ** This SELECT is similar to the one that the foreign keys implementation
  16087. ** needs to run internally on child tables. If there is an index that can
  16088. ** be used to optimize this query, then it can also be used by the FK
  16089. ** implementation to optimize DELETE or UPDATE statements on the parent
  16090. ** table.
  16091. **
  16092. ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
  16093. ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
  16094. ** contains an index that can be used to optimize the query.
  16095. **
  16096. ** 2. Human readable text that describes the child table and columns. e.g.
  16097. **
  16098. ** "child_table(child_key1, child_key2)"
  16099. **
  16100. ** 3. Human readable text that describes the parent table and columns. e.g.
  16101. **
  16102. ** "parent_table(parent_key1, parent_key2)"
  16103. **
  16104. ** 4. A full CREATE INDEX statement for an index that could be used to
  16105. ** optimize DELETE or UPDATE statements on the parent table. e.g.
  16106. **
  16107. ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
  16108. **
  16109. ** 5. The name of the parent table.
  16110. **
  16111. ** These six values are used by the C logic below to generate the report.
  16112. */
  16113. const char *zSql =
  16114. "SELECT "
  16115. " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
  16116. " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
  16117. " || fkey_collate_clause("
  16118. " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
  16119. ", "
  16120. " 'SEARCH ' || s.name || ' USING COVERING INDEX*('"
  16121. " || group_concat('*=?', ' AND ') || ')'"
  16122. ", "
  16123. " s.name || '(' || group_concat(f.[from], ', ') || ')'"
  16124. ", "
  16125. " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
  16126. ", "
  16127. " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
  16128. " || ' ON ' || quote(s.name) || '('"
  16129. " || group_concat(quote(f.[from]) ||"
  16130. " fkey_collate_clause("
  16131. " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
  16132. " || ');'"
  16133. ", "
  16134. " f.[table] "
  16135. "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
  16136. "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
  16137. "GROUP BY s.name, f.id "
  16138. "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
  16139. ;
  16140. const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
  16141. for(i=2; i<nArg; i++){
  16142. int n = strlen30(azArg[i]);
  16143. if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
  16144. bVerbose = 1;
  16145. }
  16146. else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
  16147. bGroupByParent = 1;
  16148. zIndent = " ";
  16149. }
  16150. else{
  16151. raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
  16152. azArg[0], azArg[1]
  16153. );
  16154. return SQLITE_ERROR;
  16155. }
  16156. }
  16157. /* Register the fkey_collate_clause() SQL function */
  16158. rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
  16159. 0, shellFkeyCollateClause, 0, 0
  16160. );
  16161. if( rc==SQLITE_OK ){
  16162. rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
  16163. }
  16164. if( rc==SQLITE_OK ){
  16165. sqlite3_bind_int(pSql, 1, bGroupByParent);
  16166. }
  16167. if( rc==SQLITE_OK ){
  16168. int rc2;
  16169. char *zPrev = 0;
  16170. while( SQLITE_ROW==sqlite3_step(pSql) ){
  16171. int res = -1;
  16172. sqlite3_stmt *pExplain = 0;
  16173. const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
  16174. const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
  16175. const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
  16176. const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
  16177. const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
  16178. const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
  16179. if( zEQP==0 ) continue;
  16180. if( zGlob==0 ) continue;
  16181. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  16182. if( rc!=SQLITE_OK ) break;
  16183. if( SQLITE_ROW==sqlite3_step(pExplain) ){
  16184. const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
  16185. res = zPlan!=0 && ( 0==sqlite3_strglob(zGlob, zPlan)
  16186. || 0==sqlite3_strglob(zGlobIPK, zPlan));
  16187. }
  16188. rc = sqlite3_finalize(pExplain);
  16189. if( rc!=SQLITE_OK ) break;
  16190. if( res<0 ){
  16191. raw_printf(stderr, "Error: internal error");
  16192. break;
  16193. }else{
  16194. if( bGroupByParent
  16195. && (bVerbose || res==0)
  16196. && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
  16197. ){
  16198. raw_printf(out, "-- Parent table %s\n", zParent);
  16199. sqlite3_free(zPrev);
  16200. zPrev = sqlite3_mprintf("%s", zParent);
  16201. }
  16202. if( res==0 ){
  16203. raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
  16204. }else if( bVerbose ){
  16205. raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
  16206. zIndent, zFrom, zTarget
  16207. );
  16208. }
  16209. }
  16210. }
  16211. sqlite3_free(zPrev);
  16212. if( rc!=SQLITE_OK ){
  16213. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  16214. }
  16215. rc2 = sqlite3_finalize(pSql);
  16216. if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
  16217. rc = rc2;
  16218. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  16219. }
  16220. }else{
  16221. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  16222. }
  16223. return rc;
  16224. }
  16225. /*
  16226. ** Implementation of ".lint" dot command.
  16227. */
  16228. static int lintDotCommand(
  16229. ShellState *pState, /* Current shell tool state */
  16230. char **azArg, /* Array of arguments passed to dot command */
  16231. int nArg /* Number of entries in azArg[] */
  16232. ){
  16233. int n;
  16234. n = (nArg>=2 ? strlen30(azArg[1]) : 0);
  16235. if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
  16236. return lintFkeyIndexes(pState, azArg, nArg);
  16237. usage:
  16238. raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
  16239. raw_printf(stderr, "Where sub-commands are:\n");
  16240. raw_printf(stderr, " fkey-indexes\n");
  16241. return SQLITE_ERROR;
  16242. }
  16243. #if !defined SQLITE_OMIT_VIRTUALTABLE
  16244. static void shellPrepare(
  16245. sqlite3 *db,
  16246. int *pRc,
  16247. const char *zSql,
  16248. sqlite3_stmt **ppStmt
  16249. ){
  16250. *ppStmt = 0;
  16251. if( *pRc==SQLITE_OK ){
  16252. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  16253. if( rc!=SQLITE_OK ){
  16254. raw_printf(stderr, "sql error: %s (%d)\n",
  16255. sqlite3_errmsg(db), sqlite3_errcode(db)
  16256. );
  16257. *pRc = rc;
  16258. }
  16259. }
  16260. }
  16261. /*
  16262. ** Create a prepared statement using printf-style arguments for the SQL.
  16263. **
  16264. ** This routine is could be marked "static". But it is not always used,
  16265. ** depending on compile-time options. By omitting the "static", we avoid
  16266. ** nuisance compiler warnings about "defined but not used".
  16267. */
  16268. void shellPreparePrintf(
  16269. sqlite3 *db,
  16270. int *pRc,
  16271. sqlite3_stmt **ppStmt,
  16272. const char *zFmt,
  16273. ...
  16274. ){
  16275. *ppStmt = 0;
  16276. if( *pRc==SQLITE_OK ){
  16277. va_list ap;
  16278. char *z;
  16279. va_start(ap, zFmt);
  16280. z = sqlite3_vmprintf(zFmt, ap);
  16281. va_end(ap);
  16282. if( z==0 ){
  16283. *pRc = SQLITE_NOMEM;
  16284. }else{
  16285. shellPrepare(db, pRc, z, ppStmt);
  16286. sqlite3_free(z);
  16287. }
  16288. }
  16289. }
  16290. /* Finalize the prepared statement created using shellPreparePrintf().
  16291. **
  16292. ** This routine is could be marked "static". But it is not always used,
  16293. ** depending on compile-time options. By omitting the "static", we avoid
  16294. ** nuisance compiler warnings about "defined but not used".
  16295. */
  16296. void shellFinalize(
  16297. int *pRc,
  16298. sqlite3_stmt *pStmt
  16299. ){
  16300. if( pStmt ){
  16301. sqlite3 *db = sqlite3_db_handle(pStmt);
  16302. int rc = sqlite3_finalize(pStmt);
  16303. if( *pRc==SQLITE_OK ){
  16304. if( rc!=SQLITE_OK ){
  16305. raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
  16306. }
  16307. *pRc = rc;
  16308. }
  16309. }
  16310. }
  16311. /* Reset the prepared statement created using shellPreparePrintf().
  16312. **
  16313. ** This routine is could be marked "static". But it is not always used,
  16314. ** depending on compile-time options. By omitting the "static", we avoid
  16315. ** nuisance compiler warnings about "defined but not used".
  16316. */
  16317. void shellReset(
  16318. int *pRc,
  16319. sqlite3_stmt *pStmt
  16320. ){
  16321. int rc = sqlite3_reset(pStmt);
  16322. if( *pRc==SQLITE_OK ){
  16323. if( rc!=SQLITE_OK ){
  16324. sqlite3 *db = sqlite3_db_handle(pStmt);
  16325. raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
  16326. }
  16327. *pRc = rc;
  16328. }
  16329. }
  16330. #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
  16331. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  16332. /******************************************************************************
  16333. ** The ".archive" or ".ar" command.
  16334. */
  16335. /*
  16336. ** Structure representing a single ".ar" command.
  16337. */
  16338. typedef struct ArCommand ArCommand;
  16339. struct ArCommand {
  16340. u8 eCmd; /* An AR_CMD_* value */
  16341. u8 bVerbose; /* True if --verbose */
  16342. u8 bZip; /* True if the archive is a ZIP */
  16343. u8 bDryRun; /* True if --dry-run */
  16344. u8 bAppend; /* True if --append */
  16345. u8 bGlob; /* True if --glob */
  16346. u8 fromCmdLine; /* Run from -A instead of .archive */
  16347. int nArg; /* Number of command arguments */
  16348. char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
  16349. const char *zFile; /* --file argument, or NULL */
  16350. const char *zDir; /* --directory argument, or NULL */
  16351. char **azArg; /* Array of command arguments */
  16352. ShellState *p; /* Shell state */
  16353. sqlite3 *db; /* Database containing the archive */
  16354. };
  16355. /*
  16356. ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
  16357. */
  16358. static int arUsage(FILE *f){
  16359. showHelp(f,"archive");
  16360. return SQLITE_ERROR;
  16361. }
  16362. /*
  16363. ** Print an error message for the .ar command to stderr and return
  16364. ** SQLITE_ERROR.
  16365. */
  16366. static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
  16367. va_list ap;
  16368. char *z;
  16369. va_start(ap, zFmt);
  16370. z = sqlite3_vmprintf(zFmt, ap);
  16371. va_end(ap);
  16372. utf8_printf(stderr, "Error: %s\n", z);
  16373. if( pAr->fromCmdLine ){
  16374. utf8_printf(stderr, "Use \"-A\" for more help\n");
  16375. }else{
  16376. utf8_printf(stderr, "Use \".archive --help\" for more help\n");
  16377. }
  16378. sqlite3_free(z);
  16379. return SQLITE_ERROR;
  16380. }
  16381. /*
  16382. ** Values for ArCommand.eCmd.
  16383. */
  16384. #define AR_CMD_CREATE 1
  16385. #define AR_CMD_UPDATE 2
  16386. #define AR_CMD_INSERT 3
  16387. #define AR_CMD_EXTRACT 4
  16388. #define AR_CMD_LIST 5
  16389. #define AR_CMD_HELP 6
  16390. #define AR_CMD_REMOVE 7
  16391. /*
  16392. ** Other (non-command) switches.
  16393. */
  16394. #define AR_SWITCH_VERBOSE 8
  16395. #define AR_SWITCH_FILE 9
  16396. #define AR_SWITCH_DIRECTORY 10
  16397. #define AR_SWITCH_APPEND 11
  16398. #define AR_SWITCH_DRYRUN 12
  16399. #define AR_SWITCH_GLOB 13
  16400. static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
  16401. switch( eSwitch ){
  16402. case AR_CMD_CREATE:
  16403. case AR_CMD_EXTRACT:
  16404. case AR_CMD_LIST:
  16405. case AR_CMD_REMOVE:
  16406. case AR_CMD_UPDATE:
  16407. case AR_CMD_INSERT:
  16408. case AR_CMD_HELP:
  16409. if( pAr->eCmd ){
  16410. return arErrorMsg(pAr, "multiple command options");
  16411. }
  16412. pAr->eCmd = eSwitch;
  16413. break;
  16414. case AR_SWITCH_DRYRUN:
  16415. pAr->bDryRun = 1;
  16416. break;
  16417. case AR_SWITCH_GLOB:
  16418. pAr->bGlob = 1;
  16419. break;
  16420. case AR_SWITCH_VERBOSE:
  16421. pAr->bVerbose = 1;
  16422. break;
  16423. case AR_SWITCH_APPEND:
  16424. pAr->bAppend = 1;
  16425. /* Fall thru into --file */
  16426. case AR_SWITCH_FILE:
  16427. pAr->zFile = zArg;
  16428. break;
  16429. case AR_SWITCH_DIRECTORY:
  16430. pAr->zDir = zArg;
  16431. break;
  16432. }
  16433. return SQLITE_OK;
  16434. }
  16435. /*
  16436. ** Parse the command line for an ".ar" command. The results are written into
  16437. ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
  16438. ** successfully, otherwise an error message is written to stderr and
  16439. ** SQLITE_ERROR returned.
  16440. */
  16441. static int arParseCommand(
  16442. char **azArg, /* Array of arguments passed to dot command */
  16443. int nArg, /* Number of entries in azArg[] */
  16444. ArCommand *pAr /* Populate this object */
  16445. ){
  16446. struct ArSwitch {
  16447. const char *zLong;
  16448. char cShort;
  16449. u8 eSwitch;
  16450. u8 bArg;
  16451. } aSwitch[] = {
  16452. { "create", 'c', AR_CMD_CREATE, 0 },
  16453. { "extract", 'x', AR_CMD_EXTRACT, 0 },
  16454. { "insert", 'i', AR_CMD_INSERT, 0 },
  16455. { "list", 't', AR_CMD_LIST, 0 },
  16456. { "remove", 'r', AR_CMD_REMOVE, 0 },
  16457. { "update", 'u', AR_CMD_UPDATE, 0 },
  16458. { "help", 'h', AR_CMD_HELP, 0 },
  16459. { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
  16460. { "file", 'f', AR_SWITCH_FILE, 1 },
  16461. { "append", 'a', AR_SWITCH_APPEND, 1 },
  16462. { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
  16463. { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
  16464. { "glob", 'g', AR_SWITCH_GLOB, 0 },
  16465. };
  16466. int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
  16467. struct ArSwitch *pEnd = &aSwitch[nSwitch];
  16468. if( nArg<=1 ){
  16469. utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
  16470. return arUsage(stderr);
  16471. }else{
  16472. char *z = azArg[1];
  16473. if( z[0]!='-' ){
  16474. /* Traditional style [tar] invocation */
  16475. int i;
  16476. int iArg = 2;
  16477. for(i=0; z[i]; i++){
  16478. const char *zArg = 0;
  16479. struct ArSwitch *pOpt;
  16480. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  16481. if( z[i]==pOpt->cShort ) break;
  16482. }
  16483. if( pOpt==pEnd ){
  16484. return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
  16485. }
  16486. if( pOpt->bArg ){
  16487. if( iArg>=nArg ){
  16488. return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
  16489. }
  16490. zArg = azArg[iArg++];
  16491. }
  16492. if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
  16493. }
  16494. pAr->nArg = nArg-iArg;
  16495. if( pAr->nArg>0 ){
  16496. pAr->azArg = &azArg[iArg];
  16497. }
  16498. }else{
  16499. /* Non-traditional invocation */
  16500. int iArg;
  16501. for(iArg=1; iArg<nArg; iArg++){
  16502. int n;
  16503. z = azArg[iArg];
  16504. if( z[0]!='-' ){
  16505. /* All remaining command line words are command arguments. */
  16506. pAr->azArg = &azArg[iArg];
  16507. pAr->nArg = nArg-iArg;
  16508. break;
  16509. }
  16510. n = strlen30(z);
  16511. if( z[1]!='-' ){
  16512. int i;
  16513. /* One or more short options */
  16514. for(i=1; i<n; i++){
  16515. const char *zArg = 0;
  16516. struct ArSwitch *pOpt;
  16517. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  16518. if( z[i]==pOpt->cShort ) break;
  16519. }
  16520. if( pOpt==pEnd ){
  16521. return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
  16522. }
  16523. if( pOpt->bArg ){
  16524. if( i<(n-1) ){
  16525. zArg = &z[i+1];
  16526. i = n;
  16527. }else{
  16528. if( iArg>=(nArg-1) ){
  16529. return arErrorMsg(pAr, "option requires an argument: %c",
  16530. z[i]);
  16531. }
  16532. zArg = azArg[++iArg];
  16533. }
  16534. }
  16535. if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
  16536. }
  16537. }else if( z[2]=='\0' ){
  16538. /* A -- option, indicating that all remaining command line words
  16539. ** are command arguments. */
  16540. pAr->azArg = &azArg[iArg+1];
  16541. pAr->nArg = nArg-iArg-1;
  16542. break;
  16543. }else{
  16544. /* A long option */
  16545. const char *zArg = 0; /* Argument for option, if any */
  16546. struct ArSwitch *pMatch = 0; /* Matching option */
  16547. struct ArSwitch *pOpt; /* Iterator */
  16548. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  16549. const char *zLong = pOpt->zLong;
  16550. if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
  16551. if( pMatch ){
  16552. return arErrorMsg(pAr, "ambiguous option: %s",z);
  16553. }else{
  16554. pMatch = pOpt;
  16555. }
  16556. }
  16557. }
  16558. if( pMatch==0 ){
  16559. return arErrorMsg(pAr, "unrecognized option: %s", z);
  16560. }
  16561. if( pMatch->bArg ){
  16562. if( iArg>=(nArg-1) ){
  16563. return arErrorMsg(pAr, "option requires an argument: %s", z);
  16564. }
  16565. zArg = azArg[++iArg];
  16566. }
  16567. if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
  16568. }
  16569. }
  16570. }
  16571. }
  16572. return SQLITE_OK;
  16573. }
  16574. /*
  16575. ** This function assumes that all arguments within the ArCommand.azArg[]
  16576. ** array refer to archive members, as for the --extract, --list or --remove
  16577. ** commands. It checks that each of them are "present". If any specified
  16578. ** file is not present in the archive, an error is printed to stderr and an
  16579. ** error code returned. Otherwise, if all specified arguments are present
  16580. ** in the archive, SQLITE_OK is returned. Here, "present" means either an
  16581. ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
  16582. ** when pAr->bGlob is true.
  16583. **
  16584. ** This function strips any trailing '/' characters from each argument.
  16585. ** This is consistent with the way the [tar] command seems to work on
  16586. ** Linux.
  16587. */
  16588. static int arCheckEntries(ArCommand *pAr){
  16589. int rc = SQLITE_OK;
  16590. if( pAr->nArg ){
  16591. int i, j;
  16592. sqlite3_stmt *pTest = 0;
  16593. const char *zSel = (pAr->bGlob)
  16594. ? "SELECT name FROM %s WHERE glob($name,name)"
  16595. : "SELECT name FROM %s WHERE name=$name";
  16596. shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
  16597. j = sqlite3_bind_parameter_index(pTest, "$name");
  16598. for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
  16599. char *z = pAr->azArg[i];
  16600. int n = strlen30(z);
  16601. int bOk = 0;
  16602. while( n>0 && z[n-1]=='/' ) n--;
  16603. z[n] = '\0';
  16604. sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
  16605. if( SQLITE_ROW==sqlite3_step(pTest) ){
  16606. bOk = 1;
  16607. }
  16608. shellReset(&rc, pTest);
  16609. if( rc==SQLITE_OK && bOk==0 ){
  16610. utf8_printf(stderr, "not found in archive: %s\n", z);
  16611. rc = SQLITE_ERROR;
  16612. }
  16613. }
  16614. shellFinalize(&rc, pTest);
  16615. }
  16616. return rc;
  16617. }
  16618. /*
  16619. ** Format a WHERE clause that can be used against the "sqlar" table to
  16620. ** identify all archive members that match the command arguments held
  16621. ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
  16622. ** The caller is responsible for eventually calling sqlite3_free() on
  16623. ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
  16624. ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
  16625. */
  16626. static void arWhereClause(
  16627. int *pRc,
  16628. ArCommand *pAr,
  16629. char **pzWhere /* OUT: New WHERE clause */
  16630. ){
  16631. char *zWhere = 0;
  16632. const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
  16633. if( *pRc==SQLITE_OK ){
  16634. if( pAr->nArg==0 ){
  16635. zWhere = sqlite3_mprintf("1");
  16636. }else{
  16637. int i;
  16638. const char *zSep = "";
  16639. for(i=0; i<pAr->nArg; i++){
  16640. const char *z = pAr->azArg[i];
  16641. zWhere = sqlite3_mprintf(
  16642. "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
  16643. zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
  16644. );
  16645. if( zWhere==0 ){
  16646. *pRc = SQLITE_NOMEM;
  16647. break;
  16648. }
  16649. zSep = " OR ";
  16650. }
  16651. }
  16652. }
  16653. *pzWhere = zWhere;
  16654. }
  16655. /*
  16656. ** Implementation of .ar "lisT" command.
  16657. */
  16658. static int arListCommand(ArCommand *pAr){
  16659. const char *zSql = "SELECT %s FROM %s WHERE %s";
  16660. const char *azCols[] = {
  16661. "name",
  16662. "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
  16663. };
  16664. char *zWhere = 0;
  16665. sqlite3_stmt *pSql = 0;
  16666. int rc;
  16667. rc = arCheckEntries(pAr);
  16668. arWhereClause(&rc, pAr, &zWhere);
  16669. shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
  16670. pAr->zSrcTable, zWhere);
  16671. if( pAr->bDryRun ){
  16672. utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
  16673. }else{
  16674. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  16675. if( pAr->bVerbose ){
  16676. utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
  16677. sqlite3_column_text(pSql, 0),
  16678. sqlite3_column_int(pSql, 1),
  16679. sqlite3_column_text(pSql, 2),
  16680. sqlite3_column_text(pSql, 3)
  16681. );
  16682. }else{
  16683. utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
  16684. }
  16685. }
  16686. }
  16687. shellFinalize(&rc, pSql);
  16688. sqlite3_free(zWhere);
  16689. return rc;
  16690. }
  16691. /*
  16692. ** Implementation of .ar "Remove" command.
  16693. */
  16694. static int arRemoveCommand(ArCommand *pAr){
  16695. int rc = 0;
  16696. char *zSql = 0;
  16697. char *zWhere = 0;
  16698. if( pAr->nArg ){
  16699. /* Verify that args actually exist within the archive before proceeding.
  16700. ** And formulate a WHERE clause to match them. */
  16701. rc = arCheckEntries(pAr);
  16702. arWhereClause(&rc, pAr, &zWhere);
  16703. }
  16704. if( rc==SQLITE_OK ){
  16705. zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
  16706. pAr->zSrcTable, zWhere);
  16707. if( pAr->bDryRun ){
  16708. utf8_printf(pAr->p->out, "%s\n", zSql);
  16709. }else{
  16710. char *zErr = 0;
  16711. rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
  16712. if( rc==SQLITE_OK ){
  16713. rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
  16714. if( rc!=SQLITE_OK ){
  16715. sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
  16716. }else{
  16717. rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
  16718. }
  16719. }
  16720. if( zErr ){
  16721. utf8_printf(stdout, "ERROR: %s\n", zErr);
  16722. sqlite3_free(zErr);
  16723. }
  16724. }
  16725. }
  16726. sqlite3_free(zWhere);
  16727. sqlite3_free(zSql);
  16728. return rc;
  16729. }
  16730. /*
  16731. ** Implementation of .ar "eXtract" command.
  16732. */
  16733. static int arExtractCommand(ArCommand *pAr){
  16734. const char *zSql1 =
  16735. "SELECT "
  16736. " ($dir || name),"
  16737. " writefile(($dir || name), %s, mode, mtime) "
  16738. "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
  16739. " AND name NOT GLOB '*..[/\\]*'";
  16740. const char *azExtraArg[] = {
  16741. "sqlar_uncompress(data, sz)",
  16742. "data"
  16743. };
  16744. sqlite3_stmt *pSql = 0;
  16745. int rc = SQLITE_OK;
  16746. char *zDir = 0;
  16747. char *zWhere = 0;
  16748. int i, j;
  16749. /* If arguments are specified, check that they actually exist within
  16750. ** the archive before proceeding. And formulate a WHERE clause to
  16751. ** match them. */
  16752. rc = arCheckEntries(pAr);
  16753. arWhereClause(&rc, pAr, &zWhere);
  16754. if( rc==SQLITE_OK ){
  16755. if( pAr->zDir ){
  16756. zDir = sqlite3_mprintf("%s/", pAr->zDir);
  16757. }else{
  16758. zDir = sqlite3_mprintf("");
  16759. }
  16760. if( zDir==0 ) rc = SQLITE_NOMEM;
  16761. }
  16762. shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
  16763. azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
  16764. );
  16765. if( rc==SQLITE_OK ){
  16766. j = sqlite3_bind_parameter_index(pSql, "$dir");
  16767. sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
  16768. /* Run the SELECT statement twice. The first time, writefile() is called
  16769. ** for all archive members that should be extracted. The second time,
  16770. ** only for the directories. This is because the timestamps for
  16771. ** extracted directories must be reset after they are populated (as
  16772. ** populating them changes the timestamp). */
  16773. for(i=0; i<2; i++){
  16774. j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
  16775. sqlite3_bind_int(pSql, j, i);
  16776. if( pAr->bDryRun ){
  16777. utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
  16778. }else{
  16779. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  16780. if( i==0 && pAr->bVerbose ){
  16781. utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
  16782. }
  16783. }
  16784. }
  16785. shellReset(&rc, pSql);
  16786. }
  16787. shellFinalize(&rc, pSql);
  16788. }
  16789. sqlite3_free(zDir);
  16790. sqlite3_free(zWhere);
  16791. return rc;
  16792. }
  16793. /*
  16794. ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
  16795. */
  16796. static int arExecSql(ArCommand *pAr, const char *zSql){
  16797. int rc;
  16798. if( pAr->bDryRun ){
  16799. utf8_printf(pAr->p->out, "%s\n", zSql);
  16800. rc = SQLITE_OK;
  16801. }else{
  16802. char *zErr = 0;
  16803. rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
  16804. if( zErr ){
  16805. utf8_printf(stdout, "ERROR: %s\n", zErr);
  16806. sqlite3_free(zErr);
  16807. }
  16808. }
  16809. return rc;
  16810. }
  16811. /*
  16812. ** Implementation of .ar "create", "insert", and "update" commands.
  16813. **
  16814. ** create -> Create a new SQL archive
  16815. ** insert -> Insert or reinsert all files listed
  16816. ** update -> Insert files that have changed or that were not
  16817. ** previously in the archive
  16818. **
  16819. ** Create the "sqlar" table in the database if it does not already exist.
  16820. ** Then add each file in the azFile[] array to the archive. Directories
  16821. ** are added recursively. If argument bVerbose is non-zero, a message is
  16822. ** printed on stdout for each file archived.
  16823. **
  16824. ** The create command is the same as update, except that it drops
  16825. ** any existing "sqlar" table before beginning. The "insert" command
  16826. ** always overwrites every file named on the command-line, where as
  16827. ** "update" only overwrites if the size or mtime or mode has changed.
  16828. */
  16829. static int arCreateOrUpdateCommand(
  16830. ArCommand *pAr, /* Command arguments and options */
  16831. int bUpdate, /* true for a --create. */
  16832. int bOnlyIfChanged /* Only update if file has changed */
  16833. ){
  16834. const char *zCreate =
  16835. "CREATE TABLE IF NOT EXISTS sqlar(\n"
  16836. " name TEXT PRIMARY KEY, -- name of the file\n"
  16837. " mode INT, -- access permissions\n"
  16838. " mtime INT, -- last modification time\n"
  16839. " sz INT, -- original file size\n"
  16840. " data BLOB -- compressed content\n"
  16841. ")";
  16842. const char *zDrop = "DROP TABLE IF EXISTS sqlar";
  16843. const char *zInsertFmt[2] = {
  16844. "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
  16845. " SELECT\n"
  16846. " %s,\n"
  16847. " mode,\n"
  16848. " mtime,\n"
  16849. " CASE substr(lsmode(mode),1,1)\n"
  16850. " WHEN '-' THEN length(data)\n"
  16851. " WHEN 'd' THEN 0\n"
  16852. " ELSE -1 END,\n"
  16853. " sqlar_compress(data)\n"
  16854. " FROM fsdir(%Q,%Q) AS disk\n"
  16855. " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
  16856. ,
  16857. "REPLACE INTO %s(name,mode,mtime,data)\n"
  16858. " SELECT\n"
  16859. " %s,\n"
  16860. " mode,\n"
  16861. " mtime,\n"
  16862. " data\n"
  16863. " FROM fsdir(%Q,%Q) AS disk\n"
  16864. " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
  16865. };
  16866. int i; /* For iterating through azFile[] */
  16867. int rc; /* Return code */
  16868. const char *zTab = 0; /* SQL table into which to insert */
  16869. char *zSql;
  16870. char zTemp[50];
  16871. char *zExists = 0;
  16872. arExecSql(pAr, "PRAGMA page_size=512");
  16873. rc = arExecSql(pAr, "SAVEPOINT ar;");
  16874. if( rc!=SQLITE_OK ) return rc;
  16875. zTemp[0] = 0;
  16876. if( pAr->bZip ){
  16877. /* Initialize the zipfile virtual table, if necessary */
  16878. if( pAr->zFile ){
  16879. sqlite3_uint64 r;
  16880. sqlite3_randomness(sizeof(r),&r);
  16881. sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
  16882. zTab = zTemp;
  16883. zSql = sqlite3_mprintf(
  16884. "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
  16885. zTab, pAr->zFile
  16886. );
  16887. rc = arExecSql(pAr, zSql);
  16888. sqlite3_free(zSql);
  16889. }else{
  16890. zTab = "zip";
  16891. }
  16892. }else{
  16893. /* Initialize the table for an SQLAR */
  16894. zTab = "sqlar";
  16895. if( bUpdate==0 ){
  16896. rc = arExecSql(pAr, zDrop);
  16897. if( rc!=SQLITE_OK ) goto end_ar_transaction;
  16898. }
  16899. rc = arExecSql(pAr, zCreate);
  16900. }
  16901. if( bOnlyIfChanged ){
  16902. zExists = sqlite3_mprintf(
  16903. " AND NOT EXISTS("
  16904. "SELECT 1 FROM %s AS mem"
  16905. " WHERE mem.name=disk.name"
  16906. " AND mem.mtime=disk.mtime"
  16907. " AND mem.mode=disk.mode)", zTab);
  16908. }else{
  16909. zExists = sqlite3_mprintf("");
  16910. }
  16911. if( zExists==0 ) rc = SQLITE_NOMEM;
  16912. for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
  16913. char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
  16914. pAr->bVerbose ? "shell_putsnl(name)" : "name",
  16915. pAr->azArg[i], pAr->zDir, zExists);
  16916. rc = arExecSql(pAr, zSql2);
  16917. sqlite3_free(zSql2);
  16918. }
  16919. end_ar_transaction:
  16920. if( rc!=SQLITE_OK ){
  16921. sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
  16922. }else{
  16923. rc = arExecSql(pAr, "RELEASE ar;");
  16924. if( pAr->bZip && pAr->zFile ){
  16925. zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
  16926. arExecSql(pAr, zSql);
  16927. sqlite3_free(zSql);
  16928. }
  16929. }
  16930. sqlite3_free(zExists);
  16931. return rc;
  16932. }
  16933. /*
  16934. ** Implementation of ".ar" dot command.
  16935. */
  16936. static int arDotCommand(
  16937. ShellState *pState, /* Current shell tool state */
  16938. int fromCmdLine, /* True if -A command-line option, not .ar cmd */
  16939. char **azArg, /* Array of arguments passed to dot command */
  16940. int nArg /* Number of entries in azArg[] */
  16941. ){
  16942. ArCommand cmd;
  16943. int rc;
  16944. memset(&cmd, 0, sizeof(cmd));
  16945. cmd.fromCmdLine = fromCmdLine;
  16946. rc = arParseCommand(azArg, nArg, &cmd);
  16947. if( rc==SQLITE_OK ){
  16948. int eDbType = SHELL_OPEN_UNSPEC;
  16949. cmd.p = pState;
  16950. cmd.db = pState->db;
  16951. if( cmd.zFile ){
  16952. eDbType = deduceDatabaseType(cmd.zFile, 1);
  16953. }else{
  16954. eDbType = pState->openMode;
  16955. }
  16956. if( eDbType==SHELL_OPEN_ZIPFILE ){
  16957. if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
  16958. if( cmd.zFile==0 ){
  16959. cmd.zSrcTable = sqlite3_mprintf("zip");
  16960. }else{
  16961. cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
  16962. }
  16963. }
  16964. cmd.bZip = 1;
  16965. }else if( cmd.zFile ){
  16966. int flags;
  16967. if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
  16968. if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
  16969. || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
  16970. flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
  16971. }else{
  16972. flags = SQLITE_OPEN_READONLY;
  16973. }
  16974. cmd.db = 0;
  16975. if( cmd.bDryRun ){
  16976. utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
  16977. eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
  16978. }
  16979. rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
  16980. eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
  16981. if( rc!=SQLITE_OK ){
  16982. utf8_printf(stderr, "cannot open file: %s (%s)\n",
  16983. cmd.zFile, sqlite3_errmsg(cmd.db)
  16984. );
  16985. goto end_ar_command;
  16986. }
  16987. sqlite3_fileio_init(cmd.db, 0, 0);
  16988. sqlite3_sqlar_init(cmd.db, 0, 0);
  16989. sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
  16990. shellPutsFunc, 0, 0);
  16991. }
  16992. if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
  16993. if( cmd.eCmd!=AR_CMD_CREATE
  16994. && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
  16995. ){
  16996. utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
  16997. rc = SQLITE_ERROR;
  16998. goto end_ar_command;
  16999. }
  17000. cmd.zSrcTable = sqlite3_mprintf("sqlar");
  17001. }
  17002. switch( cmd.eCmd ){
  17003. case AR_CMD_CREATE:
  17004. rc = arCreateOrUpdateCommand(&cmd, 0, 0);
  17005. break;
  17006. case AR_CMD_EXTRACT:
  17007. rc = arExtractCommand(&cmd);
  17008. break;
  17009. case AR_CMD_LIST:
  17010. rc = arListCommand(&cmd);
  17011. break;
  17012. case AR_CMD_HELP:
  17013. arUsage(pState->out);
  17014. break;
  17015. case AR_CMD_INSERT:
  17016. rc = arCreateOrUpdateCommand(&cmd, 1, 0);
  17017. break;
  17018. case AR_CMD_REMOVE:
  17019. rc = arRemoveCommand(&cmd);
  17020. break;
  17021. default:
  17022. assert( cmd.eCmd==AR_CMD_UPDATE );
  17023. rc = arCreateOrUpdateCommand(&cmd, 1, 1);
  17024. break;
  17025. }
  17026. }
  17027. end_ar_command:
  17028. if( cmd.db!=pState->db ){
  17029. close_db(cmd.db);
  17030. }
  17031. sqlite3_free(cmd.zSrcTable);
  17032. return rc;
  17033. }
  17034. /* End of the ".archive" or ".ar" command logic
  17035. *******************************************************************************/
  17036. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
  17037. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
  17038. /*
  17039. ** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
  17040. ** Otherwise, the SQL statement or statements in zSql are executed using
  17041. ** database connection db and the error code written to *pRc before
  17042. ** this function returns.
  17043. */
  17044. static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
  17045. int rc = *pRc;
  17046. if( rc==SQLITE_OK ){
  17047. char *zErr = 0;
  17048. rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
  17049. if( rc!=SQLITE_OK ){
  17050. raw_printf(stderr, "SQL error: %s\n", zErr);
  17051. }
  17052. sqlite3_free(zErr);
  17053. *pRc = rc;
  17054. }
  17055. }
  17056. /*
  17057. ** Like shellExec(), except that zFmt is a printf() style format string.
  17058. */
  17059. static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
  17060. char *z = 0;
  17061. if( *pRc==SQLITE_OK ){
  17062. va_list ap;
  17063. va_start(ap, zFmt);
  17064. z = sqlite3_vmprintf(zFmt, ap);
  17065. va_end(ap);
  17066. if( z==0 ){
  17067. *pRc = SQLITE_NOMEM;
  17068. }else{
  17069. shellExec(db, pRc, z);
  17070. }
  17071. sqlite3_free(z);
  17072. }
  17073. }
  17074. /*
  17075. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  17076. ** Otherwise, an attempt is made to allocate, zero and return a pointer
  17077. ** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
  17078. ** to SQLITE_NOMEM and NULL returned.
  17079. */
  17080. static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
  17081. void *pRet = 0;
  17082. if( *pRc==SQLITE_OK ){
  17083. pRet = sqlite3_malloc64(nByte);
  17084. if( pRet==0 ){
  17085. *pRc = SQLITE_NOMEM;
  17086. }else{
  17087. memset(pRet, 0, nByte);
  17088. }
  17089. }
  17090. return pRet;
  17091. }
  17092. /*
  17093. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  17094. ** Otherwise, zFmt is treated as a printf() style string. The result of
  17095. ** formatting it along with any trailing arguments is written into a
  17096. ** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
  17097. ** It is the responsibility of the caller to eventually free this buffer
  17098. ** using a call to sqlite3_free().
  17099. **
  17100. ** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
  17101. ** pointer returned.
  17102. */
  17103. static char *shellMPrintf(int *pRc, const char *zFmt, ...){
  17104. char *z = 0;
  17105. if( *pRc==SQLITE_OK ){
  17106. va_list ap;
  17107. va_start(ap, zFmt);
  17108. z = sqlite3_vmprintf(zFmt, ap);
  17109. va_end(ap);
  17110. if( z==0 ){
  17111. *pRc = SQLITE_NOMEM;
  17112. }
  17113. }
  17114. return z;
  17115. }
  17116. /*
  17117. ** When running the ".recover" command, each output table, and the special
  17118. ** orphaned row table if it is required, is represented by an instance
  17119. ** of the following struct.
  17120. */
  17121. typedef struct RecoverTable RecoverTable;
  17122. struct RecoverTable {
  17123. char *zQuoted; /* Quoted version of table name */
  17124. int nCol; /* Number of columns in table */
  17125. char **azlCol; /* Array of column lists */
  17126. int iPk; /* Index of IPK column */
  17127. };
  17128. /*
  17129. ** Free a RecoverTable object allocated by recoverFindTable() or
  17130. ** recoverOrphanTable().
  17131. */
  17132. static void recoverFreeTable(RecoverTable *pTab){
  17133. if( pTab ){
  17134. sqlite3_free(pTab->zQuoted);
  17135. if( pTab->azlCol ){
  17136. int i;
  17137. for(i=0; i<=pTab->nCol; i++){
  17138. sqlite3_free(pTab->azlCol[i]);
  17139. }
  17140. sqlite3_free(pTab->azlCol);
  17141. }
  17142. sqlite3_free(pTab);
  17143. }
  17144. }
  17145. /*
  17146. ** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
  17147. ** Otherwise, it allocates and returns a RecoverTable object based on the
  17148. ** final four arguments passed to this function. It is the responsibility
  17149. ** of the caller to eventually free the returned object using
  17150. ** recoverFreeTable().
  17151. */
  17152. static RecoverTable *recoverNewTable(
  17153. int *pRc, /* IN/OUT: Error code */
  17154. const char *zName, /* Name of table */
  17155. const char *zSql, /* CREATE TABLE statement */
  17156. int bIntkey,
  17157. int nCol
  17158. ){
  17159. sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */
  17160. int rc = *pRc;
  17161. RecoverTable *pTab = 0;
  17162. pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
  17163. if( rc==SQLITE_OK ){
  17164. int nSqlCol = 0;
  17165. int bSqlIntkey = 0;
  17166. sqlite3_stmt *pStmt = 0;
  17167. rc = sqlite3_open("", &dbtmp);
  17168. if( rc==SQLITE_OK ){
  17169. sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
  17170. shellIdQuote, 0, 0);
  17171. }
  17172. if( rc==SQLITE_OK ){
  17173. rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
  17174. }
  17175. if( rc==SQLITE_OK ){
  17176. rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
  17177. if( rc==SQLITE_ERROR ){
  17178. rc = SQLITE_OK;
  17179. goto finished;
  17180. }
  17181. }
  17182. shellPreparePrintf(dbtmp, &rc, &pStmt,
  17183. "SELECT count(*) FROM pragma_table_info(%Q)", zName
  17184. );
  17185. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  17186. nSqlCol = sqlite3_column_int(pStmt, 0);
  17187. }
  17188. shellFinalize(&rc, pStmt);
  17189. if( rc!=SQLITE_OK || nSqlCol<nCol ){
  17190. goto finished;
  17191. }
  17192. shellPreparePrintf(dbtmp, &rc, &pStmt,
  17193. "SELECT ("
  17194. " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
  17195. ") FROM sqlite_schema WHERE name = %Q", zName
  17196. );
  17197. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  17198. bSqlIntkey = sqlite3_column_int(pStmt, 0);
  17199. }
  17200. shellFinalize(&rc, pStmt);
  17201. if( bIntkey==bSqlIntkey ){
  17202. int i;
  17203. const char *zPk = "_rowid_";
  17204. sqlite3_stmt *pPkFinder = 0;
  17205. /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
  17206. ** set zPk to the name of the PK column, and pTab->iPk to the index
  17207. ** of the column, where columns are 0-numbered from left to right.
  17208. ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
  17209. ** leave zPk as "_rowid_" and pTab->iPk at -2. */
  17210. pTab->iPk = -2;
  17211. if( bIntkey ){
  17212. shellPreparePrintf(dbtmp, &rc, &pPkFinder,
  17213. "SELECT cid, name FROM pragma_table_info(%Q) "
  17214. " WHERE pk=1 AND type='integer' COLLATE nocase"
  17215. " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
  17216. , zName, zName
  17217. );
  17218. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
  17219. pTab->iPk = sqlite3_column_int(pPkFinder, 0);
  17220. zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
  17221. if( zPk==0 ){ zPk = "_"; /* Defensive. Should never happen */ }
  17222. }
  17223. }
  17224. pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
  17225. pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
  17226. pTab->nCol = nSqlCol;
  17227. if( bIntkey ){
  17228. pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
  17229. }else{
  17230. pTab->azlCol[0] = shellMPrintf(&rc, "");
  17231. }
  17232. i = 1;
  17233. shellPreparePrintf(dbtmp, &rc, &pStmt,
  17234. "SELECT %Q || group_concat(shell_idquote(name), ', ') "
  17235. " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
  17236. "FROM pragma_table_info(%Q)",
  17237. bIntkey ? ", " : "", pTab->iPk,
  17238. bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
  17239. zName
  17240. );
  17241. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  17242. const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
  17243. pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
  17244. i++;
  17245. }
  17246. shellFinalize(&rc, pStmt);
  17247. shellFinalize(&rc, pPkFinder);
  17248. }
  17249. }
  17250. finished:
  17251. sqlite3_close(dbtmp);
  17252. *pRc = rc;
  17253. if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
  17254. recoverFreeTable(pTab);
  17255. pTab = 0;
  17256. }
  17257. return pTab;
  17258. }
  17259. /*
  17260. ** This function is called to search the schema recovered from the
  17261. ** sqlite_schema table of the (possibly) corrupt database as part
  17262. ** of a ".recover" command. Specifically, for a table with root page
  17263. ** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
  17264. ** table must be a WITHOUT ROWID table, or if non-zero, not one of
  17265. ** those.
  17266. **
  17267. ** If a table is found, a (RecoverTable*) object is returned. Or, if
  17268. ** no such table is found, but bIntkey is false and iRoot is the
  17269. ** root page of an index in the recovered schema, then (*pbNoop) is
  17270. ** set to true and NULL returned. Or, if there is no such table or
  17271. ** index, NULL is returned and (*pbNoop) set to 0, indicating that
  17272. ** the caller should write data to the orphans table.
  17273. */
  17274. static RecoverTable *recoverFindTable(
  17275. ShellState *pState, /* Shell state object */
  17276. int *pRc, /* IN/OUT: Error code */
  17277. int iRoot, /* Root page of table */
  17278. int bIntkey, /* True for an intkey table */
  17279. int nCol, /* Number of columns in table */
  17280. int *pbNoop /* OUT: True if iRoot is root of index */
  17281. ){
  17282. sqlite3_stmt *pStmt = 0;
  17283. RecoverTable *pRet = 0;
  17284. int bNoop = 0;
  17285. const char *zSql = 0;
  17286. const char *zName = 0;
  17287. /* Search the recovered schema for an object with root page iRoot. */
  17288. shellPreparePrintf(pState->db, pRc, &pStmt,
  17289. "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
  17290. );
  17291. while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  17292. const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
  17293. if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
  17294. bNoop = 1;
  17295. break;
  17296. }
  17297. if( sqlite3_stricmp(zType, "table")==0 ){
  17298. zName = (const char*)sqlite3_column_text(pStmt, 1);
  17299. zSql = (const char*)sqlite3_column_text(pStmt, 2);
  17300. if( zName!=0 && zSql!=0 ){
  17301. pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
  17302. break;
  17303. }
  17304. }
  17305. }
  17306. shellFinalize(pRc, pStmt);
  17307. *pbNoop = bNoop;
  17308. return pRet;
  17309. }
  17310. /*
  17311. ** Return a RecoverTable object representing the orphans table.
  17312. */
  17313. static RecoverTable *recoverOrphanTable(
  17314. ShellState *pState, /* Shell state object */
  17315. int *pRc, /* IN/OUT: Error code */
  17316. const char *zLostAndFound, /* Base name for orphans table */
  17317. int nCol /* Number of user data columns */
  17318. ){
  17319. RecoverTable *pTab = 0;
  17320. if( nCol>=0 && *pRc==SQLITE_OK ){
  17321. int i;
  17322. /* This block determines the name of the orphan table. The prefered
  17323. ** name is zLostAndFound. But if that clashes with another name
  17324. ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
  17325. ** and so on until a non-clashing name is found. */
  17326. int iTab = 0;
  17327. char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
  17328. sqlite3_stmt *pTest = 0;
  17329. shellPrepare(pState->db, pRc,
  17330. "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
  17331. );
  17332. if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
  17333. while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
  17334. shellReset(pRc, pTest);
  17335. sqlite3_free(zTab);
  17336. zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
  17337. sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
  17338. }
  17339. shellFinalize(pRc, pTest);
  17340. pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
  17341. if( pTab ){
  17342. pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
  17343. pTab->nCol = nCol;
  17344. pTab->iPk = -2;
  17345. if( nCol>0 ){
  17346. pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
  17347. if( pTab->azlCol ){
  17348. pTab->azlCol[nCol] = shellMPrintf(pRc, "");
  17349. for(i=nCol-1; i>=0; i--){
  17350. pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
  17351. }
  17352. }
  17353. }
  17354. if( *pRc!=SQLITE_OK ){
  17355. recoverFreeTable(pTab);
  17356. pTab = 0;
  17357. }else{
  17358. raw_printf(pState->out,
  17359. "CREATE TABLE %s(rootpgno INTEGER, "
  17360. "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
  17361. );
  17362. for(i=0; i<nCol; i++){
  17363. raw_printf(pState->out, ", c%d", i);
  17364. }
  17365. raw_printf(pState->out, ");\n");
  17366. }
  17367. }
  17368. sqlite3_free(zTab);
  17369. }
  17370. return pTab;
  17371. }
  17372. /*
  17373. ** This function is called to recover data from the database. A script
  17374. ** to construct a new database containing all recovered data is output
  17375. ** on stream pState->out.
  17376. */
  17377. static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
  17378. int rc = SQLITE_OK;
  17379. sqlite3_stmt *pLoop = 0; /* Loop through all root pages */
  17380. sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */
  17381. sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */
  17382. const char *zRecoveryDb = ""; /* Name of "recovery" database */
  17383. const char *zLostAndFound = "lost_and_found";
  17384. int i;
  17385. int nOrphan = -1;
  17386. RecoverTable *pOrphan = 0;
  17387. int bFreelist = 1; /* 0 if --freelist-corrupt is specified */
  17388. int bRowids = 1; /* 0 if --no-rowids */
  17389. for(i=1; i<nArg; i++){
  17390. char *z = azArg[i];
  17391. int n;
  17392. if( z[0]=='-' && z[1]=='-' ) z++;
  17393. n = strlen30(z);
  17394. if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
  17395. bFreelist = 0;
  17396. }else
  17397. if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
  17398. i++;
  17399. zRecoveryDb = azArg[i];
  17400. }else
  17401. if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
  17402. i++;
  17403. zLostAndFound = azArg[i];
  17404. }else
  17405. if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
  17406. bRowids = 0;
  17407. }
  17408. else{
  17409. utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
  17410. showHelp(pState->out, azArg[0]);
  17411. return 1;
  17412. }
  17413. }
  17414. shellExecPrintf(pState->db, &rc,
  17415. /* Attach an in-memory database named 'recovery'. Create an indexed
  17416. ** cache of the sqlite_dbptr virtual table. */
  17417. "PRAGMA writable_schema = on;"
  17418. "ATTACH %Q AS recovery;"
  17419. "DROP TABLE IF EXISTS recovery.dbptr;"
  17420. "DROP TABLE IF EXISTS recovery.freelist;"
  17421. "DROP TABLE IF EXISTS recovery.map;"
  17422. "DROP TABLE IF EXISTS recovery.schema;"
  17423. "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
  17424. );
  17425. if( bFreelist ){
  17426. shellExec(pState->db, &rc,
  17427. "WITH trunk(pgno) AS ("
  17428. " SELECT shell_int32("
  17429. " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
  17430. " WHERE x>0"
  17431. " UNION"
  17432. " SELECT shell_int32("
  17433. " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
  17434. " FROM trunk WHERE x>0"
  17435. "),"
  17436. "freelist(data, n, freepgno) AS ("
  17437. " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
  17438. " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
  17439. " UNION ALL"
  17440. " SELECT data, n-1, shell_int32(data, 2+n) "
  17441. " FROM freelist WHERE n>=0"
  17442. ")"
  17443. "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
  17444. );
  17445. }
  17446. /* If this is an auto-vacuum database, add all pointer-map pages to
  17447. ** the freelist table. Do this regardless of whether or not
  17448. ** --freelist-corrupt was specified. */
  17449. shellExec(pState->db, &rc,
  17450. "WITH ptrmap(pgno) AS ("
  17451. " SELECT 2 WHERE shell_int32("
  17452. " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
  17453. " )"
  17454. " UNION ALL "
  17455. " SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
  17456. " FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
  17457. ")"
  17458. "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
  17459. );
  17460. shellExec(pState->db, &rc,
  17461. "CREATE TABLE recovery.dbptr("
  17462. " pgno, child, PRIMARY KEY(child, pgno)"
  17463. ") WITHOUT ROWID;"
  17464. "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
  17465. " SELECT * FROM sqlite_dbptr"
  17466. " WHERE pgno NOT IN freelist AND child NOT IN freelist;"
  17467. /* Delete any pointer to page 1. This ensures that page 1 is considered
  17468. ** a root page, regardless of how corrupt the db is. */
  17469. "DELETE FROM recovery.dbptr WHERE child = 1;"
  17470. /* Delete all pointers to any pages that have more than one pointer
  17471. ** to them. Such pages will be treated as root pages when recovering
  17472. ** data. */
  17473. "DELETE FROM recovery.dbptr WHERE child IN ("
  17474. " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
  17475. ");"
  17476. /* Create the "map" table that will (eventually) contain instructions
  17477. ** for dealing with each page in the db that contains one or more
  17478. ** records. */
  17479. "CREATE TABLE recovery.map("
  17480. "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
  17481. ");"
  17482. /* Populate table [map]. If there are circular loops of pages in the
  17483. ** database, the following adds all pages in such a loop to the map
  17484. ** as individual root pages. This could be handled better. */
  17485. "WITH pages(i, maxlen) AS ("
  17486. " SELECT page_count, ("
  17487. " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
  17488. " ) FROM pragma_page_count WHERE page_count>0"
  17489. " UNION ALL"
  17490. " SELECT i-1, ("
  17491. " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
  17492. " ) FROM pages WHERE i>=2"
  17493. ")"
  17494. "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
  17495. " SELECT i, maxlen, NULL, ("
  17496. " WITH p(orig, pgno, parent) AS ("
  17497. " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
  17498. " UNION "
  17499. " SELECT i, p.parent, "
  17500. " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
  17501. " )"
  17502. " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
  17503. ") "
  17504. "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
  17505. "UPDATE recovery.map AS o SET intkey = ("
  17506. " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
  17507. ");"
  17508. /* Extract data from page 1 and any linked pages into table
  17509. ** recovery.schema. With the same schema as an sqlite_schema table. */
  17510. "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
  17511. "INSERT INTO recovery.schema SELECT "
  17512. " max(CASE WHEN field=0 THEN value ELSE NULL END),"
  17513. " max(CASE WHEN field=1 THEN value ELSE NULL END),"
  17514. " max(CASE WHEN field=2 THEN value ELSE NULL END),"
  17515. " max(CASE WHEN field=3 THEN value ELSE NULL END),"
  17516. " max(CASE WHEN field=4 THEN value ELSE NULL END)"
  17517. "FROM sqlite_dbdata WHERE pgno IN ("
  17518. " SELECT pgno FROM recovery.map WHERE root=1"
  17519. ")"
  17520. "GROUP BY pgno, cell;"
  17521. "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
  17522. );
  17523. /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
  17524. ** CREATE TABLE statements that extracted from the existing schema. */
  17525. if( rc==SQLITE_OK ){
  17526. sqlite3_stmt *pStmt = 0;
  17527. /* ".recover" might output content in an order which causes immediate
  17528. ** foreign key constraints to be violated. So disable foreign-key
  17529. ** constraint enforcement to prevent problems when running the output
  17530. ** script. */
  17531. raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
  17532. raw_printf(pState->out, "BEGIN;\n");
  17533. raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
  17534. shellPrepare(pState->db, &rc,
  17535. "SELECT sql FROM recovery.schema "
  17536. "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
  17537. );
  17538. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  17539. const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
  17540. raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
  17541. &zCreateTable[12]
  17542. );
  17543. }
  17544. shellFinalize(&rc, pStmt);
  17545. }
  17546. /* Figure out if an orphan table will be required. And if so, how many
  17547. ** user columns it should contain */
  17548. shellPrepare(pState->db, &rc,
  17549. "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
  17550. , &pLoop
  17551. );
  17552. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
  17553. nOrphan = sqlite3_column_int(pLoop, 0);
  17554. }
  17555. shellFinalize(&rc, pLoop);
  17556. pLoop = 0;
  17557. shellPrepare(pState->db, &rc,
  17558. "SELECT pgno FROM recovery.map WHERE root=?", &pPages
  17559. );
  17560. shellPrepare(pState->db, &rc,
  17561. "SELECT max(field), group_concat(shell_escape_crnl(quote"
  17562. "(case when (? AND field<0) then NULL else value end)"
  17563. "), ', ')"
  17564. ", min(field) "
  17565. "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
  17566. "GROUP BY cell", &pCells
  17567. );
  17568. /* Loop through each root page. */
  17569. shellPrepare(pState->db, &rc,
  17570. "SELECT root, intkey, max(maxlen) FROM recovery.map"
  17571. " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
  17572. " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
  17573. ")", &pLoop
  17574. );
  17575. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
  17576. int iRoot = sqlite3_column_int(pLoop, 0);
  17577. int bIntkey = sqlite3_column_int(pLoop, 1);
  17578. int nCol = sqlite3_column_int(pLoop, 2);
  17579. int bNoop = 0;
  17580. RecoverTable *pTab;
  17581. assert( bIntkey==0 || bIntkey==1 );
  17582. pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
  17583. if( bNoop || rc ) continue;
  17584. if( pTab==0 ){
  17585. if( pOrphan==0 ){
  17586. pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
  17587. }
  17588. pTab = pOrphan;
  17589. if( pTab==0 ) break;
  17590. }
  17591. if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
  17592. raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
  17593. }
  17594. sqlite3_bind_int(pPages, 1, iRoot);
  17595. if( bRowids==0 && pTab->iPk<0 ){
  17596. sqlite3_bind_int(pCells, 1, 1);
  17597. }else{
  17598. sqlite3_bind_int(pCells, 1, 0);
  17599. }
  17600. sqlite3_bind_int(pCells, 3, pTab->iPk);
  17601. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
  17602. int iPgno = sqlite3_column_int(pPages, 0);
  17603. sqlite3_bind_int(pCells, 2, iPgno);
  17604. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
  17605. int nField = sqlite3_column_int(pCells, 0);
  17606. int iMin = sqlite3_column_int(pCells, 2);
  17607. const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
  17608. RecoverTable *pTab2 = pTab;
  17609. if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
  17610. if( pOrphan==0 ){
  17611. pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
  17612. }
  17613. pTab2 = pOrphan;
  17614. if( pTab2==0 ) break;
  17615. }
  17616. nField = nField+1;
  17617. if( pTab2==pOrphan ){
  17618. raw_printf(pState->out,
  17619. "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
  17620. pTab2->zQuoted, iRoot, iPgno, nField,
  17621. iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
  17622. );
  17623. }else{
  17624. raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
  17625. pTab2->zQuoted, pTab2->azlCol[nField], zVal
  17626. );
  17627. }
  17628. }
  17629. shellReset(&rc, pCells);
  17630. }
  17631. shellReset(&rc, pPages);
  17632. if( pTab!=pOrphan ) recoverFreeTable(pTab);
  17633. }
  17634. shellFinalize(&rc, pLoop);
  17635. shellFinalize(&rc, pPages);
  17636. shellFinalize(&rc, pCells);
  17637. recoverFreeTable(pOrphan);
  17638. /* The rest of the schema */
  17639. if( rc==SQLITE_OK ){
  17640. sqlite3_stmt *pStmt = 0;
  17641. shellPrepare(pState->db, &rc,
  17642. "SELECT sql, name FROM recovery.schema "
  17643. "WHERE sql NOT LIKE 'create table%'", &pStmt
  17644. );
  17645. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  17646. const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
  17647. if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
  17648. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  17649. char *zPrint = shellMPrintf(&rc,
  17650. "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
  17651. zName, zName, zSql
  17652. );
  17653. raw_printf(pState->out, "%s;\n", zPrint);
  17654. sqlite3_free(zPrint);
  17655. }else{
  17656. raw_printf(pState->out, "%s;\n", zSql);
  17657. }
  17658. }
  17659. shellFinalize(&rc, pStmt);
  17660. }
  17661. if( rc==SQLITE_OK ){
  17662. raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
  17663. raw_printf(pState->out, "COMMIT;\n");
  17664. }
  17665. sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
  17666. return rc;
  17667. }
  17668. #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
  17669. /*
  17670. * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
  17671. * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
  17672. * close db and set it to 0, and return the columns spec, to later
  17673. * be sqlite3_free()'ed by the caller.
  17674. * The return is 0 when either:
  17675. * (a) The db was not initialized and zCol==0 (There are no columns.)
  17676. * (b) zCol!=0 (Column was added, db initialized as needed.)
  17677. * The 3rd argument, pRenamed, references an out parameter. If the
  17678. * pointer is non-zero, its referent will be set to a summary of renames
  17679. * done if renaming was necessary, or set to 0 if none was done. The out
  17680. * string (if any) must be sqlite3_free()'ed by the caller.
  17681. */
  17682. #ifdef SHELL_DEBUG
  17683. #define rc_err_oom_die(rc) \
  17684. if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
  17685. else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
  17686. fprintf(stderr,"E:%d\n",rc), assert(0)
  17687. #else
  17688. static void rc_err_oom_die(int rc){
  17689. if( rc==SQLITE_NOMEM ) shell_check_oom(0);
  17690. assert(rc==SQLITE_OK||rc==SQLITE_DONE);
  17691. }
  17692. #endif
  17693. #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
  17694. static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
  17695. #else /* Otherwise, memory is faster/better for the transient DB. */
  17696. static const char *zCOL_DB = ":memory:";
  17697. #endif
  17698. /* Define character (as C string) to separate generated column ordinal
  17699. * from protected part of incoming column names. This defaults to "_"
  17700. * so that incoming column identifiers that did not need not be quoted
  17701. * remain usable without being quoted. It must be one character.
  17702. */
  17703. #ifndef SHELL_AUTOCOLUMN_SEP
  17704. # define AUTOCOLUMN_SEP "_"
  17705. #else
  17706. # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
  17707. #endif
  17708. static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
  17709. /* Queries and D{D,M}L used here */
  17710. static const char * const zTabMake = "\
  17711. CREATE TABLE ColNames(\
  17712. cpos INTEGER PRIMARY KEY,\
  17713. name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
  17714. CREATE VIEW RepeatedNames AS \
  17715. SELECT DISTINCT t.name FROM ColNames t \
  17716. WHERE t.name COLLATE NOCASE IN (\
  17717. SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
  17718. );\
  17719. ";
  17720. static const char * const zTabFill = "\
  17721. INSERT INTO ColNames(name,nlen,chop,reps,suff)\
  17722. VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
  17723. ";
  17724. static const char * const zHasDupes = "\
  17725. SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
  17726. <count(name) FROM ColNames\
  17727. ";
  17728. #ifdef SHELL_COLUMN_RENAME_CLEAN
  17729. static const char * const zDedoctor = "\
  17730. UPDATE ColNames SET chop=iif(\
  17731. (substring(name,nlen,1) BETWEEN '0' AND '9')\
  17732. AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
  17733. nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
  17734. 0\
  17735. )\
  17736. ";
  17737. #endif
  17738. static const char * const zSetReps = "\
  17739. UPDATE ColNames AS t SET reps=\
  17740. (SELECT count(*) FROM ColNames d \
  17741. WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
  17742. COLLATE NOCASE\
  17743. )\
  17744. ";
  17745. #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
  17746. static const char * const zColDigits = "\
  17747. SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
  17748. ";
  17749. #endif
  17750. static const char * const zRenameRank =
  17751. #ifdef SHELL_COLUMN_RENAME_CLEAN
  17752. "UPDATE ColNames AS t SET suff="
  17753. "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
  17754. #else /* ...RENAME_MINIMAL_ONE_PASS */
  17755. "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
  17756. " SELECT 0 AS nlz"
  17757. " UNION"
  17758. " SELECT nlz+1 AS nlz FROM Lzn"
  17759. " WHERE EXISTS("
  17760. " SELECT 1"
  17761. " FROM ColNames t, ColNames o"
  17762. " WHERE"
  17763. " iif(t.name IN (SELECT * FROM RepeatedNames),"
  17764. " printf('%s"AUTOCOLUMN_SEP"%s',"
  17765. " t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
  17766. " t.name"
  17767. " )"
  17768. " ="
  17769. " iif(o.name IN (SELECT * FROM RepeatedNames),"
  17770. " printf('%s"AUTOCOLUMN_SEP"%s',"
  17771. " o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
  17772. " o.name"
  17773. " )"
  17774. " COLLATE NOCASE"
  17775. " AND o.cpos<>t.cpos"
  17776. " GROUP BY t.cpos"
  17777. " )"
  17778. ") UPDATE Colnames AS t SET"
  17779. " chop = 0," /* No chopping, never touch incoming names. */
  17780. " suff = iif(name IN (SELECT * FROM RepeatedNames),"
  17781. " printf('"AUTOCOLUMN_SEP"%s', substring("
  17782. " printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
  17783. " ''"
  17784. " )"
  17785. #endif
  17786. ;
  17787. static const char * const zCollectVar = "\
  17788. SELECT\
  17789. '('||x'0a'\
  17790. || group_concat(\
  17791. cname||' TEXT',\
  17792. ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
  17793. ||')' AS ColsSpec \
  17794. FROM (\
  17795. SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
  17796. FROM ColNames ORDER BY cpos\
  17797. )";
  17798. static const char * const zRenamesDone =
  17799. "SELECT group_concat("
  17800. " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
  17801. " ','||x'0a')"
  17802. "FROM ColNames WHERE suff<>'' OR chop!=0"
  17803. ;
  17804. int rc;
  17805. sqlite3_stmt *pStmt = 0;
  17806. assert(pDb!=0);
  17807. if( zColNew ){
  17808. /* Add initial or additional column. Init db if necessary. */
  17809. if( *pDb==0 ){
  17810. if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
  17811. #ifdef SHELL_COLFIX_DB
  17812. if(*zCOL_DB!=':')
  17813. sqlite3_exec(*pDb,"drop table if exists ColNames;"
  17814. "drop view if exists RepeatedNames;",0,0,0);
  17815. #endif
  17816. rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
  17817. rc_err_oom_die(rc);
  17818. }
  17819. assert(*pDb!=0);
  17820. rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
  17821. rc_err_oom_die(rc);
  17822. rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
  17823. rc_err_oom_die(rc);
  17824. rc = sqlite3_step(pStmt);
  17825. rc_err_oom_die(rc);
  17826. sqlite3_finalize(pStmt);
  17827. return 0;
  17828. }else if( *pDb==0 ){
  17829. return 0;
  17830. }else{
  17831. /* Formulate the columns spec, close the DB, zero *pDb. */
  17832. char *zColsSpec = 0;
  17833. int hasDupes = db_int(*pDb, zHasDupes);
  17834. #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
  17835. int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
  17836. #else
  17837. # define nDigits 2
  17838. #endif
  17839. if( hasDupes ){
  17840. #ifdef SHELL_COLUMN_RENAME_CLEAN
  17841. rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
  17842. rc_err_oom_die(rc);
  17843. #endif
  17844. rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
  17845. rc_err_oom_die(rc);
  17846. rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
  17847. rc_err_oom_die(rc);
  17848. sqlite3_bind_int(pStmt, 1, nDigits);
  17849. rc = sqlite3_step(pStmt);
  17850. sqlite3_finalize(pStmt);
  17851. assert(rc==SQLITE_DONE);
  17852. }
  17853. assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
  17854. rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
  17855. rc_err_oom_die(rc);
  17856. rc = sqlite3_step(pStmt);
  17857. if( rc==SQLITE_ROW ){
  17858. zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  17859. }else{
  17860. zColsSpec = 0;
  17861. }
  17862. if( pzRenamed!=0 ){
  17863. if( !hasDupes ) *pzRenamed = 0;
  17864. else{
  17865. sqlite3_finalize(pStmt);
  17866. if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
  17867. && SQLITE_ROW==sqlite3_step(pStmt) ){
  17868. *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  17869. }else
  17870. *pzRenamed = 0;
  17871. }
  17872. }
  17873. sqlite3_finalize(pStmt);
  17874. sqlite3_close(*pDb);
  17875. *pDb = 0;
  17876. return zColsSpec;
  17877. }
  17878. }
  17879. /*
  17880. ** If an input line begins with "." then invoke this routine to
  17881. ** process that line.
  17882. **
  17883. ** Return 1 on error, 2 to exit, and 0 otherwise.
  17884. */
  17885. static int do_meta_command(char *zLine, ShellState *p){
  17886. int h = 1;
  17887. int nArg = 0;
  17888. int n, c;
  17889. int rc = 0;
  17890. char *azArg[52];
  17891. #ifndef SQLITE_OMIT_VIRTUALTABLE
  17892. if( p->expert.pExpert ){
  17893. expertFinish(p, 1, 0);
  17894. }
  17895. #endif
  17896. /* Parse the input line into tokens.
  17897. */
  17898. while( zLine[h] && nArg<ArraySize(azArg)-1 ){
  17899. while( IsSpace(zLine[h]) ){ h++; }
  17900. if( zLine[h]==0 ) break;
  17901. if( zLine[h]=='\'' || zLine[h]=='"' ){
  17902. int delim = zLine[h++];
  17903. azArg[nArg++] = &zLine[h];
  17904. while( zLine[h] && zLine[h]!=delim ){
  17905. if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
  17906. h++;
  17907. }
  17908. if( zLine[h]==delim ){
  17909. zLine[h++] = 0;
  17910. }
  17911. if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  17912. }else{
  17913. azArg[nArg++] = &zLine[h];
  17914. while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
  17915. if( zLine[h] ) zLine[h++] = 0;
  17916. resolve_backslashes(azArg[nArg-1]);
  17917. }
  17918. }
  17919. azArg[nArg] = 0;
  17920. /* Process the input line.
  17921. */
  17922. if( nArg==0 ) return 0; /* no tokens, no error */
  17923. n = strlen30(azArg[0]);
  17924. c = azArg[0][0];
  17925. clearTempFile(p);
  17926. #ifndef SQLITE_OMIT_AUTHORIZATION
  17927. if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
  17928. if( nArg!=2 ){
  17929. raw_printf(stderr, "Usage: .auth ON|OFF\n");
  17930. rc = 1;
  17931. goto meta_command_exit;
  17932. }
  17933. open_db(p, 0);
  17934. if( booleanValue(azArg[1]) ){
  17935. sqlite3_set_authorizer(p->db, shellAuth, p);
  17936. }else if( p->bSafeModePersist ){
  17937. sqlite3_set_authorizer(p->db, safeModeAuth, p);
  17938. }else{
  17939. sqlite3_set_authorizer(p->db, 0, 0);
  17940. }
  17941. }else
  17942. #endif
  17943. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  17944. if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
  17945. open_db(p, 0);
  17946. failIfSafeMode(p, "cannot run .archive in safe mode");
  17947. rc = arDotCommand(p, 0, azArg, nArg);
  17948. }else
  17949. #endif
  17950. if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
  17951. || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
  17952. ){
  17953. const char *zDestFile = 0;
  17954. const char *zDb = 0;
  17955. sqlite3 *pDest;
  17956. sqlite3_backup *pBackup;
  17957. int j;
  17958. int bAsync = 0;
  17959. const char *zVfs = 0;
  17960. failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
  17961. for(j=1; j<nArg; j++){
  17962. const char *z = azArg[j];
  17963. if( z[0]=='-' ){
  17964. if( z[1]=='-' ) z++;
  17965. if( strcmp(z, "-append")==0 ){
  17966. zVfs = "apndvfs";
  17967. }else
  17968. if( strcmp(z, "-async")==0 ){
  17969. bAsync = 1;
  17970. }else
  17971. {
  17972. utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
  17973. return 1;
  17974. }
  17975. }else if( zDestFile==0 ){
  17976. zDestFile = azArg[j];
  17977. }else if( zDb==0 ){
  17978. zDb = zDestFile;
  17979. zDestFile = azArg[j];
  17980. }else{
  17981. raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
  17982. return 1;
  17983. }
  17984. }
  17985. if( zDestFile==0 ){
  17986. raw_printf(stderr, "missing FILENAME argument on .backup\n");
  17987. return 1;
  17988. }
  17989. if( zDb==0 ) zDb = "main";
  17990. rc = sqlite3_open_v2(zDestFile, &pDest,
  17991. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
  17992. if( rc!=SQLITE_OK ){
  17993. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  17994. close_db(pDest);
  17995. return 1;
  17996. }
  17997. if( bAsync ){
  17998. sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
  17999. 0, 0, 0);
  18000. }
  18001. open_db(p, 0);
  18002. pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  18003. if( pBackup==0 ){
  18004. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  18005. close_db(pDest);
  18006. return 1;
  18007. }
  18008. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  18009. sqlite3_backup_finish(pBackup);
  18010. if( rc==SQLITE_DONE ){
  18011. rc = 0;
  18012. }else{
  18013. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  18014. rc = 1;
  18015. }
  18016. close_db(pDest);
  18017. }else
  18018. if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
  18019. if( nArg==2 ){
  18020. bail_on_error = booleanValue(azArg[1]);
  18021. }else{
  18022. raw_printf(stderr, "Usage: .bail on|off\n");
  18023. rc = 1;
  18024. }
  18025. }else
  18026. if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
  18027. if( nArg==2 ){
  18028. if( booleanValue(azArg[1]) ){
  18029. setBinaryMode(p->out, 1);
  18030. }else{
  18031. setTextMode(p->out, 1);
  18032. }
  18033. }else{
  18034. raw_printf(stderr, "Usage: .binary on|off\n");
  18035. rc = 1;
  18036. }
  18037. }else
  18038. /* The undocumented ".breakpoint" command causes a call to the no-op
  18039. ** routine named test_breakpoint().
  18040. */
  18041. if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
  18042. test_breakpoint();
  18043. }else
  18044. if( c=='c' && strcmp(azArg[0],"cd")==0 ){
  18045. failIfSafeMode(p, "cannot run .cd in safe mode");
  18046. if( nArg==2 ){
  18047. #if defined(_WIN32) || defined(WIN32)
  18048. wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
  18049. rc = !SetCurrentDirectoryW(z);
  18050. sqlite3_free(z);
  18051. #else
  18052. rc = chdir(azArg[1]);
  18053. #endif
  18054. if( rc ){
  18055. utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
  18056. rc = 1;
  18057. }
  18058. }else{
  18059. raw_printf(stderr, "Usage: .cd DIRECTORY\n");
  18060. rc = 1;
  18061. }
  18062. }else
  18063. if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
  18064. if( nArg==2 ){
  18065. setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
  18066. }else{
  18067. raw_printf(stderr, "Usage: .changes on|off\n");
  18068. rc = 1;
  18069. }
  18070. }else
  18071. /* Cancel output redirection, if it is currently set (by .testcase)
  18072. ** Then read the content of the testcase-out.txt file and compare against
  18073. ** azArg[1]. If there are differences, report an error and exit.
  18074. */
  18075. if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
  18076. char *zRes = 0;
  18077. output_reset(p);
  18078. if( nArg!=2 ){
  18079. raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
  18080. rc = 2;
  18081. }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
  18082. raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
  18083. rc = 2;
  18084. }else if( testcase_glob(azArg[1],zRes)==0 ){
  18085. utf8_printf(stderr,
  18086. "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
  18087. p->zTestcase, azArg[1], zRes);
  18088. rc = 1;
  18089. }else{
  18090. utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
  18091. p->nCheck++;
  18092. }
  18093. sqlite3_free(zRes);
  18094. }else
  18095. if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
  18096. failIfSafeMode(p, "cannot run .clone in safe mode");
  18097. if( nArg==2 ){
  18098. tryToClone(p, azArg[1]);
  18099. }else{
  18100. raw_printf(stderr, "Usage: .clone FILENAME\n");
  18101. rc = 1;
  18102. }
  18103. }else
  18104. if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
  18105. if( nArg==1 ){
  18106. /* List available connections */
  18107. int i;
  18108. for(i=0; i<ArraySize(p->aAuxDb); i++){
  18109. const char *zFile = p->aAuxDb[i].zDbFilename;
  18110. if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
  18111. zFile = "(not open)";
  18112. }else if( zFile==0 ){
  18113. zFile = "(memory)";
  18114. }else if( zFile[0]==0 ){
  18115. zFile = "(temporary-file)";
  18116. }
  18117. if( p->pAuxDb == &p->aAuxDb[i] ){
  18118. utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
  18119. }else if( p->aAuxDb[i].db!=0 ){
  18120. utf8_printf(stdout, " %d: %s\n", i, zFile);
  18121. }
  18122. }
  18123. }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
  18124. int i = azArg[1][0] - '0';
  18125. if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
  18126. p->pAuxDb->db = p->db;
  18127. p->pAuxDb = &p->aAuxDb[i];
  18128. globalDb = p->db = p->pAuxDb->db;
  18129. p->pAuxDb->db = 0;
  18130. }
  18131. }else if( nArg==3 && strcmp(azArg[1], "close")==0
  18132. && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
  18133. int i = azArg[2][0] - '0';
  18134. if( i<0 || i>=ArraySize(p->aAuxDb) ){
  18135. /* No-op */
  18136. }else if( p->pAuxDb == &p->aAuxDb[i] ){
  18137. raw_printf(stderr, "cannot close the active database connection\n");
  18138. rc = 1;
  18139. }else if( p->aAuxDb[i].db ){
  18140. session_close_all(p, i);
  18141. close_db(p->aAuxDb[i].db);
  18142. p->aAuxDb[i].db = 0;
  18143. }
  18144. }else{
  18145. raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
  18146. rc = 1;
  18147. }
  18148. }else
  18149. if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
  18150. char **azName = 0;
  18151. int nName = 0;
  18152. sqlite3_stmt *pStmt;
  18153. int i;
  18154. open_db(p, 0);
  18155. rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
  18156. if( rc ){
  18157. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  18158. rc = 1;
  18159. }else{
  18160. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  18161. const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
  18162. const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
  18163. if( zSchema==0 || zFile==0 ) continue;
  18164. azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
  18165. shell_check_oom(azName);
  18166. azName[nName*2] = strdup(zSchema);
  18167. azName[nName*2+1] = strdup(zFile);
  18168. nName++;
  18169. }
  18170. }
  18171. sqlite3_finalize(pStmt);
  18172. for(i=0; i<nName; i++){
  18173. int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
  18174. int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
  18175. const char *z = azName[i*2+1];
  18176. utf8_printf(p->out, "%s: %s %s%s\n",
  18177. azName[i*2],
  18178. z && z[0] ? z : "\"\"",
  18179. bRdonly ? "r/o" : "r/w",
  18180. eTxn==SQLITE_TXN_NONE ? "" :
  18181. eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
  18182. free(azName[i*2]);
  18183. free(azName[i*2+1]);
  18184. }
  18185. sqlite3_free(azName);
  18186. }else
  18187. if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
  18188. static const struct DbConfigChoices {
  18189. const char *zName;
  18190. int op;
  18191. } aDbConfig[] = {
  18192. { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
  18193. { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL },
  18194. { "dqs_dml", SQLITE_DBCONFIG_DQS_DML },
  18195. { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
  18196. { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
  18197. { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
  18198. { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW },
  18199. { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
  18200. { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE },
  18201. { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT },
  18202. { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
  18203. { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
  18204. { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
  18205. { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
  18206. { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
  18207. { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
  18208. };
  18209. int ii, v;
  18210. open_db(p, 0);
  18211. for(ii=0; ii<ArraySize(aDbConfig); ii++){
  18212. if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
  18213. if( nArg>=3 ){
  18214. sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
  18215. }
  18216. sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
  18217. utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
  18218. if( nArg>1 ) break;
  18219. }
  18220. if( nArg>1 && ii==ArraySize(aDbConfig) ){
  18221. utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
  18222. utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
  18223. }
  18224. }else
  18225. if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
  18226. rc = shell_dbinfo_command(p, nArg, azArg);
  18227. }else
  18228. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
  18229. if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
  18230. open_db(p, 0);
  18231. rc = recoverDatabaseCmd(p, nArg, azArg);
  18232. }else
  18233. #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
  18234. if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
  18235. char *zLike = 0;
  18236. char *zSql;
  18237. int i;
  18238. int savedShowHeader = p->showHeader;
  18239. int savedShellFlags = p->shellFlgs;
  18240. ShellClearFlag(p,
  18241. SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
  18242. |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
  18243. for(i=1; i<nArg; i++){
  18244. if( azArg[i][0]=='-' ){
  18245. const char *z = azArg[i]+1;
  18246. if( z[0]=='-' ) z++;
  18247. if( strcmp(z,"preserve-rowids")==0 ){
  18248. #ifdef SQLITE_OMIT_VIRTUALTABLE
  18249. raw_printf(stderr, "The --preserve-rowids option is not compatible"
  18250. " with SQLITE_OMIT_VIRTUALTABLE\n");
  18251. rc = 1;
  18252. sqlite3_free(zLike);
  18253. goto meta_command_exit;
  18254. #else
  18255. ShellSetFlag(p, SHFLG_PreserveRowid);
  18256. #endif
  18257. }else
  18258. if( strcmp(z,"newlines")==0 ){
  18259. ShellSetFlag(p, SHFLG_Newlines);
  18260. }else
  18261. if( strcmp(z,"data-only")==0 ){
  18262. ShellSetFlag(p, SHFLG_DumpDataOnly);
  18263. }else
  18264. if( strcmp(z,"nosys")==0 ){
  18265. ShellSetFlag(p, SHFLG_DumpNoSys);
  18266. }else
  18267. {
  18268. raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
  18269. rc = 1;
  18270. sqlite3_free(zLike);
  18271. goto meta_command_exit;
  18272. }
  18273. }else{
  18274. /* azArg[i] contains a LIKE pattern. This ".dump" request should
  18275. ** only dump data for tables for which either the table name matches
  18276. ** the LIKE pattern, or the table appears to be a shadow table of
  18277. ** a virtual table for which the name matches the LIKE pattern.
  18278. */
  18279. char *zExpr = sqlite3_mprintf(
  18280. "name LIKE %Q ESCAPE '\\' OR EXISTS ("
  18281. " SELECT 1 FROM sqlite_schema WHERE "
  18282. " name LIKE %Q ESCAPE '\\' AND"
  18283. " sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
  18284. " substr(o.name, 1, length(name)+1) == (name||'_')"
  18285. ")", azArg[i], azArg[i]
  18286. );
  18287. if( zLike ){
  18288. zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
  18289. }else{
  18290. zLike = zExpr;
  18291. }
  18292. }
  18293. }
  18294. open_db(p, 0);
  18295. if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
  18296. /* When playing back a "dump", the content might appear in an order
  18297. ** which causes immediate foreign key constraints to be violated.
  18298. ** So disable foreign-key constraint enforcement to prevent problems. */
  18299. raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
  18300. raw_printf(p->out, "BEGIN TRANSACTION;\n");
  18301. }
  18302. p->writableSchema = 0;
  18303. p->showHeader = 0;
  18304. /* Set writable_schema=ON since doing so forces SQLite to initialize
  18305. ** as much of the schema as it can even if the sqlite_schema table is
  18306. ** corrupt. */
  18307. sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
  18308. p->nErr = 0;
  18309. if( zLike==0 ) zLike = sqlite3_mprintf("true");
  18310. zSql = sqlite3_mprintf(
  18311. "SELECT name, type, sql FROM sqlite_schema AS o "
  18312. "WHERE (%s) AND type=='table'"
  18313. " AND sql NOT NULL"
  18314. " ORDER BY tbl_name='sqlite_sequence', rowid",
  18315. zLike
  18316. );
  18317. run_schema_dump_query(p,zSql);
  18318. sqlite3_free(zSql);
  18319. if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
  18320. zSql = sqlite3_mprintf(
  18321. "SELECT sql FROM sqlite_schema AS o "
  18322. "WHERE (%s) AND sql NOT NULL"
  18323. " AND type IN ('index','trigger','view')",
  18324. zLike
  18325. );
  18326. run_table_dump_query(p, zSql);
  18327. sqlite3_free(zSql);
  18328. }
  18329. sqlite3_free(zLike);
  18330. if( p->writableSchema ){
  18331. raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
  18332. p->writableSchema = 0;
  18333. }
  18334. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  18335. sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
  18336. if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
  18337. raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
  18338. }
  18339. p->showHeader = savedShowHeader;
  18340. p->shellFlgs = savedShellFlags;
  18341. }else
  18342. if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
  18343. if( nArg==2 ){
  18344. setOrClearFlag(p, SHFLG_Echo, azArg[1]);
  18345. }else{
  18346. raw_printf(stderr, "Usage: .echo on|off\n");
  18347. rc = 1;
  18348. }
  18349. }else
  18350. if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
  18351. if( nArg==2 ){
  18352. p->autoEQPtest = 0;
  18353. if( p->autoEQPtrace ){
  18354. if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
  18355. p->autoEQPtrace = 0;
  18356. }
  18357. if( strcmp(azArg[1],"full")==0 ){
  18358. p->autoEQP = AUTOEQP_full;
  18359. }else if( strcmp(azArg[1],"trigger")==0 ){
  18360. p->autoEQP = AUTOEQP_trigger;
  18361. #ifdef SQLITE_DEBUG
  18362. }else if( strcmp(azArg[1],"test")==0 ){
  18363. p->autoEQP = AUTOEQP_on;
  18364. p->autoEQPtest = 1;
  18365. }else if( strcmp(azArg[1],"trace")==0 ){
  18366. p->autoEQP = AUTOEQP_full;
  18367. p->autoEQPtrace = 1;
  18368. open_db(p, 0);
  18369. sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
  18370. sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
  18371. #endif
  18372. }else{
  18373. p->autoEQP = (u8)booleanValue(azArg[1]);
  18374. }
  18375. }else{
  18376. raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
  18377. rc = 1;
  18378. }
  18379. }else
  18380. if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
  18381. if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
  18382. rc = 2;
  18383. }else
  18384. /* The ".explain" command is automatic now. It is largely pointless. It
  18385. ** retained purely for backwards compatibility */
  18386. if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
  18387. int val = 1;
  18388. if( nArg>=2 ){
  18389. if( strcmp(azArg[1],"auto")==0 ){
  18390. val = 99;
  18391. }else{
  18392. val = booleanValue(azArg[1]);
  18393. }
  18394. }
  18395. if( val==1 && p->mode!=MODE_Explain ){
  18396. p->normalMode = p->mode;
  18397. p->mode = MODE_Explain;
  18398. p->autoExplain = 0;
  18399. }else if( val==0 ){
  18400. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  18401. p->autoExplain = 0;
  18402. }else if( val==99 ){
  18403. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  18404. p->autoExplain = 1;
  18405. }
  18406. }else
  18407. #ifndef SQLITE_OMIT_VIRTUALTABLE
  18408. if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
  18409. if( p->bSafeMode ){
  18410. raw_printf(stderr,
  18411. "Cannot run experimental commands such as \"%s\" in safe mode\n",
  18412. azArg[0]);
  18413. rc = 1;
  18414. }else{
  18415. open_db(p, 0);
  18416. expertDotCommand(p, azArg, nArg);
  18417. }
  18418. }else
  18419. #endif
  18420. if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
  18421. static const struct {
  18422. const char *zCtrlName; /* Name of a test-control option */
  18423. int ctrlCode; /* Integer code for that option */
  18424. const char *zUsage; /* Usage notes */
  18425. } aCtrl[] = {
  18426. { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" },
  18427. { "data_version", SQLITE_FCNTL_DATA_VERSION, "" },
  18428. { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" },
  18429. { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" },
  18430. { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" },
  18431. /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
  18432. { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" },
  18433. { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" },
  18434. { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" },
  18435. { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" },
  18436. /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
  18437. };
  18438. int filectrl = -1;
  18439. int iCtrl = -1;
  18440. sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */
  18441. int isOk = 0; /* 0: usage 1: %lld 2: no-result */
  18442. int n2, i;
  18443. const char *zCmd = 0;
  18444. const char *zSchema = 0;
  18445. open_db(p, 0);
  18446. zCmd = nArg>=2 ? azArg[1] : "help";
  18447. if( zCmd[0]=='-'
  18448. && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
  18449. && nArg>=4
  18450. ){
  18451. zSchema = azArg[2];
  18452. for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
  18453. nArg -= 2;
  18454. zCmd = azArg[1];
  18455. }
  18456. /* The argument can optionally begin with "-" or "--" */
  18457. if( zCmd[0]=='-' && zCmd[1] ){
  18458. zCmd++;
  18459. if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
  18460. }
  18461. /* --help lists all file-controls */
  18462. if( strcmp(zCmd,"help")==0 ){
  18463. utf8_printf(p->out, "Available file-controls:\n");
  18464. for(i=0; i<ArraySize(aCtrl); i++){
  18465. utf8_printf(p->out, " .filectrl %s %s\n",
  18466. aCtrl[i].zCtrlName, aCtrl[i].zUsage);
  18467. }
  18468. rc = 1;
  18469. goto meta_command_exit;
  18470. }
  18471. /* convert filectrl text option to value. allow any unique prefix
  18472. ** of the option name, or a numerical value. */
  18473. n2 = strlen30(zCmd);
  18474. for(i=0; i<ArraySize(aCtrl); i++){
  18475. if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
  18476. if( filectrl<0 ){
  18477. filectrl = aCtrl[i].ctrlCode;
  18478. iCtrl = i;
  18479. }else{
  18480. utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
  18481. "Use \".filectrl --help\" for help\n", zCmd);
  18482. rc = 1;
  18483. goto meta_command_exit;
  18484. }
  18485. }
  18486. }
  18487. if( filectrl<0 ){
  18488. utf8_printf(stderr,"Error: unknown file-control: %s\n"
  18489. "Use \".filectrl --help\" for help\n", zCmd);
  18490. }else{
  18491. switch(filectrl){
  18492. case SQLITE_FCNTL_SIZE_LIMIT: {
  18493. if( nArg!=2 && nArg!=3 ) break;
  18494. iRes = nArg==3 ? integerValue(azArg[2]) : -1;
  18495. sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
  18496. isOk = 1;
  18497. break;
  18498. }
  18499. case SQLITE_FCNTL_LOCK_TIMEOUT:
  18500. case SQLITE_FCNTL_CHUNK_SIZE: {
  18501. int x;
  18502. if( nArg!=3 ) break;
  18503. x = (int)integerValue(azArg[2]);
  18504. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  18505. isOk = 2;
  18506. break;
  18507. }
  18508. case SQLITE_FCNTL_PERSIST_WAL:
  18509. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  18510. int x;
  18511. if( nArg!=2 && nArg!=3 ) break;
  18512. x = nArg==3 ? booleanValue(azArg[2]) : -1;
  18513. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  18514. iRes = x;
  18515. isOk = 1;
  18516. break;
  18517. }
  18518. case SQLITE_FCNTL_DATA_VERSION:
  18519. case SQLITE_FCNTL_HAS_MOVED: {
  18520. int x;
  18521. if( nArg!=2 ) break;
  18522. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  18523. iRes = x;
  18524. isOk = 1;
  18525. break;
  18526. }
  18527. case SQLITE_FCNTL_TEMPFILENAME: {
  18528. char *z = 0;
  18529. if( nArg!=2 ) break;
  18530. sqlite3_file_control(p->db, zSchema, filectrl, &z);
  18531. if( z ){
  18532. utf8_printf(p->out, "%s\n", z);
  18533. sqlite3_free(z);
  18534. }
  18535. isOk = 2;
  18536. break;
  18537. }
  18538. case SQLITE_FCNTL_RESERVE_BYTES: {
  18539. int x;
  18540. if( nArg>=3 ){
  18541. x = atoi(azArg[2]);
  18542. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  18543. }
  18544. x = -1;
  18545. sqlite3_file_control(p->db, zSchema, filectrl, &x);
  18546. utf8_printf(p->out,"%d\n", x);
  18547. isOk = 2;
  18548. break;
  18549. }
  18550. }
  18551. }
  18552. if( isOk==0 && iCtrl>=0 ){
  18553. utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
  18554. rc = 1;
  18555. }else if( isOk==1 ){
  18556. char zBuf[100];
  18557. sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
  18558. raw_printf(p->out, "%s\n", zBuf);
  18559. }
  18560. }else
  18561. if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
  18562. ShellState data;
  18563. int doStats = 0;
  18564. memcpy(&data, p, sizeof(data));
  18565. data.showHeader = 0;
  18566. data.cMode = data.mode = MODE_Semi;
  18567. if( nArg==2 && optionMatch(azArg[1], "indent") ){
  18568. data.cMode = data.mode = MODE_Pretty;
  18569. nArg = 1;
  18570. }
  18571. if( nArg!=1 ){
  18572. raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
  18573. rc = 1;
  18574. goto meta_command_exit;
  18575. }
  18576. open_db(p, 0);
  18577. rc = sqlite3_exec(p->db,
  18578. "SELECT sql FROM"
  18579. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  18580. " FROM sqlite_schema UNION ALL"
  18581. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
  18582. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  18583. "ORDER BY x",
  18584. callback, &data, 0
  18585. );
  18586. if( rc==SQLITE_OK ){
  18587. sqlite3_stmt *pStmt;
  18588. rc = sqlite3_prepare_v2(p->db,
  18589. "SELECT rowid FROM sqlite_schema"
  18590. " WHERE name GLOB 'sqlite_stat[134]'",
  18591. -1, &pStmt, 0);
  18592. doStats = sqlite3_step(pStmt)==SQLITE_ROW;
  18593. sqlite3_finalize(pStmt);
  18594. }
  18595. if( doStats==0 ){
  18596. raw_printf(p->out, "/* No STAT tables available */\n");
  18597. }else{
  18598. raw_printf(p->out, "ANALYZE sqlite_schema;\n");
  18599. data.cMode = data.mode = MODE_Insert;
  18600. data.zDestTable = "sqlite_stat1";
  18601. shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
  18602. data.zDestTable = "sqlite_stat4";
  18603. shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
  18604. raw_printf(p->out, "ANALYZE sqlite_schema;\n");
  18605. }
  18606. }else
  18607. if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
  18608. if( nArg==2 ){
  18609. p->showHeader = booleanValue(azArg[1]);
  18610. p->shellFlgs |= SHFLG_HeaderSet;
  18611. }else{
  18612. raw_printf(stderr, "Usage: .headers on|off\n");
  18613. rc = 1;
  18614. }
  18615. }else
  18616. if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  18617. if( nArg>=2 ){
  18618. n = showHelp(p->out, azArg[1]);
  18619. if( n==0 ){
  18620. utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
  18621. }
  18622. }else{
  18623. showHelp(p->out, 0);
  18624. }
  18625. }else
  18626. if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
  18627. char *zTable = 0; /* Insert data into this table */
  18628. char *zSchema = 0; /* within this schema (may default to "main") */
  18629. char *zFile = 0; /* Name of file to extra content from */
  18630. sqlite3_stmt *pStmt = NULL; /* A statement */
  18631. int nCol; /* Number of columns in the table */
  18632. int nByte; /* Number of bytes in an SQL string */
  18633. int i, j; /* Loop counters */
  18634. int needCommit; /* True to COMMIT or ROLLBACK at end */
  18635. int nSep; /* Number of bytes in p->colSeparator[] */
  18636. char *zSql; /* An SQL statement */
  18637. char *zFullTabName; /* Table name with schema if applicable */
  18638. ImportCtx sCtx; /* Reader context */
  18639. char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
  18640. int eVerbose = 0; /* Larger for more console output */
  18641. int nSkip = 0; /* Initial lines to skip */
  18642. int useOutputMode = 1; /* Use output mode to determine separators */
  18643. char *zCreate = 0; /* CREATE TABLE statement text */
  18644. failIfSafeMode(p, "cannot run .import in safe mode");
  18645. memset(&sCtx, 0, sizeof(sCtx));
  18646. sCtx.z = sqlite3_malloc64(120);
  18647. if( sCtx.z==0 ){
  18648. import_cleanup(&sCtx);
  18649. shell_out_of_memory();
  18650. }
  18651. if( p->mode==MODE_Ascii ){
  18652. xRead = ascii_read_one_field;
  18653. }else{
  18654. xRead = csv_read_one_field;
  18655. }
  18656. for(i=1; i<nArg; i++){
  18657. char *z = azArg[i];
  18658. if( z[0]=='-' && z[1]=='-' ) z++;
  18659. if( z[0]!='-' ){
  18660. if( zFile==0 ){
  18661. zFile = z;
  18662. }else if( zTable==0 ){
  18663. zTable = z;
  18664. }else{
  18665. utf8_printf(p->out, "ERROR: extra argument: \"%s\". Usage:\n", z);
  18666. showHelp(p->out, "import");
  18667. rc = 1;
  18668. goto meta_command_exit;
  18669. }
  18670. }else if( strcmp(z,"-v")==0 ){
  18671. eVerbose++;
  18672. }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){
  18673. zSchema = azArg[++i];
  18674. }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
  18675. nSkip = integerValue(azArg[++i]);
  18676. }else if( strcmp(z,"-ascii")==0 ){
  18677. sCtx.cColSep = SEP_Unit[0];
  18678. sCtx.cRowSep = SEP_Record[0];
  18679. xRead = ascii_read_one_field;
  18680. useOutputMode = 0;
  18681. }else if( strcmp(z,"-csv")==0 ){
  18682. sCtx.cColSep = ',';
  18683. sCtx.cRowSep = '\n';
  18684. xRead = csv_read_one_field;
  18685. useOutputMode = 0;
  18686. }else{
  18687. utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", z);
  18688. showHelp(p->out, "import");
  18689. rc = 1;
  18690. goto meta_command_exit;
  18691. }
  18692. }
  18693. if( zTable==0 ){
  18694. utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
  18695. zFile==0 ? "FILE" : "TABLE");
  18696. showHelp(p->out, "import");
  18697. rc = 1;
  18698. goto meta_command_exit;
  18699. }
  18700. seenInterrupt = 0;
  18701. open_db(p, 0);
  18702. if( useOutputMode ){
  18703. /* If neither the --csv or --ascii options are specified, then set
  18704. ** the column and row separator characters from the output mode. */
  18705. nSep = strlen30(p->colSeparator);
  18706. if( nSep==0 ){
  18707. raw_printf(stderr,
  18708. "Error: non-null column separator required for import\n");
  18709. rc = 1;
  18710. goto meta_command_exit;
  18711. }
  18712. if( nSep>1 ){
  18713. raw_printf(stderr,
  18714. "Error: multi-character column separators not allowed"
  18715. " for import\n");
  18716. rc = 1;
  18717. goto meta_command_exit;
  18718. }
  18719. nSep = strlen30(p->rowSeparator);
  18720. if( nSep==0 ){
  18721. raw_printf(stderr,
  18722. "Error: non-null row separator required for import\n");
  18723. rc = 1;
  18724. goto meta_command_exit;
  18725. }
  18726. if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
  18727. /* When importing CSV (only), if the row separator is set to the
  18728. ** default output row separator, change it to the default input
  18729. ** row separator. This avoids having to maintain different input
  18730. ** and output row separators. */
  18731. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  18732. nSep = strlen30(p->rowSeparator);
  18733. }
  18734. if( nSep>1 ){
  18735. raw_printf(stderr, "Error: multi-character row separators not allowed"
  18736. " for import\n");
  18737. rc = 1;
  18738. goto meta_command_exit;
  18739. }
  18740. sCtx.cColSep = p->colSeparator[0];
  18741. sCtx.cRowSep = p->rowSeparator[0];
  18742. }
  18743. sCtx.zFile = zFile;
  18744. sCtx.nLine = 1;
  18745. if( sCtx.zFile[0]=='|' ){
  18746. #ifdef SQLITE_OMIT_POPEN
  18747. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  18748. rc = 1;
  18749. goto meta_command_exit;
  18750. #else
  18751. sCtx.in = popen(sCtx.zFile+1, "r");
  18752. sCtx.zFile = "<pipe>";
  18753. sCtx.xCloser = pclose;
  18754. #endif
  18755. }else{
  18756. sCtx.in = fopen(sCtx.zFile, "rb");
  18757. sCtx.xCloser = fclose;
  18758. }
  18759. if( sCtx.in==0 ){
  18760. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  18761. rc = 1;
  18762. import_cleanup(&sCtx);
  18763. goto meta_command_exit;
  18764. }
  18765. if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
  18766. char zSep[2];
  18767. zSep[1] = 0;
  18768. zSep[0] = sCtx.cColSep;
  18769. utf8_printf(p->out, "Column separator ");
  18770. output_c_string(p->out, zSep);
  18771. utf8_printf(p->out, ", row separator ");
  18772. zSep[0] = sCtx.cRowSep;
  18773. output_c_string(p->out, zSep);
  18774. utf8_printf(p->out, "\n");
  18775. }
  18776. /* Below, resources must be freed before exit. */
  18777. while( (nSkip--)>0 ){
  18778. while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
  18779. }
  18780. if( zSchema!=0 ){
  18781. zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
  18782. }else{
  18783. zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
  18784. }
  18785. zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
  18786. if( zSql==0 || zFullTabName==0 ){
  18787. import_cleanup(&sCtx);
  18788. shell_out_of_memory();
  18789. }
  18790. nByte = strlen30(zSql);
  18791. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  18792. import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
  18793. if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
  18794. sqlite3 *dbCols = 0;
  18795. char *zRenames = 0;
  18796. char *zColDefs;
  18797. zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
  18798. while( xRead(&sCtx) ){
  18799. zAutoColumn(sCtx.z, &dbCols, 0);
  18800. if( sCtx.cTerm!=sCtx.cColSep ) break;
  18801. }
  18802. zColDefs = zAutoColumn(0, &dbCols, &zRenames);
  18803. if( zRenames!=0 ){
  18804. utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
  18805. "Columns renamed during .import %s due to duplicates:\n"
  18806. "%s\n", sCtx.zFile, zRenames);
  18807. sqlite3_free(zRenames);
  18808. }
  18809. assert(dbCols==0);
  18810. if( zColDefs==0 ){
  18811. utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
  18812. import_fail:
  18813. sqlite3_free(zCreate);
  18814. sqlite3_free(zSql);
  18815. sqlite3_free(zFullTabName);
  18816. import_cleanup(&sCtx);
  18817. rc = 1;
  18818. goto meta_command_exit;
  18819. }
  18820. zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
  18821. if( eVerbose>=1 ){
  18822. utf8_printf(p->out, "%s\n", zCreate);
  18823. }
  18824. rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
  18825. if( rc ){
  18826. utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
  18827. goto import_fail;
  18828. }
  18829. sqlite3_free(zCreate);
  18830. zCreate = 0;
  18831. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  18832. }
  18833. if( rc ){
  18834. if (pStmt) sqlite3_finalize(pStmt);
  18835. utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
  18836. goto import_fail;
  18837. }
  18838. sqlite3_free(zSql);
  18839. nCol = sqlite3_column_count(pStmt);
  18840. sqlite3_finalize(pStmt);
  18841. pStmt = 0;
  18842. if( nCol==0 ) return 0; /* no columns, no error */
  18843. zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
  18844. if( zSql==0 ){
  18845. import_cleanup(&sCtx);
  18846. shell_out_of_memory();
  18847. }
  18848. sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
  18849. j = strlen30(zSql);
  18850. for(i=1; i<nCol; i++){
  18851. zSql[j++] = ',';
  18852. zSql[j++] = '?';
  18853. }
  18854. zSql[j++] = ')';
  18855. zSql[j] = 0;
  18856. if( eVerbose>=2 ){
  18857. utf8_printf(p->out, "Insert using: %s\n", zSql);
  18858. }
  18859. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  18860. if( rc ){
  18861. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  18862. if (pStmt) sqlite3_finalize(pStmt);
  18863. goto import_fail;
  18864. }
  18865. sqlite3_free(zSql);
  18866. sqlite3_free(zFullTabName);
  18867. needCommit = sqlite3_get_autocommit(p->db);
  18868. if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
  18869. do{
  18870. int startLine = sCtx.nLine;
  18871. for(i=0; i<nCol; i++){
  18872. char *z = xRead(&sCtx);
  18873. /*
  18874. ** Did we reach end-of-file before finding any columns?
  18875. ** If so, stop instead of NULL filling the remaining columns.
  18876. */
  18877. if( z==0 && i==0 ) break;
  18878. /*
  18879. ** Did we reach end-of-file OR end-of-line before finding any
  18880. ** columns in ASCII mode? If so, stop instead of NULL filling
  18881. ** the remaining columns.
  18882. */
  18883. if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
  18884. sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
  18885. if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
  18886. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  18887. "filling the rest with NULL\n",
  18888. sCtx.zFile, startLine, nCol, i+1);
  18889. i += 2;
  18890. while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
  18891. }
  18892. }
  18893. if( sCtx.cTerm==sCtx.cColSep ){
  18894. do{
  18895. xRead(&sCtx);
  18896. i++;
  18897. }while( sCtx.cTerm==sCtx.cColSep );
  18898. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  18899. "extras ignored\n",
  18900. sCtx.zFile, startLine, nCol, i);
  18901. }
  18902. if( i>=nCol ){
  18903. sqlite3_step(pStmt);
  18904. rc = sqlite3_reset(pStmt);
  18905. if( rc!=SQLITE_OK ){
  18906. utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
  18907. startLine, sqlite3_errmsg(p->db));
  18908. sCtx.nErr++;
  18909. }else{
  18910. sCtx.nRow++;
  18911. }
  18912. }
  18913. }while( sCtx.cTerm!=EOF );
  18914. import_cleanup(&sCtx);
  18915. sqlite3_finalize(pStmt);
  18916. if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
  18917. if( eVerbose>0 ){
  18918. utf8_printf(p->out,
  18919. "Added %d rows with %d errors using %d lines of input\n",
  18920. sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
  18921. }
  18922. }else
  18923. #ifndef SQLITE_UNTESTABLE
  18924. if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
  18925. char *zSql;
  18926. char *zCollist = 0;
  18927. sqlite3_stmt *pStmt;
  18928. int tnum = 0;
  18929. int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */
  18930. int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
  18931. int i;
  18932. if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
  18933. utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
  18934. " .imposter off\n");
  18935. /* Also allowed, but not documented:
  18936. **
  18937. ** .imposter TABLE IMPOSTER
  18938. **
  18939. ** where TABLE is a WITHOUT ROWID table. In that case, the
  18940. ** imposter is another WITHOUT ROWID table with the columns in
  18941. ** storage order. */
  18942. rc = 1;
  18943. goto meta_command_exit;
  18944. }
  18945. open_db(p, 0);
  18946. if( nArg==2 ){
  18947. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
  18948. goto meta_command_exit;
  18949. }
  18950. zSql = sqlite3_mprintf(
  18951. "SELECT rootpage, 0 FROM sqlite_schema"
  18952. " WHERE name='%q' AND type='index'"
  18953. "UNION ALL "
  18954. "SELECT rootpage, 1 FROM sqlite_schema"
  18955. " WHERE name='%q' AND type='table'"
  18956. " AND sql LIKE '%%without%%rowid%%'",
  18957. azArg[1], azArg[1]
  18958. );
  18959. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  18960. sqlite3_free(zSql);
  18961. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  18962. tnum = sqlite3_column_int(pStmt, 0);
  18963. isWO = sqlite3_column_int(pStmt, 1);
  18964. }
  18965. sqlite3_finalize(pStmt);
  18966. zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
  18967. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  18968. sqlite3_free(zSql);
  18969. i = 0;
  18970. while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
  18971. char zLabel[20];
  18972. const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
  18973. i++;
  18974. if( zCol==0 ){
  18975. if( sqlite3_column_int(pStmt,1)==-1 ){
  18976. zCol = "_ROWID_";
  18977. }else{
  18978. sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
  18979. zCol = zLabel;
  18980. }
  18981. }
  18982. if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
  18983. lenPK = (int)strlen(zCollist);
  18984. }
  18985. if( zCollist==0 ){
  18986. zCollist = sqlite3_mprintf("\"%w\"", zCol);
  18987. }else{
  18988. zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
  18989. }
  18990. }
  18991. sqlite3_finalize(pStmt);
  18992. if( i==0 || tnum==0 ){
  18993. utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
  18994. rc = 1;
  18995. sqlite3_free(zCollist);
  18996. goto meta_command_exit;
  18997. }
  18998. if( lenPK==0 ) lenPK = 100000;
  18999. zSql = sqlite3_mprintf(
  19000. "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
  19001. azArg[2], zCollist, lenPK, zCollist);
  19002. sqlite3_free(zCollist);
  19003. rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
  19004. if( rc==SQLITE_OK ){
  19005. rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
  19006. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
  19007. if( rc ){
  19008. utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
  19009. }else{
  19010. utf8_printf(stdout, "%s;\n", zSql);
  19011. raw_printf(stdout,
  19012. "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
  19013. azArg[1], isWO ? "table" : "index"
  19014. );
  19015. }
  19016. }else{
  19017. raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
  19018. rc = 1;
  19019. }
  19020. sqlite3_free(zSql);
  19021. }else
  19022. #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
  19023. #ifdef SQLITE_ENABLE_IOTRACE
  19024. if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
  19025. SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
  19026. if( iotrace && iotrace!=stdout ) fclose(iotrace);
  19027. iotrace = 0;
  19028. if( nArg<2 ){
  19029. sqlite3IoTrace = 0;
  19030. }else if( strcmp(azArg[1], "-")==0 ){
  19031. sqlite3IoTrace = iotracePrintf;
  19032. iotrace = stdout;
  19033. }else{
  19034. iotrace = fopen(azArg[1], "w");
  19035. if( iotrace==0 ){
  19036. utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  19037. sqlite3IoTrace = 0;
  19038. rc = 1;
  19039. }else{
  19040. sqlite3IoTrace = iotracePrintf;
  19041. }
  19042. }
  19043. }else
  19044. #endif
  19045. if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
  19046. static const struct {
  19047. const char *zLimitName; /* Name of a limit */
  19048. int limitCode; /* Integer code for that limit */
  19049. } aLimit[] = {
  19050. { "length", SQLITE_LIMIT_LENGTH },
  19051. { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
  19052. { "column", SQLITE_LIMIT_COLUMN },
  19053. { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
  19054. { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
  19055. { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
  19056. { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
  19057. { "attached", SQLITE_LIMIT_ATTACHED },
  19058. { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
  19059. { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
  19060. { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
  19061. { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
  19062. };
  19063. int i, n2;
  19064. open_db(p, 0);
  19065. if( nArg==1 ){
  19066. for(i=0; i<ArraySize(aLimit); i++){
  19067. printf("%20s %d\n", aLimit[i].zLimitName,
  19068. sqlite3_limit(p->db, aLimit[i].limitCode, -1));
  19069. }
  19070. }else if( nArg>3 ){
  19071. raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
  19072. rc = 1;
  19073. goto meta_command_exit;
  19074. }else{
  19075. int iLimit = -1;
  19076. n2 = strlen30(azArg[1]);
  19077. for(i=0; i<ArraySize(aLimit); i++){
  19078. if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
  19079. if( iLimit<0 ){
  19080. iLimit = i;
  19081. }else{
  19082. utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
  19083. rc = 1;
  19084. goto meta_command_exit;
  19085. }
  19086. }
  19087. }
  19088. if( iLimit<0 ){
  19089. utf8_printf(stderr, "unknown limit: \"%s\"\n"
  19090. "enter \".limits\" with no arguments for a list.\n",
  19091. azArg[1]);
  19092. rc = 1;
  19093. goto meta_command_exit;
  19094. }
  19095. if( nArg==3 ){
  19096. sqlite3_limit(p->db, aLimit[iLimit].limitCode,
  19097. (int)integerValue(azArg[2]));
  19098. }
  19099. printf("%20s %d\n", aLimit[iLimit].zLimitName,
  19100. sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
  19101. }
  19102. }else
  19103. if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
  19104. open_db(p, 0);
  19105. lintDotCommand(p, azArg, nArg);
  19106. }else
  19107. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  19108. if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
  19109. const char *zFile, *zProc;
  19110. char *zErrMsg = 0;
  19111. failIfSafeMode(p, "cannot run .load in safe mode");
  19112. if( nArg<2 ){
  19113. raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
  19114. rc = 1;
  19115. goto meta_command_exit;
  19116. }
  19117. zFile = azArg[1];
  19118. zProc = nArg>=3 ? azArg[2] : 0;
  19119. open_db(p, 0);
  19120. rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  19121. if( rc!=SQLITE_OK ){
  19122. utf8_printf(stderr, "Error: %s\n", zErrMsg);
  19123. sqlite3_free(zErrMsg);
  19124. rc = 1;
  19125. }
  19126. }else
  19127. #endif
  19128. if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
  19129. failIfSafeMode(p, "cannot run .log in safe mode");
  19130. if( nArg!=2 ){
  19131. raw_printf(stderr, "Usage: .log FILENAME\n");
  19132. rc = 1;
  19133. }else{
  19134. const char *zFile = azArg[1];
  19135. output_file_close(p->pLog);
  19136. p->pLog = output_file_open(zFile, 0);
  19137. }
  19138. }else
  19139. if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
  19140. const char *zMode = 0;
  19141. const char *zTabname = 0;
  19142. int i, n2;
  19143. ColModeOpts cmOpts = ColModeOpts_default;
  19144. for(i=1; i<nArg; i++){
  19145. const char *z = azArg[i];
  19146. if( optionMatch(z,"wrap") && i+1<nArg ){
  19147. cmOpts.iWrap = integerValue(azArg[++i]);
  19148. }else if( optionMatch(z,"ww") ){
  19149. cmOpts.bWordWrap = 1;
  19150. }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
  19151. cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
  19152. }else if( optionMatch(z,"quote") ){
  19153. cmOpts.bQuote = 1;
  19154. }else if( optionMatch(z,"noquote") ){
  19155. cmOpts.bQuote = 0;
  19156. }else if( zMode==0 ){
  19157. zMode = z;
  19158. /* Apply defaults for qbox pseudo-mods. If that
  19159. * overwrites already-set values, user was informed of this.
  19160. */
  19161. if( strcmp(z, "qbox")==0 ){
  19162. ColModeOpts cmo = ColModeOpts_default_qbox;
  19163. zMode = "box";
  19164. cmOpts = cmo;
  19165. }
  19166. }else if( zTabname==0 ){
  19167. zTabname = z;
  19168. }else if( z[0]=='-' ){
  19169. utf8_printf(stderr, "unknown option: %s\n", z);
  19170. utf8_printf(stderr, "options:\n"
  19171. " --noquote\n"
  19172. " --quote\n"
  19173. " --wordwrap on/off\n"
  19174. " --wrap N\n"
  19175. " --ww\n");
  19176. rc = 1;
  19177. goto meta_command_exit;
  19178. }else{
  19179. utf8_printf(stderr, "extra argument: \"%s\"\n", z);
  19180. rc = 1;
  19181. goto meta_command_exit;
  19182. }
  19183. }
  19184. if( zMode==0 ){
  19185. if( p->mode==MODE_Column
  19186. || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
  19187. ){
  19188. raw_printf
  19189. (p->out,
  19190. "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
  19191. modeDescr[p->mode], p->cmOpts.iWrap,
  19192. p->cmOpts.bWordWrap ? "on" : "off",
  19193. p->cmOpts.bQuote ? "" : "no");
  19194. }else{
  19195. raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
  19196. }
  19197. zMode = modeDescr[p->mode];
  19198. }
  19199. n2 = strlen30(zMode);
  19200. if( strncmp(zMode,"lines",n2)==0 ){
  19201. p->mode = MODE_Line;
  19202. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  19203. }else if( strncmp(zMode,"columns",n2)==0 ){
  19204. p->mode = MODE_Column;
  19205. if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
  19206. p->showHeader = 1;
  19207. }
  19208. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  19209. p->cmOpts = cmOpts;
  19210. }else if( strncmp(zMode,"list",n2)==0 ){
  19211. p->mode = MODE_List;
  19212. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
  19213. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  19214. }else if( strncmp(zMode,"html",n2)==0 ){
  19215. p->mode = MODE_Html;
  19216. }else if( strncmp(zMode,"tcl",n2)==0 ){
  19217. p->mode = MODE_Tcl;
  19218. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
  19219. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  19220. }else if( strncmp(zMode,"csv",n2)==0 ){
  19221. p->mode = MODE_Csv;
  19222. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  19223. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  19224. }else if( strncmp(zMode,"tabs",n2)==0 ){
  19225. p->mode = MODE_List;
  19226. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
  19227. }else if( strncmp(zMode,"insert",n2)==0 ){
  19228. p->mode = MODE_Insert;
  19229. set_table_name(p, zTabname ? zTabname : "table");
  19230. }else if( strncmp(zMode,"quote",n2)==0 ){
  19231. p->mode = MODE_Quote;
  19232. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  19233. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  19234. }else if( strncmp(zMode,"ascii",n2)==0 ){
  19235. p->mode = MODE_Ascii;
  19236. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
  19237. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
  19238. }else if( strncmp(zMode,"markdown",n2)==0 ){
  19239. p->mode = MODE_Markdown;
  19240. p->cmOpts = cmOpts;
  19241. }else if( strncmp(zMode,"table",n2)==0 ){
  19242. p->mode = MODE_Table;
  19243. p->cmOpts = cmOpts;
  19244. }else if( strncmp(zMode,"box",n2)==0 ){
  19245. p->mode = MODE_Box;
  19246. p->cmOpts = cmOpts;
  19247. }else if( strncmp(zMode,"count",n2)==0 ){
  19248. p->mode = MODE_Count;
  19249. }else if( strncmp(zMode,"off",n2)==0 ){
  19250. p->mode = MODE_Off;
  19251. }else if( strncmp(zMode,"json",n2)==0 ){
  19252. p->mode = MODE_Json;
  19253. }else{
  19254. raw_printf(stderr, "Error: mode should be one of: "
  19255. "ascii box column csv html insert json line list markdown "
  19256. "qbox quote table tabs tcl\n");
  19257. rc = 1;
  19258. }
  19259. p->cMode = p->mode;
  19260. }else
  19261. if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
  19262. if( nArg!=2 ){
  19263. raw_printf(stderr, "Usage: .nonce NONCE\n");
  19264. rc = 1;
  19265. }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
  19266. raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
  19267. p->lineno, azArg[1]);
  19268. exit(1);
  19269. }else{
  19270. p->bSafeMode = 0;
  19271. return 0; /* Return immediately to bypass the safe mode reset
  19272. ** at the end of this procedure */
  19273. }
  19274. }else
  19275. if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
  19276. if( nArg==2 ){
  19277. sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
  19278. "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
  19279. }else{
  19280. raw_printf(stderr, "Usage: .nullvalue STRING\n");
  19281. rc = 1;
  19282. }
  19283. }else
  19284. if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
  19285. const char *zFN = 0; /* Pointer to constant filename */
  19286. char *zNewFilename = 0; /* Name of the database file to open */
  19287. int iName = 1; /* Index in azArg[] of the filename */
  19288. int newFlag = 0; /* True to delete file before opening */
  19289. int openMode = SHELL_OPEN_UNSPEC;
  19290. /* Check for command-line arguments */
  19291. for(iName=1; iName<nArg; iName++){
  19292. const char *z = azArg[iName];
  19293. if( optionMatch(z,"new") ){
  19294. newFlag = 1;
  19295. #ifdef SQLITE_HAVE_ZLIB
  19296. }else if( optionMatch(z, "zip") ){
  19297. openMode = SHELL_OPEN_ZIPFILE;
  19298. #endif
  19299. }else if( optionMatch(z, "append") ){
  19300. openMode = SHELL_OPEN_APPENDVFS;
  19301. }else if( optionMatch(z, "readonly") ){
  19302. openMode = SHELL_OPEN_READONLY;
  19303. }else if( optionMatch(z, "nofollow") ){
  19304. p->openFlags |= SQLITE_OPEN_NOFOLLOW;
  19305. #ifndef SQLITE_OMIT_DESERIALIZE
  19306. }else if( optionMatch(z, "deserialize") ){
  19307. openMode = SHELL_OPEN_DESERIALIZE;
  19308. }else if( optionMatch(z, "hexdb") ){
  19309. openMode = SHELL_OPEN_HEXDB;
  19310. }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
  19311. p->szMax = integerValue(azArg[++iName]);
  19312. #endif /* SQLITE_OMIT_DESERIALIZE */
  19313. }else if( z[0]=='-' ){
  19314. utf8_printf(stderr, "unknown option: %s\n", z);
  19315. rc = 1;
  19316. goto meta_command_exit;
  19317. }else if( zFN ){
  19318. utf8_printf(stderr, "extra argument: \"%s\"\n", z);
  19319. rc = 1;
  19320. goto meta_command_exit;
  19321. }else{
  19322. zFN = z;
  19323. }
  19324. }
  19325. /* Close the existing database */
  19326. session_close_all(p, -1);
  19327. close_db(p->db);
  19328. p->db = 0;
  19329. p->pAuxDb->zDbFilename = 0;
  19330. sqlite3_free(p->pAuxDb->zFreeOnClose);
  19331. p->pAuxDb->zFreeOnClose = 0;
  19332. p->openMode = openMode;
  19333. p->openFlags = 0;
  19334. p->szMax = 0;
  19335. /* If a filename is specified, try to open it first */
  19336. if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
  19337. if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
  19338. if( p->bSafeMode
  19339. && p->openMode!=SHELL_OPEN_HEXDB
  19340. && zFN
  19341. && strcmp(zFN,":memory:")!=0
  19342. ){
  19343. failIfSafeMode(p, "cannot open disk-based database files in safe mode");
  19344. }
  19345. if( zFN ){
  19346. zNewFilename = sqlite3_mprintf("%s", zFN);
  19347. shell_check_oom(zNewFilename);
  19348. }else{
  19349. zNewFilename = 0;
  19350. }
  19351. p->pAuxDb->zDbFilename = zNewFilename;
  19352. open_db(p, OPEN_DB_KEEPALIVE);
  19353. if( p->db==0 ){
  19354. utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
  19355. sqlite3_free(zNewFilename);
  19356. }else{
  19357. p->pAuxDb->zFreeOnClose = zNewFilename;
  19358. }
  19359. }
  19360. if( p->db==0 ){
  19361. /* As a fall-back open a TEMP database */
  19362. p->pAuxDb->zDbFilename = 0;
  19363. open_db(p, 0);
  19364. }
  19365. }else
  19366. if( (c=='o'
  19367. && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
  19368. || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
  19369. ){
  19370. char *zFile = 0;
  19371. int bTxtMode = 0;
  19372. int i;
  19373. int eMode = 0;
  19374. int bBOM = 0;
  19375. int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */
  19376. failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
  19377. if( c=='e' ){
  19378. eMode = 'x';
  19379. bOnce = 2;
  19380. }else if( strncmp(azArg[0],"once",n)==0 ){
  19381. bOnce = 1;
  19382. }
  19383. for(i=1; i<nArg; i++){
  19384. char *z = azArg[i];
  19385. if( z[0]=='-' ){
  19386. if( z[1]=='-' ) z++;
  19387. if( strcmp(z,"-bom")==0 ){
  19388. bBOM = 1;
  19389. }else if( c!='e' && strcmp(z,"-x")==0 ){
  19390. eMode = 'x'; /* spreadsheet */
  19391. }else if( c!='e' && strcmp(z,"-e")==0 ){
  19392. eMode = 'e'; /* text editor */
  19393. }else{
  19394. utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n",
  19395. azArg[i]);
  19396. showHelp(p->out, azArg[0]);
  19397. rc = 1;
  19398. goto meta_command_exit;
  19399. }
  19400. }else if( zFile==0 && eMode!='e' && eMode!='x' ){
  19401. zFile = sqlite3_mprintf("%s", z);
  19402. if( zFile && zFile[0]=='|' ){
  19403. while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
  19404. break;
  19405. }
  19406. }else{
  19407. utf8_printf(p->out,"ERROR: extra parameter: \"%s\". Usage:\n",
  19408. azArg[i]);
  19409. showHelp(p->out, azArg[0]);
  19410. rc = 1;
  19411. sqlite3_free(zFile);
  19412. goto meta_command_exit;
  19413. }
  19414. }
  19415. if( zFile==0 ){
  19416. zFile = sqlite3_mprintf("stdout");
  19417. }
  19418. if( bOnce ){
  19419. p->outCount = 2;
  19420. }else{
  19421. p->outCount = 0;
  19422. }
  19423. output_reset(p);
  19424. #ifndef SQLITE_NOHAVE_SYSTEM
  19425. if( eMode=='e' || eMode=='x' ){
  19426. p->doXdgOpen = 1;
  19427. outputModePush(p);
  19428. if( eMode=='x' ){
  19429. /* spreadsheet mode. Output as CSV. */
  19430. newTempFile(p, "csv");
  19431. ShellClearFlag(p, SHFLG_Echo);
  19432. p->mode = MODE_Csv;
  19433. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  19434. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  19435. }else{
  19436. /* text editor mode */
  19437. newTempFile(p, "txt");
  19438. bTxtMode = 1;
  19439. }
  19440. sqlite3_free(zFile);
  19441. zFile = sqlite3_mprintf("%s", p->zTempFile);
  19442. }
  19443. #endif /* SQLITE_NOHAVE_SYSTEM */
  19444. shell_check_oom(zFile);
  19445. if( zFile[0]=='|' ){
  19446. #ifdef SQLITE_OMIT_POPEN
  19447. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  19448. rc = 1;
  19449. p->out = stdout;
  19450. #else
  19451. p->out = popen(zFile + 1, "w");
  19452. if( p->out==0 ){
  19453. utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
  19454. p->out = stdout;
  19455. rc = 1;
  19456. }else{
  19457. if( bBOM ) fprintf(p->out,"\357\273\277");
  19458. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  19459. }
  19460. #endif
  19461. }else{
  19462. p->out = output_file_open(zFile, bTxtMode);
  19463. if( p->out==0 ){
  19464. if( strcmp(zFile,"off")!=0 ){
  19465. utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
  19466. }
  19467. p->out = stdout;
  19468. rc = 1;
  19469. } else {
  19470. if( bBOM ) fprintf(p->out,"\357\273\277");
  19471. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  19472. }
  19473. }
  19474. sqlite3_free(zFile);
  19475. }else
  19476. if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
  19477. open_db(p,0);
  19478. if( nArg<=1 ) goto parameter_syntax_error;
  19479. /* .parameter clear
  19480. ** Clear all bind parameters by dropping the TEMP table that holds them.
  19481. */
  19482. if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
  19483. sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
  19484. 0, 0, 0);
  19485. }else
  19486. /* .parameter list
  19487. ** List all bind parameters.
  19488. */
  19489. if( nArg==2 && strcmp(azArg[1],"list")==0 ){
  19490. sqlite3_stmt *pStmt = 0;
  19491. int rx;
  19492. int len = 0;
  19493. rx = sqlite3_prepare_v2(p->db,
  19494. "SELECT max(length(key)) "
  19495. "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
  19496. if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
  19497. len = sqlite3_column_int(pStmt, 0);
  19498. if( len>40 ) len = 40;
  19499. }
  19500. sqlite3_finalize(pStmt);
  19501. pStmt = 0;
  19502. if( len ){
  19503. rx = sqlite3_prepare_v2(p->db,
  19504. "SELECT key, quote(value) "
  19505. "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
  19506. while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
  19507. utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
  19508. sqlite3_column_text(pStmt,1));
  19509. }
  19510. sqlite3_finalize(pStmt);
  19511. }
  19512. }else
  19513. /* .parameter init
  19514. ** Make sure the TEMP table used to hold bind parameters exists.
  19515. ** Create it if necessary.
  19516. */
  19517. if( nArg==2 && strcmp(azArg[1],"init")==0 ){
  19518. bind_table_init(p);
  19519. }else
  19520. /* .parameter set NAME VALUE
  19521. ** Set or reset a bind parameter. NAME should be the full parameter
  19522. ** name exactly as it appears in the query. (ex: $abc, @def). The
  19523. ** VALUE can be in either SQL literal notation, or if not it will be
  19524. ** understood to be a text string.
  19525. */
  19526. if( nArg==4 && strcmp(azArg[1],"set")==0 ){
  19527. int rx;
  19528. char *zSql;
  19529. sqlite3_stmt *pStmt;
  19530. const char *zKey = azArg[2];
  19531. const char *zValue = azArg[3];
  19532. bind_table_init(p);
  19533. zSql = sqlite3_mprintf(
  19534. "REPLACE INTO temp.sqlite_parameters(key,value)"
  19535. "VALUES(%Q,%s);", zKey, zValue);
  19536. shell_check_oom(zSql);
  19537. pStmt = 0;
  19538. rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  19539. sqlite3_free(zSql);
  19540. if( rx!=SQLITE_OK ){
  19541. sqlite3_finalize(pStmt);
  19542. pStmt = 0;
  19543. zSql = sqlite3_mprintf(
  19544. "REPLACE INTO temp.sqlite_parameters(key,value)"
  19545. "VALUES(%Q,%Q);", zKey, zValue);
  19546. shell_check_oom(zSql);
  19547. rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  19548. sqlite3_free(zSql);
  19549. if( rx!=SQLITE_OK ){
  19550. utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
  19551. sqlite3_finalize(pStmt);
  19552. pStmt = 0;
  19553. rc = 1;
  19554. }
  19555. }
  19556. sqlite3_step(pStmt);
  19557. sqlite3_finalize(pStmt);
  19558. }else
  19559. /* .parameter unset NAME
  19560. ** Remove the NAME binding from the parameter binding table, if it
  19561. ** exists.
  19562. */
  19563. if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
  19564. char *zSql = sqlite3_mprintf(
  19565. "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
  19566. shell_check_oom(zSql);
  19567. sqlite3_exec(p->db, zSql, 0, 0, 0);
  19568. sqlite3_free(zSql);
  19569. }else
  19570. /* If no command name matches, show a syntax error */
  19571. parameter_syntax_error:
  19572. showHelp(p->out, "parameter");
  19573. }else
  19574. if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
  19575. int i;
  19576. for(i=1; i<nArg; i++){
  19577. if( i>1 ) raw_printf(p->out, " ");
  19578. utf8_printf(p->out, "%s", azArg[i]);
  19579. }
  19580. raw_printf(p->out, "\n");
  19581. }else
  19582. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  19583. if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
  19584. int i;
  19585. int nn = 0;
  19586. p->flgProgress = 0;
  19587. p->mxProgress = 0;
  19588. p->nProgress = 0;
  19589. for(i=1; i<nArg; i++){
  19590. const char *z = azArg[i];
  19591. if( z[0]=='-' ){
  19592. z++;
  19593. if( z[0]=='-' ) z++;
  19594. if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
  19595. p->flgProgress |= SHELL_PROGRESS_QUIET;
  19596. continue;
  19597. }
  19598. if( strcmp(z,"reset")==0 ){
  19599. p->flgProgress |= SHELL_PROGRESS_RESET;
  19600. continue;
  19601. }
  19602. if( strcmp(z,"once")==0 ){
  19603. p->flgProgress |= SHELL_PROGRESS_ONCE;
  19604. continue;
  19605. }
  19606. if( strcmp(z,"limit")==0 ){
  19607. if( i+1>=nArg ){
  19608. utf8_printf(stderr, "Error: missing argument on --limit\n");
  19609. rc = 1;
  19610. goto meta_command_exit;
  19611. }else{
  19612. p->mxProgress = (int)integerValue(azArg[++i]);
  19613. }
  19614. continue;
  19615. }
  19616. utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
  19617. rc = 1;
  19618. goto meta_command_exit;
  19619. }else{
  19620. nn = (int)integerValue(z);
  19621. }
  19622. }
  19623. open_db(p, 0);
  19624. sqlite3_progress_handler(p->db, nn, progress_handler, p);
  19625. }else
  19626. #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
  19627. if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
  19628. if( nArg >= 2) {
  19629. strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  19630. }
  19631. if( nArg >= 3) {
  19632. strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  19633. }
  19634. }else
  19635. if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
  19636. rc = 2;
  19637. }else
  19638. if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
  19639. FILE *inSaved = p->in;
  19640. int savedLineno = p->lineno;
  19641. failIfSafeMode(p, "cannot run .read in safe mode");
  19642. if( nArg!=2 ){
  19643. raw_printf(stderr, "Usage: .read FILE\n");
  19644. rc = 1;
  19645. goto meta_command_exit;
  19646. }
  19647. if( azArg[1][0]=='|' ){
  19648. #ifdef SQLITE_OMIT_POPEN
  19649. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  19650. rc = 1;
  19651. p->out = stdout;
  19652. #else
  19653. p->in = popen(azArg[1]+1, "r");
  19654. if( p->in==0 ){
  19655. utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  19656. rc = 1;
  19657. }else{
  19658. rc = process_input(p);
  19659. pclose(p->in);
  19660. }
  19661. #endif
  19662. }else if( (p->in = openChrSource(azArg[1]))==0 ){
  19663. utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
  19664. rc = 1;
  19665. }else{
  19666. rc = process_input(p);
  19667. fclose(p->in);
  19668. }
  19669. p->in = inSaved;
  19670. p->lineno = savedLineno;
  19671. }else
  19672. if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
  19673. const char *zSrcFile;
  19674. const char *zDb;
  19675. sqlite3 *pSrc;
  19676. sqlite3_backup *pBackup;
  19677. int nTimeout = 0;
  19678. failIfSafeMode(p, "cannot run .restore in safe mode");
  19679. if( nArg==2 ){
  19680. zSrcFile = azArg[1];
  19681. zDb = "main";
  19682. }else if( nArg==3 ){
  19683. zSrcFile = azArg[2];
  19684. zDb = azArg[1];
  19685. }else{
  19686. raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
  19687. rc = 1;
  19688. goto meta_command_exit;
  19689. }
  19690. rc = sqlite3_open(zSrcFile, &pSrc);
  19691. if( rc!=SQLITE_OK ){
  19692. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  19693. close_db(pSrc);
  19694. return 1;
  19695. }
  19696. open_db(p, 0);
  19697. pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  19698. if( pBackup==0 ){
  19699. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  19700. close_db(pSrc);
  19701. return 1;
  19702. }
  19703. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  19704. || rc==SQLITE_BUSY ){
  19705. if( rc==SQLITE_BUSY ){
  19706. if( nTimeout++ >= 3 ) break;
  19707. sqlite3_sleep(100);
  19708. }
  19709. }
  19710. sqlite3_backup_finish(pBackup);
  19711. if( rc==SQLITE_DONE ){
  19712. rc = 0;
  19713. }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  19714. raw_printf(stderr, "Error: source database is busy\n");
  19715. rc = 1;
  19716. }else{
  19717. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  19718. rc = 1;
  19719. }
  19720. close_db(pSrc);
  19721. }else
  19722. if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
  19723. if( nArg==2 ){
  19724. p->scanstatsOn = (u8)booleanValue(azArg[1]);
  19725. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  19726. raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
  19727. #endif
  19728. }else{
  19729. raw_printf(stderr, "Usage: .scanstats on|off\n");
  19730. rc = 1;
  19731. }
  19732. }else
  19733. if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
  19734. ShellText sSelect;
  19735. ShellState data;
  19736. char *zErrMsg = 0;
  19737. const char *zDiv = "(";
  19738. const char *zName = 0;
  19739. int iSchema = 0;
  19740. int bDebug = 0;
  19741. int bNoSystemTabs = 0;
  19742. int ii;
  19743. open_db(p, 0);
  19744. memcpy(&data, p, sizeof(data));
  19745. data.showHeader = 0;
  19746. data.cMode = data.mode = MODE_Semi;
  19747. initText(&sSelect);
  19748. for(ii=1; ii<nArg; ii++){
  19749. if( optionMatch(azArg[ii],"indent") ){
  19750. data.cMode = data.mode = MODE_Pretty;
  19751. }else if( optionMatch(azArg[ii],"debug") ){
  19752. bDebug = 1;
  19753. }else if( optionMatch(azArg[ii],"nosys") ){
  19754. bNoSystemTabs = 1;
  19755. }else if( azArg[ii][0]=='-' ){
  19756. utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
  19757. rc = 1;
  19758. goto meta_command_exit;
  19759. }else if( zName==0 ){
  19760. zName = azArg[ii];
  19761. }else{
  19762. raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
  19763. rc = 1;
  19764. goto meta_command_exit;
  19765. }
  19766. }
  19767. if( zName!=0 ){
  19768. int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
  19769. || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
  19770. || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
  19771. || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
  19772. if( isSchema ){
  19773. char *new_argv[2], *new_colv[2];
  19774. new_argv[0] = sqlite3_mprintf(
  19775. "CREATE TABLE %s (\n"
  19776. " type text,\n"
  19777. " name text,\n"
  19778. " tbl_name text,\n"
  19779. " rootpage integer,\n"
  19780. " sql text\n"
  19781. ")", zName);
  19782. shell_check_oom(new_argv[0]);
  19783. new_argv[1] = 0;
  19784. new_colv[0] = "sql";
  19785. new_colv[1] = 0;
  19786. callback(&data, 1, new_argv, new_colv);
  19787. sqlite3_free(new_argv[0]);
  19788. }
  19789. }
  19790. if( zDiv ){
  19791. sqlite3_stmt *pStmt = 0;
  19792. rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
  19793. -1, &pStmt, 0);
  19794. if( rc ){
  19795. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  19796. sqlite3_finalize(pStmt);
  19797. rc = 1;
  19798. goto meta_command_exit;
  19799. }
  19800. appendText(&sSelect, "SELECT sql FROM", 0);
  19801. iSchema = 0;
  19802. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  19803. const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
  19804. char zScNum[30];
  19805. sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
  19806. appendText(&sSelect, zDiv, 0);
  19807. zDiv = " UNION ALL ";
  19808. appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
  19809. if( sqlite3_stricmp(zDb, "main")!=0 ){
  19810. appendText(&sSelect, zDb, '\'');
  19811. }else{
  19812. appendText(&sSelect, "NULL", 0);
  19813. }
  19814. appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
  19815. appendText(&sSelect, zScNum, 0);
  19816. appendText(&sSelect, " AS snum, ", 0);
  19817. appendText(&sSelect, zDb, '\'');
  19818. appendText(&sSelect, " AS sname FROM ", 0);
  19819. appendText(&sSelect, zDb, quoteChar(zDb));
  19820. appendText(&sSelect, ".sqlite_schema", 0);
  19821. }
  19822. sqlite3_finalize(pStmt);
  19823. #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
  19824. if( zName ){
  19825. appendText(&sSelect,
  19826. " UNION ALL SELECT shell_module_schema(name),"
  19827. " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
  19828. 0);
  19829. }
  19830. #endif
  19831. appendText(&sSelect, ") WHERE ", 0);
  19832. if( zName ){
  19833. char *zQarg = sqlite3_mprintf("%Q", zName);
  19834. int bGlob;
  19835. shell_check_oom(zQarg);
  19836. bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
  19837. strchr(zName, '[') != 0;
  19838. if( strchr(zName, '.') ){
  19839. appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
  19840. }else{
  19841. appendText(&sSelect, "lower(tbl_name)", 0);
  19842. }
  19843. appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
  19844. appendText(&sSelect, zQarg, 0);
  19845. if( !bGlob ){
  19846. appendText(&sSelect, " ESCAPE '\\' ", 0);
  19847. }
  19848. appendText(&sSelect, " AND ", 0);
  19849. sqlite3_free(zQarg);
  19850. }
  19851. if( bNoSystemTabs ){
  19852. appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
  19853. }
  19854. appendText(&sSelect, "sql IS NOT NULL"
  19855. " ORDER BY snum, rowid", 0);
  19856. if( bDebug ){
  19857. utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
  19858. }else{
  19859. rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
  19860. }
  19861. freeText(&sSelect);
  19862. }
  19863. if( zErrMsg ){
  19864. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  19865. sqlite3_free(zErrMsg);
  19866. rc = 1;
  19867. }else if( rc != SQLITE_OK ){
  19868. raw_printf(stderr,"Error: querying schema information\n");
  19869. rc = 1;
  19870. }else{
  19871. rc = 0;
  19872. }
  19873. }else
  19874. if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
  19875. unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
  19876. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
  19877. }else
  19878. #if defined(SQLITE_ENABLE_SESSION)
  19879. if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
  19880. struct AuxDb *pAuxDb = p->pAuxDb;
  19881. OpenSession *pSession = &pAuxDb->aSession[0];
  19882. char **azCmd = &azArg[1];
  19883. int iSes = 0;
  19884. int nCmd = nArg - 1;
  19885. int i;
  19886. if( nArg<=1 ) goto session_syntax_error;
  19887. open_db(p, 0);
  19888. if( nArg>=3 ){
  19889. for(iSes=0; iSes<pAuxDb->nSession; iSes++){
  19890. if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
  19891. }
  19892. if( iSes<pAuxDb->nSession ){
  19893. pSession = &pAuxDb->aSession[iSes];
  19894. azCmd++;
  19895. nCmd--;
  19896. }else{
  19897. pSession = &pAuxDb->aSession[0];
  19898. iSes = 0;
  19899. }
  19900. }
  19901. /* .session attach TABLE
  19902. ** Invoke the sqlite3session_attach() interface to attach a particular
  19903. ** table so that it is never filtered.
  19904. */
  19905. if( strcmp(azCmd[0],"attach")==0 ){
  19906. if( nCmd!=2 ) goto session_syntax_error;
  19907. if( pSession->p==0 ){
  19908. session_not_open:
  19909. raw_printf(stderr, "ERROR: No sessions are open\n");
  19910. }else{
  19911. rc = sqlite3session_attach(pSession->p, azCmd[1]);
  19912. if( rc ){
  19913. raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
  19914. rc = 0;
  19915. }
  19916. }
  19917. }else
  19918. /* .session changeset FILE
  19919. ** .session patchset FILE
  19920. ** Write a changeset or patchset into a file. The file is overwritten.
  19921. */
  19922. if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
  19923. FILE *out = 0;
  19924. failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
  19925. if( nCmd!=2 ) goto session_syntax_error;
  19926. if( pSession->p==0 ) goto session_not_open;
  19927. out = fopen(azCmd[1], "wb");
  19928. if( out==0 ){
  19929. utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
  19930. azCmd[1]);
  19931. }else{
  19932. int szChng;
  19933. void *pChng;
  19934. if( azCmd[0][0]=='c' ){
  19935. rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
  19936. }else{
  19937. rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
  19938. }
  19939. if( rc ){
  19940. printf("Error: error code %d\n", rc);
  19941. rc = 0;
  19942. }
  19943. if( pChng
  19944. && fwrite(pChng, szChng, 1, out)!=1 ){
  19945. raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
  19946. szChng);
  19947. }
  19948. sqlite3_free(pChng);
  19949. fclose(out);
  19950. }
  19951. }else
  19952. /* .session close
  19953. ** Close the identified session
  19954. */
  19955. if( strcmp(azCmd[0], "close")==0 ){
  19956. if( nCmd!=1 ) goto session_syntax_error;
  19957. if( pAuxDb->nSession ){
  19958. session_close(pSession);
  19959. pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
  19960. }
  19961. }else
  19962. /* .session enable ?BOOLEAN?
  19963. ** Query or set the enable flag
  19964. */
  19965. if( strcmp(azCmd[0], "enable")==0 ){
  19966. int ii;
  19967. if( nCmd>2 ) goto session_syntax_error;
  19968. ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  19969. if( pAuxDb->nSession ){
  19970. ii = sqlite3session_enable(pSession->p, ii);
  19971. utf8_printf(p->out, "session %s enable flag = %d\n",
  19972. pSession->zName, ii);
  19973. }
  19974. }else
  19975. /* .session filter GLOB ....
  19976. ** Set a list of GLOB patterns of table names to be excluded.
  19977. */
  19978. if( strcmp(azCmd[0], "filter")==0 ){
  19979. int ii, nByte;
  19980. if( nCmd<2 ) goto session_syntax_error;
  19981. if( pAuxDb->nSession ){
  19982. for(ii=0; ii<pSession->nFilter; ii++){
  19983. sqlite3_free(pSession->azFilter[ii]);
  19984. }
  19985. sqlite3_free(pSession->azFilter);
  19986. nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
  19987. pSession->azFilter = sqlite3_malloc( nByte );
  19988. if( pSession->azFilter==0 ){
  19989. raw_printf(stderr, "Error: out or memory\n");
  19990. exit(1);
  19991. }
  19992. for(ii=1; ii<nCmd; ii++){
  19993. char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
  19994. shell_check_oom(x);
  19995. }
  19996. pSession->nFilter = ii-1;
  19997. }
  19998. }else
  19999. /* .session indirect ?BOOLEAN?
  20000. ** Query or set the indirect flag
  20001. */
  20002. if( strcmp(azCmd[0], "indirect")==0 ){
  20003. int ii;
  20004. if( nCmd>2 ) goto session_syntax_error;
  20005. ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  20006. if( pAuxDb->nSession ){
  20007. ii = sqlite3session_indirect(pSession->p, ii);
  20008. utf8_printf(p->out, "session %s indirect flag = %d\n",
  20009. pSession->zName, ii);
  20010. }
  20011. }else
  20012. /* .session isempty
  20013. ** Determine if the session is empty
  20014. */
  20015. if( strcmp(azCmd[0], "isempty")==0 ){
  20016. int ii;
  20017. if( nCmd!=1 ) goto session_syntax_error;
  20018. if( pAuxDb->nSession ){
  20019. ii = sqlite3session_isempty(pSession->p);
  20020. utf8_printf(p->out, "session %s isempty flag = %d\n",
  20021. pSession->zName, ii);
  20022. }
  20023. }else
  20024. /* .session list
  20025. ** List all currently open sessions
  20026. */
  20027. if( strcmp(azCmd[0],"list")==0 ){
  20028. for(i=0; i<pAuxDb->nSession; i++){
  20029. utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
  20030. }
  20031. }else
  20032. /* .session open DB NAME
  20033. ** Open a new session called NAME on the attached database DB.
  20034. ** DB is normally "main".
  20035. */
  20036. if( strcmp(azCmd[0],"open")==0 ){
  20037. char *zName;
  20038. if( nCmd!=3 ) goto session_syntax_error;
  20039. zName = azCmd[2];
  20040. if( zName[0]==0 ) goto session_syntax_error;
  20041. for(i=0; i<pAuxDb->nSession; i++){
  20042. if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
  20043. utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
  20044. goto meta_command_exit;
  20045. }
  20046. }
  20047. if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
  20048. raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
  20049. goto meta_command_exit;
  20050. }
  20051. pSession = &pAuxDb->aSession[pAuxDb->nSession];
  20052. rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
  20053. if( rc ){
  20054. raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
  20055. rc = 0;
  20056. goto meta_command_exit;
  20057. }
  20058. pSession->nFilter = 0;
  20059. sqlite3session_table_filter(pSession->p, session_filter, pSession);
  20060. pAuxDb->nSession++;
  20061. pSession->zName = sqlite3_mprintf("%s", zName);
  20062. shell_check_oom(pSession->zName);
  20063. }else
  20064. /* If no command name matches, show a syntax error */
  20065. session_syntax_error:
  20066. showHelp(p->out, "session");
  20067. }else
  20068. #endif
  20069. #ifdef SQLITE_DEBUG
  20070. /* Undocumented commands for internal testing. Subject to change
  20071. ** without notice. */
  20072. if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
  20073. if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
  20074. int i, v;
  20075. for(i=1; i<nArg; i++){
  20076. v = booleanValue(azArg[i]);
  20077. utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
  20078. }
  20079. }
  20080. if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
  20081. int i; sqlite3_int64 v;
  20082. for(i=1; i<nArg; i++){
  20083. char zBuf[200];
  20084. v = integerValue(azArg[i]);
  20085. sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
  20086. utf8_printf(p->out, "%s", zBuf);
  20087. }
  20088. }
  20089. }else
  20090. #endif
  20091. if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
  20092. int bIsInit = 0; /* True to initialize the SELFTEST table */
  20093. int bVerbose = 0; /* Verbose output */
  20094. int bSelftestExists; /* True if SELFTEST already exists */
  20095. int i, k; /* Loop counters */
  20096. int nTest = 0; /* Number of tests runs */
  20097. int nErr = 0; /* Number of errors seen */
  20098. ShellText str; /* Answer for a query */
  20099. sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
  20100. open_db(p,0);
  20101. for(i=1; i<nArg; i++){
  20102. const char *z = azArg[i];
  20103. if( z[0]=='-' && z[1]=='-' ) z++;
  20104. if( strcmp(z,"-init")==0 ){
  20105. bIsInit = 1;
  20106. }else
  20107. if( strcmp(z,"-v")==0 ){
  20108. bVerbose++;
  20109. }else
  20110. {
  20111. utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
  20112. azArg[i], azArg[0]);
  20113. raw_printf(stderr, "Should be one of: --init -v\n");
  20114. rc = 1;
  20115. goto meta_command_exit;
  20116. }
  20117. }
  20118. if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
  20119. != SQLITE_OK ){
  20120. bSelftestExists = 0;
  20121. }else{
  20122. bSelftestExists = 1;
  20123. }
  20124. if( bIsInit ){
  20125. createSelftestTable(p);
  20126. bSelftestExists = 1;
  20127. }
  20128. initText(&str);
  20129. appendText(&str, "x", 0);
  20130. for(k=bSelftestExists; k>=0; k--){
  20131. if( k==1 ){
  20132. rc = sqlite3_prepare_v2(p->db,
  20133. "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
  20134. -1, &pStmt, 0);
  20135. }else{
  20136. rc = sqlite3_prepare_v2(p->db,
  20137. "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
  20138. " (1,'run','PRAGMA integrity_check','ok')",
  20139. -1, &pStmt, 0);
  20140. }
  20141. if( rc ){
  20142. raw_printf(stderr, "Error querying the selftest table\n");
  20143. rc = 1;
  20144. sqlite3_finalize(pStmt);
  20145. goto meta_command_exit;
  20146. }
  20147. for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
  20148. int tno = sqlite3_column_int(pStmt, 0);
  20149. const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
  20150. const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
  20151. const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
  20152. if( zOp==0 ) continue;
  20153. if( zSql==0 ) continue;
  20154. if( zAns==0 ) continue;
  20155. k = 0;
  20156. if( bVerbose>0 ){
  20157. printf("%d: %s %s\n", tno, zOp, zSql);
  20158. }
  20159. if( strcmp(zOp,"memo")==0 ){
  20160. utf8_printf(p->out, "%s\n", zSql);
  20161. }else
  20162. if( strcmp(zOp,"run")==0 ){
  20163. char *zErrMsg = 0;
  20164. str.n = 0;
  20165. str.z[0] = 0;
  20166. rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
  20167. nTest++;
  20168. if( bVerbose ){
  20169. utf8_printf(p->out, "Result: %s\n", str.z);
  20170. }
  20171. if( rc || zErrMsg ){
  20172. nErr++;
  20173. rc = 1;
  20174. utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
  20175. sqlite3_free(zErrMsg);
  20176. }else if( strcmp(zAns,str.z)!=0 ){
  20177. nErr++;
  20178. rc = 1;
  20179. utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
  20180. utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
  20181. }
  20182. }else
  20183. {
  20184. utf8_printf(stderr,
  20185. "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
  20186. rc = 1;
  20187. break;
  20188. }
  20189. } /* End loop over rows of content from SELFTEST */
  20190. sqlite3_finalize(pStmt);
  20191. } /* End loop over k */
  20192. freeText(&str);
  20193. utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
  20194. }else
  20195. if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
  20196. if( nArg<2 || nArg>3 ){
  20197. raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
  20198. rc = 1;
  20199. }
  20200. if( nArg>=2 ){
  20201. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
  20202. "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
  20203. }
  20204. if( nArg>=3 ){
  20205. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
  20206. "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
  20207. }
  20208. }else
  20209. if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
  20210. const char *zLike = 0; /* Which table to checksum. 0 means everything */
  20211. int i; /* Loop counter */
  20212. int bSchema = 0; /* Also hash the schema */
  20213. int bSeparate = 0; /* Hash each table separately */
  20214. int iSize = 224; /* Hash algorithm to use */
  20215. int bDebug = 0; /* Only show the query that would have run */
  20216. sqlite3_stmt *pStmt; /* For querying tables names */
  20217. char *zSql; /* SQL to be run */
  20218. char *zSep; /* Separator */
  20219. ShellText sSql; /* Complete SQL for the query to run the hash */
  20220. ShellText sQuery; /* Set of queries used to read all content */
  20221. open_db(p, 0);
  20222. for(i=1; i<nArg; i++){
  20223. const char *z = azArg[i];
  20224. if( z[0]=='-' ){
  20225. z++;
  20226. if( z[0]=='-' ) z++;
  20227. if( strcmp(z,"schema")==0 ){
  20228. bSchema = 1;
  20229. }else
  20230. if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
  20231. || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
  20232. ){
  20233. iSize = atoi(&z[5]);
  20234. }else
  20235. if( strcmp(z,"debug")==0 ){
  20236. bDebug = 1;
  20237. }else
  20238. {
  20239. utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
  20240. azArg[i], azArg[0]);
  20241. showHelp(p->out, azArg[0]);
  20242. rc = 1;
  20243. goto meta_command_exit;
  20244. }
  20245. }else if( zLike ){
  20246. raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
  20247. rc = 1;
  20248. goto meta_command_exit;
  20249. }else{
  20250. zLike = z;
  20251. bSeparate = 1;
  20252. if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
  20253. }
  20254. }
  20255. if( bSchema ){
  20256. zSql = "SELECT lower(name) FROM sqlite_schema"
  20257. " WHERE type='table' AND coalesce(rootpage,0)>1"
  20258. " UNION ALL SELECT 'sqlite_schema'"
  20259. " ORDER BY 1 collate nocase";
  20260. }else{
  20261. zSql = "SELECT lower(name) FROM sqlite_schema"
  20262. " WHERE type='table' AND coalesce(rootpage,0)>1"
  20263. " AND name NOT LIKE 'sqlite_%'"
  20264. " ORDER BY 1 collate nocase";
  20265. }
  20266. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  20267. initText(&sQuery);
  20268. initText(&sSql);
  20269. appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
  20270. zSep = "VALUES(";
  20271. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  20272. const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
  20273. if( zTab==0 ) continue;
  20274. if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
  20275. if( strncmp(zTab, "sqlite_",7)!=0 ){
  20276. appendText(&sQuery,"SELECT * FROM ", 0);
  20277. appendText(&sQuery,zTab,'"');
  20278. appendText(&sQuery," NOT INDEXED;", 0);
  20279. }else if( strcmp(zTab, "sqlite_schema")==0 ){
  20280. appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
  20281. " ORDER BY name;", 0);
  20282. }else if( strcmp(zTab, "sqlite_sequence")==0 ){
  20283. appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
  20284. " ORDER BY name;", 0);
  20285. }else if( strcmp(zTab, "sqlite_stat1")==0 ){
  20286. appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
  20287. " ORDER BY tbl,idx;", 0);
  20288. }else if( strcmp(zTab, "sqlite_stat4")==0 ){
  20289. appendText(&sQuery, "SELECT * FROM ", 0);
  20290. appendText(&sQuery, zTab, 0);
  20291. appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
  20292. }
  20293. appendText(&sSql, zSep, 0);
  20294. appendText(&sSql, sQuery.z, '\'');
  20295. sQuery.n = 0;
  20296. appendText(&sSql, ",", 0);
  20297. appendText(&sSql, zTab, '\'');
  20298. zSep = "),(";
  20299. }
  20300. sqlite3_finalize(pStmt);
  20301. if( bSeparate ){
  20302. zSql = sqlite3_mprintf(
  20303. "%s))"
  20304. " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
  20305. " FROM [sha3sum$query]",
  20306. sSql.z, iSize);
  20307. }else{
  20308. zSql = sqlite3_mprintf(
  20309. "%s))"
  20310. " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
  20311. " FROM [sha3sum$query]",
  20312. sSql.z, iSize);
  20313. }
  20314. shell_check_oom(zSql);
  20315. freeText(&sQuery);
  20316. freeText(&sSql);
  20317. if( bDebug ){
  20318. utf8_printf(p->out, "%s\n", zSql);
  20319. }else{
  20320. shell_exec(p, zSql, 0);
  20321. }
  20322. sqlite3_free(zSql);
  20323. }else
  20324. #ifndef SQLITE_NOHAVE_SYSTEM
  20325. if( c=='s'
  20326. && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
  20327. ){
  20328. char *zCmd;
  20329. int i, x;
  20330. failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
  20331. if( nArg<2 ){
  20332. raw_printf(stderr, "Usage: .system COMMAND\n");
  20333. rc = 1;
  20334. goto meta_command_exit;
  20335. }
  20336. zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
  20337. for(i=2; i<nArg && zCmd!=0; i++){
  20338. zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
  20339. zCmd, azArg[i]);
  20340. }
  20341. x = zCmd!=0 ? system(zCmd) : 1;
  20342. sqlite3_free(zCmd);
  20343. if( x ) raw_printf(stderr, "System command returns %d\n", x);
  20344. }else
  20345. #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
  20346. if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
  20347. static const char *azBool[] = { "off", "on", "trigger", "full"};
  20348. const char *zOut;
  20349. int i;
  20350. if( nArg!=1 ){
  20351. raw_printf(stderr, "Usage: .show\n");
  20352. rc = 1;
  20353. goto meta_command_exit;
  20354. }
  20355. utf8_printf(p->out, "%12.12s: %s\n","echo",
  20356. azBool[ShellHasFlag(p, SHFLG_Echo)]);
  20357. utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
  20358. utf8_printf(p->out, "%12.12s: %s\n","explain",
  20359. p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
  20360. utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
  20361. if( p->mode==MODE_Column
  20362. || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
  20363. ){
  20364. utf8_printf
  20365. (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
  20366. modeDescr[p->mode], p->cmOpts.iWrap,
  20367. p->cmOpts.bWordWrap ? "on" : "off",
  20368. p->cmOpts.bQuote ? "" : "no");
  20369. }else{
  20370. utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
  20371. }
  20372. utf8_printf(p->out, "%12.12s: ", "nullvalue");
  20373. output_c_string(p->out, p->nullValue);
  20374. raw_printf(p->out, "\n");
  20375. utf8_printf(p->out,"%12.12s: %s\n","output",
  20376. strlen30(p->outfile) ? p->outfile : "stdout");
  20377. utf8_printf(p->out,"%12.12s: ", "colseparator");
  20378. output_c_string(p->out, p->colSeparator);
  20379. raw_printf(p->out, "\n");
  20380. utf8_printf(p->out,"%12.12s: ", "rowseparator");
  20381. output_c_string(p->out, p->rowSeparator);
  20382. raw_printf(p->out, "\n");
  20383. switch( p->statsOn ){
  20384. case 0: zOut = "off"; break;
  20385. default: zOut = "on"; break;
  20386. case 2: zOut = "stmt"; break;
  20387. case 3: zOut = "vmstep"; break;
  20388. }
  20389. utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
  20390. utf8_printf(p->out, "%12.12s: ", "width");
  20391. for (i=0;i<p->nWidth;i++) {
  20392. raw_printf(p->out, "%d ", p->colWidth[i]);
  20393. }
  20394. raw_printf(p->out, "\n");
  20395. utf8_printf(p->out, "%12.12s: %s\n", "filename",
  20396. p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
  20397. }else
  20398. if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
  20399. if( nArg==2 ){
  20400. if( strcmp(azArg[1],"stmt")==0 ){
  20401. p->statsOn = 2;
  20402. }else if( strcmp(azArg[1],"vmstep")==0 ){
  20403. p->statsOn = 3;
  20404. }else{
  20405. p->statsOn = (u8)booleanValue(azArg[1]);
  20406. }
  20407. }else if( nArg==1 ){
  20408. display_stats(p->db, p, 0);
  20409. }else{
  20410. raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
  20411. rc = 1;
  20412. }
  20413. }else
  20414. if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
  20415. || (c=='i' && (strncmp(azArg[0], "indices", n)==0
  20416. || strncmp(azArg[0], "indexes", n)==0) )
  20417. ){
  20418. sqlite3_stmt *pStmt;
  20419. char **azResult;
  20420. int nRow, nAlloc;
  20421. int ii;
  20422. ShellText s;
  20423. initText(&s);
  20424. open_db(p, 0);
  20425. rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
  20426. if( rc ){
  20427. sqlite3_finalize(pStmt);
  20428. return shellDatabaseError(p->db);
  20429. }
  20430. if( nArg>2 && c=='i' ){
  20431. /* It is an historical accident that the .indexes command shows an error
  20432. ** when called with the wrong number of arguments whereas the .tables
  20433. ** command does not. */
  20434. raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
  20435. rc = 1;
  20436. sqlite3_finalize(pStmt);
  20437. goto meta_command_exit;
  20438. }
  20439. for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
  20440. const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
  20441. if( zDbName==0 ) continue;
  20442. if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
  20443. if( sqlite3_stricmp(zDbName, "main")==0 ){
  20444. appendText(&s, "SELECT name FROM ", 0);
  20445. }else{
  20446. appendText(&s, "SELECT ", 0);
  20447. appendText(&s, zDbName, '\'');
  20448. appendText(&s, "||'.'||name FROM ", 0);
  20449. }
  20450. appendText(&s, zDbName, '"');
  20451. appendText(&s, ".sqlite_schema ", 0);
  20452. if( c=='t' ){
  20453. appendText(&s," WHERE type IN ('table','view')"
  20454. " AND name NOT LIKE 'sqlite_%'"
  20455. " AND name LIKE ?1", 0);
  20456. }else{
  20457. appendText(&s," WHERE type='index'"
  20458. " AND tbl_name LIKE ?1", 0);
  20459. }
  20460. }
  20461. rc = sqlite3_finalize(pStmt);
  20462. if( rc==SQLITE_OK ){
  20463. appendText(&s, " ORDER BY 1", 0);
  20464. rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
  20465. }
  20466. freeText(&s);
  20467. if( rc ) return shellDatabaseError(p->db);
  20468. /* Run the SQL statement prepared by the above block. Store the results
  20469. ** as an array of nul-terminated strings in azResult[]. */
  20470. nRow = nAlloc = 0;
  20471. azResult = 0;
  20472. if( nArg>1 ){
  20473. sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
  20474. }else{
  20475. sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
  20476. }
  20477. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  20478. if( nRow>=nAlloc ){
  20479. char **azNew;
  20480. int n2 = nAlloc*2 + 10;
  20481. azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
  20482. shell_check_oom(azNew);
  20483. nAlloc = n2;
  20484. azResult = azNew;
  20485. }
  20486. azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  20487. shell_check_oom(azResult[nRow]);
  20488. nRow++;
  20489. }
  20490. if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
  20491. rc = shellDatabaseError(p->db);
  20492. }
  20493. /* Pretty-print the contents of array azResult[] to the output */
  20494. if( rc==0 && nRow>0 ){
  20495. int len, maxlen = 0;
  20496. int i, j;
  20497. int nPrintCol, nPrintRow;
  20498. for(i=0; i<nRow; i++){
  20499. len = strlen30(azResult[i]);
  20500. if( len>maxlen ) maxlen = len;
  20501. }
  20502. nPrintCol = 80/(maxlen+2);
  20503. if( nPrintCol<1 ) nPrintCol = 1;
  20504. nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  20505. for(i=0; i<nPrintRow; i++){
  20506. for(j=i; j<nRow; j+=nPrintRow){
  20507. char *zSp = j<nPrintRow ? "" : " ";
  20508. utf8_printf(p->out, "%s%-*s", zSp, maxlen,
  20509. azResult[j] ? azResult[j]:"");
  20510. }
  20511. raw_printf(p->out, "\n");
  20512. }
  20513. }
  20514. for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
  20515. sqlite3_free(azResult);
  20516. }else
  20517. /* Begin redirecting output to the file "testcase-out.txt" */
  20518. if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
  20519. output_reset(p);
  20520. p->out = output_file_open("testcase-out.txt", 0);
  20521. if( p->out==0 ){
  20522. raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
  20523. }
  20524. if( nArg>=2 ){
  20525. sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
  20526. }else{
  20527. sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
  20528. }
  20529. }else
  20530. #ifndef SQLITE_UNTESTABLE
  20531. if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
  20532. static const struct {
  20533. const char *zCtrlName; /* Name of a test-control option */
  20534. int ctrlCode; /* Integer code for that option */
  20535. int unSafe; /* Not valid for --safe mode */
  20536. const char *zUsage; /* Usage notes */
  20537. } aCtrl[] = {
  20538. { "always", SQLITE_TESTCTRL_ALWAYS, 1, "BOOLEAN" },
  20539. { "assert", SQLITE_TESTCTRL_ASSERT, 1, "BOOLEAN" },
  20540. /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/
  20541. /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/
  20542. { "byteorder", SQLITE_TESTCTRL_BYTEORDER, 0, "" },
  20543. { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" },
  20544. /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/
  20545. { "imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
  20546. { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" },
  20547. { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" },
  20548. { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" },
  20549. { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" },
  20550. #ifdef YYCOVERAGE
  20551. { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" },
  20552. #endif
  20553. { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET " },
  20554. { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE,0, "" },
  20555. { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, 0, "" },
  20556. { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, 0, "SEED ?db?" },
  20557. { "seek_count", SQLITE_TESTCTRL_SEEK_COUNT, 0, "" },
  20558. { "sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX" },
  20559. { "tune", SQLITE_TESTCTRL_TUNE, 1, "ID VALUE" },
  20560. };
  20561. int testctrl = -1;
  20562. int iCtrl = -1;
  20563. int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
  20564. int isOk = 0;
  20565. int i, n2;
  20566. const char *zCmd = 0;
  20567. open_db(p, 0);
  20568. zCmd = nArg>=2 ? azArg[1] : "help";
  20569. /* The argument can optionally begin with "-" or "--" */
  20570. if( zCmd[0]=='-' && zCmd[1] ){
  20571. zCmd++;
  20572. if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
  20573. }
  20574. /* --help lists all test-controls */
  20575. if( strcmp(zCmd,"help")==0 ){
  20576. utf8_printf(p->out, "Available test-controls:\n");
  20577. for(i=0; i<ArraySize(aCtrl); i++){
  20578. utf8_printf(p->out, " .testctrl %s %s\n",
  20579. aCtrl[i].zCtrlName, aCtrl[i].zUsage);
  20580. }
  20581. rc = 1;
  20582. goto meta_command_exit;
  20583. }
  20584. /* convert testctrl text option to value. allow any unique prefix
  20585. ** of the option name, or a numerical value. */
  20586. n2 = strlen30(zCmd);
  20587. for(i=0; i<ArraySize(aCtrl); i++){
  20588. if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
  20589. if( testctrl<0 ){
  20590. testctrl = aCtrl[i].ctrlCode;
  20591. iCtrl = i;
  20592. }else{
  20593. utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
  20594. "Use \".testctrl --help\" for help\n", zCmd);
  20595. rc = 1;
  20596. goto meta_command_exit;
  20597. }
  20598. }
  20599. }
  20600. if( testctrl<0 ){
  20601. utf8_printf(stderr,"Error: unknown test-control: %s\n"
  20602. "Use \".testctrl --help\" for help\n", zCmd);
  20603. }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
  20604. utf8_printf(stderr,
  20605. "line %d: \".testctrl %s\" may not be used in safe mode\n",
  20606. p->lineno, aCtrl[iCtrl].zCtrlName);
  20607. exit(1);
  20608. }else{
  20609. switch(testctrl){
  20610. /* sqlite3_test_control(int, db, int) */
  20611. case SQLITE_TESTCTRL_OPTIMIZATIONS:
  20612. if( nArg==3 ){
  20613. unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
  20614. rc2 = sqlite3_test_control(testctrl, p->db, opt);
  20615. isOk = 3;
  20616. }
  20617. break;
  20618. /* sqlite3_test_control(int) */
  20619. case SQLITE_TESTCTRL_PRNG_SAVE:
  20620. case SQLITE_TESTCTRL_PRNG_RESTORE:
  20621. case SQLITE_TESTCTRL_BYTEORDER:
  20622. if( nArg==2 ){
  20623. rc2 = sqlite3_test_control(testctrl);
  20624. isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
  20625. }
  20626. break;
  20627. /* sqlite3_test_control(int, uint) */
  20628. case SQLITE_TESTCTRL_PENDING_BYTE:
  20629. if( nArg==3 ){
  20630. unsigned int opt = (unsigned int)integerValue(azArg[2]);
  20631. rc2 = sqlite3_test_control(testctrl, opt);
  20632. isOk = 3;
  20633. }
  20634. break;
  20635. /* sqlite3_test_control(int, int, sqlite3*) */
  20636. case SQLITE_TESTCTRL_PRNG_SEED:
  20637. if( nArg==3 || nArg==4 ){
  20638. int ii = (int)integerValue(azArg[2]);
  20639. sqlite3 *db;
  20640. if( ii==0 && strcmp(azArg[2],"random")==0 ){
  20641. sqlite3_randomness(sizeof(ii),&ii);
  20642. printf("-- random seed: %d\n", ii);
  20643. }
  20644. if( nArg==3 ){
  20645. db = 0;
  20646. }else{
  20647. db = p->db;
  20648. /* Make sure the schema has been loaded */
  20649. sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
  20650. }
  20651. rc2 = sqlite3_test_control(testctrl, ii, db);
  20652. isOk = 3;
  20653. }
  20654. break;
  20655. /* sqlite3_test_control(int, int) */
  20656. case SQLITE_TESTCTRL_ASSERT:
  20657. case SQLITE_TESTCTRL_ALWAYS:
  20658. if( nArg==3 ){
  20659. int opt = booleanValue(azArg[2]);
  20660. rc2 = sqlite3_test_control(testctrl, opt);
  20661. isOk = 1;
  20662. }
  20663. break;
  20664. /* sqlite3_test_control(int, int) */
  20665. case SQLITE_TESTCTRL_LOCALTIME_FAULT:
  20666. case SQLITE_TESTCTRL_NEVER_CORRUPT:
  20667. if( nArg==3 ){
  20668. int opt = booleanValue(azArg[2]);
  20669. rc2 = sqlite3_test_control(testctrl, opt);
  20670. isOk = 3;
  20671. }
  20672. break;
  20673. /* sqlite3_test_control(sqlite3*) */
  20674. case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
  20675. rc2 = sqlite3_test_control(testctrl, p->db);
  20676. isOk = 3;
  20677. break;
  20678. case SQLITE_TESTCTRL_IMPOSTER:
  20679. if( nArg==5 ){
  20680. rc2 = sqlite3_test_control(testctrl, p->db,
  20681. azArg[2],
  20682. integerValue(azArg[3]),
  20683. integerValue(azArg[4]));
  20684. isOk = 3;
  20685. }
  20686. break;
  20687. case SQLITE_TESTCTRL_SEEK_COUNT: {
  20688. u64 x = 0;
  20689. rc2 = sqlite3_test_control(testctrl, p->db, &x);
  20690. utf8_printf(p->out, "%llu\n", x);
  20691. isOk = 3;
  20692. break;
  20693. }
  20694. #ifdef YYCOVERAGE
  20695. case SQLITE_TESTCTRL_PARSER_COVERAGE: {
  20696. if( nArg==2 ){
  20697. sqlite3_test_control(testctrl, p->out);
  20698. isOk = 3;
  20699. }
  20700. break;
  20701. }
  20702. #endif
  20703. #ifdef SQLITE_DEBUG
  20704. case SQLITE_TESTCTRL_TUNE: {
  20705. if( nArg==4 ){
  20706. int id = (int)integerValue(azArg[2]);
  20707. int val = (int)integerValue(azArg[3]);
  20708. sqlite3_test_control(testctrl, id, &val);
  20709. isOk = 3;
  20710. }else if( nArg==3 ){
  20711. int id = (int)integerValue(azArg[2]);
  20712. sqlite3_test_control(testctrl, -id, &rc2);
  20713. isOk = 1;
  20714. }else if( nArg==2 ){
  20715. int id = 1;
  20716. while(1){
  20717. int val = 0;
  20718. rc2 = sqlite3_test_control(testctrl, -id, &val);
  20719. if( rc2!=SQLITE_OK ) break;
  20720. if( id>1 ) utf8_printf(p->out, " ");
  20721. utf8_printf(p->out, "%d: %d", id, val);
  20722. id++;
  20723. }
  20724. if( id>1 ) utf8_printf(p->out, "\n");
  20725. isOk = 3;
  20726. }
  20727. break;
  20728. }
  20729. #endif
  20730. case SQLITE_TESTCTRL_SORTER_MMAP:
  20731. if( nArg==3 ){
  20732. int opt = (unsigned int)integerValue(azArg[2]);
  20733. rc2 = sqlite3_test_control(testctrl, p->db, opt);
  20734. isOk = 3;
  20735. }
  20736. break;
  20737. }
  20738. }
  20739. if( isOk==0 && iCtrl>=0 ){
  20740. utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
  20741. rc = 1;
  20742. }else if( isOk==1 ){
  20743. raw_printf(p->out, "%d\n", rc2);
  20744. }else if( isOk==2 ){
  20745. raw_printf(p->out, "0x%08x\n", rc2);
  20746. }
  20747. }else
  20748. #endif /* !defined(SQLITE_UNTESTABLE) */
  20749. if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
  20750. open_db(p, 0);
  20751. sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
  20752. }else
  20753. if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
  20754. if( nArg==2 ){
  20755. enableTimer = booleanValue(azArg[1]);
  20756. if( enableTimer && !HAS_TIMER ){
  20757. raw_printf(stderr, "Error: timer not available on this system.\n");
  20758. enableTimer = 0;
  20759. }
  20760. }else{
  20761. raw_printf(stderr, "Usage: .timer on|off\n");
  20762. rc = 1;
  20763. }
  20764. }else
  20765. #ifndef SQLITE_OMIT_TRACE
  20766. if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
  20767. int mType = 0;
  20768. int jj;
  20769. open_db(p, 0);
  20770. for(jj=1; jj<nArg; jj++){
  20771. const char *z = azArg[jj];
  20772. if( z[0]=='-' ){
  20773. if( optionMatch(z, "expanded") ){
  20774. p->eTraceType = SHELL_TRACE_EXPANDED;
  20775. }
  20776. #ifdef SQLITE_ENABLE_NORMALIZE
  20777. else if( optionMatch(z, "normalized") ){
  20778. p->eTraceType = SHELL_TRACE_NORMALIZED;
  20779. }
  20780. #endif
  20781. else if( optionMatch(z, "plain") ){
  20782. p->eTraceType = SHELL_TRACE_PLAIN;
  20783. }
  20784. else if( optionMatch(z, "profile") ){
  20785. mType |= SQLITE_TRACE_PROFILE;
  20786. }
  20787. else if( optionMatch(z, "row") ){
  20788. mType |= SQLITE_TRACE_ROW;
  20789. }
  20790. else if( optionMatch(z, "stmt") ){
  20791. mType |= SQLITE_TRACE_STMT;
  20792. }
  20793. else if( optionMatch(z, "close") ){
  20794. mType |= SQLITE_TRACE_CLOSE;
  20795. }
  20796. else {
  20797. raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
  20798. rc = 1;
  20799. goto meta_command_exit;
  20800. }
  20801. }else{
  20802. output_file_close(p->traceOut);
  20803. p->traceOut = output_file_open(azArg[1], 0);
  20804. }
  20805. }
  20806. if( p->traceOut==0 ){
  20807. sqlite3_trace_v2(p->db, 0, 0, 0);
  20808. }else{
  20809. if( mType==0 ) mType = SQLITE_TRACE_STMT;
  20810. sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
  20811. }
  20812. }else
  20813. #endif /* !defined(SQLITE_OMIT_TRACE) */
  20814. #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
  20815. if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
  20816. int ii;
  20817. int lenOpt;
  20818. char *zOpt;
  20819. if( nArg<2 ){
  20820. raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
  20821. rc = 1;
  20822. goto meta_command_exit;
  20823. }
  20824. open_db(p, 0);
  20825. zOpt = azArg[1];
  20826. if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
  20827. lenOpt = (int)strlen(zOpt);
  20828. if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
  20829. assert( azArg[nArg]==0 );
  20830. sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
  20831. }else{
  20832. for(ii=1; ii<nArg; ii++){
  20833. sqlite3_create_module(p->db, azArg[ii], 0, 0);
  20834. }
  20835. }
  20836. }else
  20837. #endif
  20838. #if SQLITE_USER_AUTHENTICATION
  20839. if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
  20840. if( nArg<2 ){
  20841. raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
  20842. rc = 1;
  20843. goto meta_command_exit;
  20844. }
  20845. open_db(p, 0);
  20846. if( strcmp(azArg[1],"login")==0 ){
  20847. if( nArg!=4 ){
  20848. raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
  20849. rc = 1;
  20850. goto meta_command_exit;
  20851. }
  20852. rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
  20853. strlen30(azArg[3]));
  20854. if( rc ){
  20855. utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
  20856. rc = 1;
  20857. }
  20858. }else if( strcmp(azArg[1],"add")==0 ){
  20859. if( nArg!=5 ){
  20860. raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
  20861. rc = 1;
  20862. goto meta_command_exit;
  20863. }
  20864. rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
  20865. booleanValue(azArg[4]));
  20866. if( rc ){
  20867. raw_printf(stderr, "User-Add failed: %d\n", rc);
  20868. rc = 1;
  20869. }
  20870. }else if( strcmp(azArg[1],"edit")==0 ){
  20871. if( nArg!=5 ){
  20872. raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
  20873. rc = 1;
  20874. goto meta_command_exit;
  20875. }
  20876. rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
  20877. booleanValue(azArg[4]));
  20878. if( rc ){
  20879. raw_printf(stderr, "User-Edit failed: %d\n", rc);
  20880. rc = 1;
  20881. }
  20882. }else if( strcmp(azArg[1],"delete")==0 ){
  20883. if( nArg!=3 ){
  20884. raw_printf(stderr, "Usage: .user delete USER\n");
  20885. rc = 1;
  20886. goto meta_command_exit;
  20887. }
  20888. rc = sqlite3_user_delete(p->db, azArg[2]);
  20889. if( rc ){
  20890. raw_printf(stderr, "User-Delete failed: %d\n", rc);
  20891. rc = 1;
  20892. }
  20893. }else{
  20894. raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
  20895. rc = 1;
  20896. goto meta_command_exit;
  20897. }
  20898. }else
  20899. #endif /* SQLITE_USER_AUTHENTICATION */
  20900. if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
  20901. utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
  20902. sqlite3_libversion(), sqlite3_sourceid());
  20903. #if SQLITE_HAVE_ZLIB
  20904. utf8_printf(p->out, "zlib version %s\n", zlibVersion());
  20905. #endif
  20906. #define CTIMEOPT_VAL_(opt) #opt
  20907. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  20908. #if defined(__clang__) && defined(__clang_major__)
  20909. utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
  20910. CTIMEOPT_VAL(__clang_minor__) "."
  20911. CTIMEOPT_VAL(__clang_patchlevel__) "\n");
  20912. #elif defined(_MSC_VER)
  20913. utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
  20914. #elif defined(__GNUC__) && defined(__VERSION__)
  20915. utf8_printf(p->out, "gcc-" __VERSION__ "\n");
  20916. #endif
  20917. }else
  20918. if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
  20919. const char *zDbName = nArg==2 ? azArg[1] : "main";
  20920. sqlite3_vfs *pVfs = 0;
  20921. if( p->db ){
  20922. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
  20923. if( pVfs ){
  20924. utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
  20925. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  20926. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  20927. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  20928. }
  20929. }
  20930. }else
  20931. if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
  20932. sqlite3_vfs *pVfs;
  20933. sqlite3_vfs *pCurrent = 0;
  20934. if( p->db ){
  20935. sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
  20936. }
  20937. for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
  20938. utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
  20939. pVfs==pCurrent ? " <--- CURRENT" : "");
  20940. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  20941. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  20942. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  20943. if( pVfs->pNext ){
  20944. raw_printf(p->out, "-----------------------------------\n");
  20945. }
  20946. }
  20947. }else
  20948. if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
  20949. const char *zDbName = nArg==2 ? azArg[1] : "main";
  20950. char *zVfsName = 0;
  20951. if( p->db ){
  20952. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
  20953. if( zVfsName ){
  20954. utf8_printf(p->out, "%s\n", zVfsName);
  20955. sqlite3_free(zVfsName);
  20956. }
  20957. }
  20958. }else
  20959. if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
  20960. unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
  20961. sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
  20962. }else
  20963. if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
  20964. int j;
  20965. assert( nArg<=ArraySize(azArg) );
  20966. p->nWidth = nArg-1;
  20967. p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
  20968. if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
  20969. if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
  20970. for(j=1; j<nArg; j++){
  20971. p->colWidth[j-1] = (int)integerValue(azArg[j]);
  20972. }
  20973. }else
  20974. {
  20975. utf8_printf(stderr, "Error: unknown command or invalid arguments: "
  20976. " \"%s\". Enter \".help\" for help\n", azArg[0]);
  20977. rc = 1;
  20978. }
  20979. meta_command_exit:
  20980. if( p->outCount ){
  20981. p->outCount--;
  20982. if( p->outCount==0 ) output_reset(p);
  20983. }
  20984. p->bSafeMode = p->bSafeModePersist;
  20985. return rc;
  20986. }
  20987. /* Line scan result and intermediate states (supporting scan resumption)
  20988. */
  20989. #ifndef CHAR_BIT
  20990. # define CHAR_BIT 8
  20991. #endif
  20992. typedef enum {
  20993. QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
  20994. QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
  20995. QSS_Start = 0
  20996. } QuickScanState;
  20997. #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
  20998. #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
  20999. #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
  21000. #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
  21001. #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
  21002. /*
  21003. ** Scan line for classification to guide shell's handling.
  21004. ** The scan is resumable for subsequent lines when prior
  21005. ** return values are passed as the 2nd argument.
  21006. */
  21007. static QuickScanState quickscan(char *zLine, QuickScanState qss){
  21008. char cin;
  21009. char cWait = (char)qss; /* intentional narrowing loss */
  21010. if( cWait==0 ){
  21011. PlainScan:
  21012. assert( cWait==0 );
  21013. while( (cin = *zLine++)!=0 ){
  21014. if( IsSpace(cin) )
  21015. continue;
  21016. switch (cin){
  21017. case '-':
  21018. if( *zLine!='-' )
  21019. break;
  21020. while((cin = *++zLine)!=0 )
  21021. if( cin=='\n')
  21022. goto PlainScan;
  21023. return qss;
  21024. case ';':
  21025. qss |= QSS_EndingSemi;
  21026. continue;
  21027. case '/':
  21028. if( *zLine=='*' ){
  21029. ++zLine;
  21030. cWait = '*';
  21031. qss = QSS_SETV(qss, cWait);
  21032. goto TermScan;
  21033. }
  21034. break;
  21035. case '[':
  21036. cin = ']';
  21037. /* fall thru */
  21038. case '`': case '\'': case '"':
  21039. cWait = cin;
  21040. qss = QSS_HasDark | cWait;
  21041. goto TermScan;
  21042. default:
  21043. break;
  21044. }
  21045. qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
  21046. }
  21047. }else{
  21048. TermScan:
  21049. while( (cin = *zLine++)!=0 ){
  21050. if( cin==cWait ){
  21051. switch( cWait ){
  21052. case '*':
  21053. if( *zLine != '/' )
  21054. continue;
  21055. ++zLine;
  21056. cWait = 0;
  21057. qss = QSS_SETV(qss, 0);
  21058. goto PlainScan;
  21059. case '`': case '\'': case '"':
  21060. if(*zLine==cWait){
  21061. ++zLine;
  21062. continue;
  21063. }
  21064. /* fall thru */
  21065. case ']':
  21066. cWait = 0;
  21067. qss = QSS_SETV(qss, 0);
  21068. goto PlainScan;
  21069. default: assert(0);
  21070. }
  21071. }
  21072. }
  21073. }
  21074. return qss;
  21075. }
  21076. /*
  21077. ** Return TRUE if the line typed in is an SQL command terminator other
  21078. ** than a semi-colon. The SQL Server style "go" command is understood
  21079. ** as is the Oracle "/".
  21080. */
  21081. static int line_is_command_terminator(char *zLine){
  21082. while( IsSpace(zLine[0]) ){ zLine++; };
  21083. if( zLine[0]=='/' )
  21084. zLine += 1; /* Oracle */
  21085. else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
  21086. zLine += 2; /* SQL Server */
  21087. else
  21088. return 0;
  21089. return quickscan(zLine,QSS_Start)==QSS_Start;
  21090. }
  21091. /*
  21092. ** We need a default sqlite3_complete() implementation to use in case
  21093. ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
  21094. ** any arbitrary text is a complete SQL statement. This is not very
  21095. ** user-friendly, but it does seem to work.
  21096. */
  21097. #ifdef SQLITE_OMIT_COMPLETE
  21098. #define sqlite3_complete(x) 1
  21099. #endif
  21100. /*
  21101. ** Return true if zSql is a complete SQL statement. Return false if it
  21102. ** ends in the middle of a string literal or C-style comment.
  21103. */
  21104. static int line_is_complete(char *zSql, int nSql){
  21105. int rc;
  21106. if( zSql==0 ) return 1;
  21107. zSql[nSql] = ';';
  21108. zSql[nSql+1] = 0;
  21109. rc = sqlite3_complete(zSql);
  21110. zSql[nSql] = 0;
  21111. return rc;
  21112. }
  21113. /*
  21114. ** Run a single line of SQL. Return the number of errors.
  21115. */
  21116. static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
  21117. int rc;
  21118. char *zErrMsg = 0;
  21119. open_db(p, 0);
  21120. if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
  21121. if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
  21122. BEGIN_TIMER;
  21123. rc = shell_exec(p, zSql, &zErrMsg);
  21124. END_TIMER;
  21125. if( rc || zErrMsg ){
  21126. char zPrefix[100];
  21127. const char *zErrorTail;
  21128. const char *zErrorType;
  21129. if( zErrMsg==0 ){
  21130. zErrorType = "Error";
  21131. zErrorTail = sqlite3_errmsg(p->db);
  21132. }else if( strncmp(zErrMsg, "in prepare, ",12)==0 ){
  21133. zErrorType = "Parse error";
  21134. zErrorTail = &zErrMsg[12];
  21135. }else if( strncmp(zErrMsg, "stepping, ", 10)==0 ){
  21136. zErrorType = "Runtime error";
  21137. zErrorTail = &zErrMsg[10];
  21138. }else{
  21139. zErrorType = "Error";
  21140. zErrorTail = zErrMsg;
  21141. }
  21142. if( in!=0 || !stdin_is_interactive ){
  21143. sqlite3_snprintf(sizeof(zPrefix), zPrefix,
  21144. "%s near line %d:", zErrorType, startline);
  21145. }else{
  21146. sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
  21147. }
  21148. utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
  21149. sqlite3_free(zErrMsg);
  21150. zErrMsg = 0;
  21151. return 1;
  21152. }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
  21153. char zLineBuf[2000];
  21154. sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
  21155. "changes: %lld total_changes: %lld",
  21156. sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
  21157. raw_printf(p->out, "%s\n", zLineBuf);
  21158. }
  21159. return 0;
  21160. }
  21161. /*
  21162. ** Read input from *in and process it. If *in==0 then input
  21163. ** is interactive - the user is typing it it. Otherwise, input
  21164. ** is coming from a file or device. A prompt is issued and history
  21165. ** is saved only if input is interactive. An interrupt signal will
  21166. ** cause this routine to exit immediately, unless input is interactive.
  21167. **
  21168. ** Return the number of errors.
  21169. */
  21170. static int process_input(ShellState *p){
  21171. char *zLine = 0; /* A single input line */
  21172. char *zSql = 0; /* Accumulated SQL text */
  21173. int nLine; /* Length of current line */
  21174. int nSql = 0; /* Bytes of zSql[] used */
  21175. int nAlloc = 0; /* Allocated zSql[] space */
  21176. int rc; /* Error code */
  21177. int errCnt = 0; /* Number of errors seen */
  21178. int startline = 0; /* Line number for start of current input */
  21179. QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
  21180. if( p->inputNesting==MAX_INPUT_NESTING ){
  21181. /* This will be more informative in a later version. */
  21182. utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
  21183. " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
  21184. return 1;
  21185. }
  21186. ++p->inputNesting;
  21187. p->lineno = 0;
  21188. while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
  21189. fflush(p->out);
  21190. zLine = one_input_line(p->in, zLine, nSql>0);
  21191. if( zLine==0 ){
  21192. /* End of input */
  21193. if( p->in==0 && stdin_is_interactive ) printf("\n");
  21194. break;
  21195. }
  21196. if( seenInterrupt ){
  21197. if( p->in!=0 ) break;
  21198. seenInterrupt = 0;
  21199. }
  21200. p->lineno++;
  21201. if( QSS_INPLAIN(qss)
  21202. && line_is_command_terminator(zLine)
  21203. && line_is_complete(zSql, nSql) ){
  21204. memcpy(zLine,";",2);
  21205. }
  21206. qss = quickscan(zLine, qss);
  21207. if( QSS_PLAINWHITE(qss) && nSql==0 ){
  21208. if( ShellHasFlag(p, SHFLG_Echo) )
  21209. printf("%s\n", zLine);
  21210. /* Just swallow single-line whitespace */
  21211. qss = QSS_Start;
  21212. continue;
  21213. }
  21214. if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
  21215. if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
  21216. if( zLine[0]=='.' ){
  21217. rc = do_meta_command(zLine, p);
  21218. if( rc==2 ){ /* exit requested */
  21219. break;
  21220. }else if( rc ){
  21221. errCnt++;
  21222. }
  21223. }
  21224. qss = QSS_Start;
  21225. continue;
  21226. }
  21227. /* No single-line dispositions remain; accumulate line(s). */
  21228. nLine = strlen30(zLine);
  21229. if( nSql+nLine+2>=nAlloc ){
  21230. /* Grow buffer by half-again increments when big. */
  21231. nAlloc = nSql+(nSql>>1)+nLine+100;
  21232. zSql = realloc(zSql, nAlloc);
  21233. shell_check_oom(zSql);
  21234. }
  21235. if( nSql==0 ){
  21236. int i;
  21237. for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
  21238. assert( nAlloc>0 && zSql!=0 );
  21239. memcpy(zSql, zLine+i, nLine+1-i);
  21240. startline = p->lineno;
  21241. nSql = nLine-i;
  21242. }else{
  21243. zSql[nSql++] = '\n';
  21244. memcpy(zSql+nSql, zLine, nLine+1);
  21245. nSql += nLine;
  21246. }
  21247. if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
  21248. errCnt += runOneSqlLine(p, zSql, p->in, startline);
  21249. nSql = 0;
  21250. if( p->outCount ){
  21251. output_reset(p);
  21252. p->outCount = 0;
  21253. }else{
  21254. clearTempFile(p);
  21255. }
  21256. p->bSafeMode = p->bSafeModePersist;
  21257. qss = QSS_Start;
  21258. }else if( nSql && QSS_PLAINWHITE(qss) ){
  21259. if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
  21260. nSql = 0;
  21261. qss = QSS_Start;
  21262. }
  21263. }
  21264. if( nSql ){
  21265. /* This may be incomplete. Let the SQL parser deal with that. */
  21266. errCnt += runOneSqlLine(p, zSql, p->in, startline);
  21267. }
  21268. free(zSql);
  21269. free(zLine);
  21270. --p->inputNesting;
  21271. return errCnt>0;
  21272. }
  21273. /*
  21274. ** Return a pathname which is the user's home directory. A
  21275. ** 0 return indicates an error of some kind.
  21276. */
  21277. static char *find_home_dir(int clearFlag){
  21278. static char *home_dir = NULL;
  21279. if( clearFlag ){
  21280. free(home_dir);
  21281. home_dir = 0;
  21282. return 0;
  21283. }
  21284. if( home_dir ) return home_dir;
  21285. #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
  21286. && !defined(__RTP__) && !defined(_WRS_KERNEL)
  21287. {
  21288. struct passwd *pwent;
  21289. uid_t uid = getuid();
  21290. if( (pwent=getpwuid(uid)) != NULL) {
  21291. home_dir = pwent->pw_dir;
  21292. }
  21293. }
  21294. #endif
  21295. #if defined(_WIN32_WCE)
  21296. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  21297. */
  21298. home_dir = "/";
  21299. #else
  21300. #if defined(_WIN32) || defined(WIN32)
  21301. if (!home_dir) {
  21302. home_dir = getenv("USERPROFILE");
  21303. }
  21304. #endif
  21305. if (!home_dir) {
  21306. home_dir = getenv("HOME");
  21307. }
  21308. #if defined(_WIN32) || defined(WIN32)
  21309. if (!home_dir) {
  21310. char *zDrive, *zPath;
  21311. int n;
  21312. zDrive = getenv("HOMEDRIVE");
  21313. zPath = getenv("HOMEPATH");
  21314. if( zDrive && zPath ){
  21315. n = strlen30(zDrive) + strlen30(zPath) + 1;
  21316. home_dir = malloc( n );
  21317. if( home_dir==0 ) return 0;
  21318. sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  21319. return home_dir;
  21320. }
  21321. home_dir = "c:\\";
  21322. }
  21323. #endif
  21324. #endif /* !_WIN32_WCE */
  21325. if( home_dir ){
  21326. int n = strlen30(home_dir) + 1;
  21327. char *z = malloc( n );
  21328. if( z ) memcpy(z, home_dir, n);
  21329. home_dir = z;
  21330. }
  21331. return home_dir;
  21332. }
  21333. /*
  21334. ** Read input from the file given by sqliterc_override. Or if that
  21335. ** parameter is NULL, take input from ~/.sqliterc
  21336. **
  21337. ** Returns the number of errors.
  21338. */
  21339. static void process_sqliterc(
  21340. ShellState *p, /* Configuration data */
  21341. const char *sqliterc_override /* Name of config file. NULL to use default */
  21342. ){
  21343. char *home_dir = NULL;
  21344. const char *sqliterc = sqliterc_override;
  21345. char *zBuf = 0;
  21346. FILE *inSaved = p->in;
  21347. int savedLineno = p->lineno;
  21348. if (sqliterc == NULL) {
  21349. home_dir = find_home_dir(0);
  21350. if( home_dir==0 ){
  21351. raw_printf(stderr, "-- warning: cannot find home directory;"
  21352. " cannot read ~/.sqliterc\n");
  21353. return;
  21354. }
  21355. zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
  21356. shell_check_oom(zBuf);
  21357. sqliterc = zBuf;
  21358. }
  21359. p->in = fopen(sqliterc,"rb");
  21360. if( p->in ){
  21361. if( stdin_is_interactive ){
  21362. utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
  21363. }
  21364. if( process_input(p) && bail_on_error ) exit(1);
  21365. fclose(p->in);
  21366. }else if( sqliterc_override!=0 ){
  21367. utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
  21368. if( bail_on_error ) exit(1);
  21369. }
  21370. p->in = inSaved;
  21371. p->lineno = savedLineno;
  21372. sqlite3_free(zBuf);
  21373. }
  21374. /*
  21375. ** Show available command line options
  21376. */
  21377. static const char zOptions[] =
  21378. #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
  21379. " -A ARGS... run \".archive ARGS\" and exit\n"
  21380. #endif
  21381. " -append append the database to the end of the file\n"
  21382. " -ascii set output mode to 'ascii'\n"
  21383. " -bail stop after hitting an error\n"
  21384. " -batch force batch I/O\n"
  21385. " -box set output mode to 'box'\n"
  21386. " -column set output mode to 'column'\n"
  21387. " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
  21388. " -csv set output mode to 'csv'\n"
  21389. #if !defined(SQLITE_OMIT_DESERIALIZE)
  21390. " -deserialize open the database using sqlite3_deserialize()\n"
  21391. #endif
  21392. " -echo print commands before execution\n"
  21393. " -init FILENAME read/process named file\n"
  21394. " -[no]header turn headers on or off\n"
  21395. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  21396. " -heap SIZE Size of heap for memsys3 or memsys5\n"
  21397. #endif
  21398. " -help show this message\n"
  21399. " -html set output mode to HTML\n"
  21400. " -interactive force interactive I/O\n"
  21401. " -json set output mode to 'json'\n"
  21402. " -line set output mode to 'line'\n"
  21403. " -list set output mode to 'list'\n"
  21404. " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
  21405. " -markdown set output mode to 'markdown'\n"
  21406. #if !defined(SQLITE_OMIT_DESERIALIZE)
  21407. " -maxsize N maximum size for a --deserialize database\n"
  21408. #endif
  21409. " -memtrace trace all memory allocations and deallocations\n"
  21410. " -mmap N default mmap size set to N\n"
  21411. #ifdef SQLITE_ENABLE_MULTIPLEX
  21412. " -multiplex enable the multiplexor VFS\n"
  21413. #endif
  21414. " -newline SEP set output row separator. Default: '\\n'\n"
  21415. " -nofollow refuse to open symbolic links to database files\n"
  21416. " -nonce STRING set the safe-mode escape nonce\n"
  21417. " -nullvalue TEXT set text string for NULL values. Default ''\n"
  21418. " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
  21419. " -quote set output mode to 'quote'\n"
  21420. " -readonly open the database read-only\n"
  21421. " -safe enable safe-mode\n"
  21422. " -separator SEP set output column separator. Default: '|'\n"
  21423. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  21424. " -sorterref SIZE sorter references threshold size\n"
  21425. #endif
  21426. " -stats print memory stats before each finalize\n"
  21427. " -table set output mode to 'table'\n"
  21428. " -tabs set output mode to 'tabs'\n"
  21429. " -version show SQLite version\n"
  21430. " -vfs NAME use NAME as the default VFS\n"
  21431. #ifdef SQLITE_ENABLE_VFSTRACE
  21432. " -vfstrace enable tracing of all VFS calls\n"
  21433. #endif
  21434. #ifdef SQLITE_HAVE_ZLIB
  21435. " -zip open the file as a ZIP Archive\n"
  21436. #endif
  21437. ;
  21438. static void usage(int showDetail){
  21439. utf8_printf(stderr,
  21440. "Usage: %s [OPTIONS] FILENAME [SQL]\n"
  21441. "FILENAME is the name of an SQLite database. A new database is created\n"
  21442. "if the file does not previously exist.\n", Argv0);
  21443. if( showDetail ){
  21444. utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
  21445. }else{
  21446. raw_printf(stderr, "Use the -help option for additional information\n");
  21447. }
  21448. exit(1);
  21449. }
  21450. /*
  21451. ** Internal check: Verify that the SQLite is uninitialized. Print a
  21452. ** error message if it is initialized.
  21453. */
  21454. static void verify_uninitialized(void){
  21455. if( sqlite3_config(-1)==SQLITE_MISUSE ){
  21456. utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
  21457. " initialization.\n");
  21458. }
  21459. }
  21460. /*
  21461. ** Initialize the state information in data
  21462. */
  21463. static void main_init(ShellState *data) {
  21464. memset(data, 0, sizeof(*data));
  21465. data->normalMode = data->cMode = data->mode = MODE_List;
  21466. data->autoExplain = 1;
  21467. data->pAuxDb = &data->aAuxDb[0];
  21468. memcpy(data->colSeparator,SEP_Column, 2);
  21469. memcpy(data->rowSeparator,SEP_Row, 2);
  21470. data->showHeader = 0;
  21471. data->shellFlgs = SHFLG_Lookaside;
  21472. verify_uninitialized();
  21473. sqlite3_config(SQLITE_CONFIG_URI, 1);
  21474. sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
  21475. sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
  21476. sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  21477. sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
  21478. }
  21479. /*
  21480. ** Output text to the console in a font that attracts extra attention.
  21481. */
  21482. #ifdef _WIN32
  21483. static void printBold(const char *zText){
  21484. #if !SQLITE_OS_WINRT
  21485. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  21486. CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
  21487. GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
  21488. SetConsoleTextAttribute(out,
  21489. FOREGROUND_RED|FOREGROUND_INTENSITY
  21490. );
  21491. #endif
  21492. printf("%s", zText);
  21493. #if !SQLITE_OS_WINRT
  21494. SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
  21495. #endif
  21496. }
  21497. #else
  21498. static void printBold(const char *zText){
  21499. printf("\033[1m%s\033[0m", zText);
  21500. }
  21501. #endif
  21502. /*
  21503. ** Get the argument to an --option. Throw an error and die if no argument
  21504. ** is available.
  21505. */
  21506. static char *cmdline_option_value(int argc, char **argv, int i){
  21507. if( i==argc ){
  21508. utf8_printf(stderr, "%s: Error: missing argument to %s\n",
  21509. argv[0], argv[argc-1]);
  21510. exit(1);
  21511. }
  21512. return argv[i];
  21513. }
  21514. #ifndef SQLITE_SHELL_IS_UTF8
  21515. # if (defined(_WIN32) || defined(WIN32)) \
  21516. && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
  21517. # define SQLITE_SHELL_IS_UTF8 (0)
  21518. # else
  21519. # define SQLITE_SHELL_IS_UTF8 (1)
  21520. # endif
  21521. #endif
  21522. #if SQLITE_SHELL_IS_UTF8
  21523. int SQLITE_CDECL main(int argc, char **argv){
  21524. #else
  21525. int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
  21526. char **argv;
  21527. #endif
  21528. char *zErrMsg = 0;
  21529. ShellState data;
  21530. const char *zInitFile = 0;
  21531. int i;
  21532. int rc = 0;
  21533. int warnInmemoryDb = 0;
  21534. int readStdin = 1;
  21535. int nCmd = 0;
  21536. char **azCmd = 0;
  21537. const char *zVfs = 0; /* Value of -vfs command-line option */
  21538. #if !SQLITE_SHELL_IS_UTF8
  21539. char **argvToFree = 0;
  21540. int argcToFree = 0;
  21541. #endif
  21542. setBinaryMode(stdin, 0);
  21543. setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
  21544. stdin_is_interactive = isatty(0);
  21545. stdout_is_console = isatty(1);
  21546. #if !defined(_WIN32_WCE)
  21547. if( getenv("SQLITE_DEBUG_BREAK") ){
  21548. if( isatty(0) && isatty(2) ){
  21549. fprintf(stderr,
  21550. "attach debugger to process %d and press any key to continue.\n",
  21551. GETPID());
  21552. fgetc(stdin);
  21553. }else{
  21554. #if defined(_WIN32) || defined(WIN32)
  21555. #if SQLITE_OS_WINRT
  21556. __debugbreak();
  21557. #else
  21558. DebugBreak();
  21559. #endif
  21560. #elif defined(SIGTRAP)
  21561. raise(SIGTRAP);
  21562. #endif
  21563. }
  21564. }
  21565. #endif
  21566. #if USE_SYSTEM_SQLITE+0!=1
  21567. if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
  21568. utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
  21569. sqlite3_sourceid(), SQLITE_SOURCE_ID);
  21570. exit(1);
  21571. }
  21572. #endif
  21573. main_init(&data);
  21574. /* On Windows, we must translate command-line arguments into UTF-8.
  21575. ** The SQLite memory allocator subsystem has to be enabled in order to
  21576. ** do this. But we want to run an sqlite3_shutdown() afterwards so that
  21577. ** subsequent sqlite3_config() calls will work. So copy all results into
  21578. ** memory that does not come from the SQLite memory allocator.
  21579. */
  21580. #if !SQLITE_SHELL_IS_UTF8
  21581. sqlite3_initialize();
  21582. argvToFree = malloc(sizeof(argv[0])*argc*2);
  21583. shell_check_oom(argvToFree);
  21584. argcToFree = argc;
  21585. argv = argvToFree + argc;
  21586. for(i=0; i<argc; i++){
  21587. char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
  21588. int n;
  21589. shell_check_oom(z);
  21590. n = (int)strlen(z);
  21591. argv[i] = malloc( n+1 );
  21592. shell_check_oom(argv[i]);
  21593. memcpy(argv[i], z, n+1);
  21594. argvToFree[i] = argv[i];
  21595. sqlite3_free(z);
  21596. }
  21597. sqlite3_shutdown();
  21598. #endif
  21599. assert( argc>=1 && argv && argv[0] );
  21600. Argv0 = argv[0];
  21601. /* Make sure we have a valid signal handler early, before anything
  21602. ** else is done.
  21603. */
  21604. #ifdef SIGINT
  21605. signal(SIGINT, interrupt_handler);
  21606. #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
  21607. SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
  21608. #endif
  21609. #ifdef SQLITE_SHELL_DBNAME_PROC
  21610. {
  21611. /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
  21612. ** of a C-function that will provide the name of the database file. Use
  21613. ** this compile-time option to embed this shell program in larger
  21614. ** applications. */
  21615. extern void SQLITE_SHELL_DBNAME_PROC(const char**);
  21616. SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
  21617. warnInmemoryDb = 0;
  21618. }
  21619. #endif
  21620. /* Do an initial pass through the command-line argument to locate
  21621. ** the name of the database file, the name of the initialization file,
  21622. ** the size of the alternative malloc heap,
  21623. ** and the first command to execute.
  21624. */
  21625. verify_uninitialized();
  21626. for(i=1; i<argc; i++){
  21627. char *z;
  21628. z = argv[i];
  21629. if( z[0]!='-' ){
  21630. if( data.aAuxDb->zDbFilename==0 ){
  21631. data.aAuxDb->zDbFilename = z;
  21632. }else{
  21633. /* Excesss arguments are interpreted as SQL (or dot-commands) and
  21634. ** mean that nothing is read from stdin */
  21635. readStdin = 0;
  21636. nCmd++;
  21637. azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
  21638. shell_check_oom(azCmd);
  21639. azCmd[nCmd-1] = z;
  21640. }
  21641. }
  21642. if( z[1]=='-' ) z++;
  21643. if( strcmp(z,"-separator")==0
  21644. || strcmp(z,"-nullvalue")==0
  21645. || strcmp(z,"-newline")==0
  21646. || strcmp(z,"-cmd")==0
  21647. ){
  21648. (void)cmdline_option_value(argc, argv, ++i);
  21649. }else if( strcmp(z,"-init")==0 ){
  21650. zInitFile = cmdline_option_value(argc, argv, ++i);
  21651. }else if( strcmp(z,"-batch")==0 ){
  21652. /* Need to check for batch mode here to so we can avoid printing
  21653. ** informational messages (like from process_sqliterc) before
  21654. ** we do the actual processing of arguments later in a second pass.
  21655. */
  21656. stdin_is_interactive = 0;
  21657. }else if( strcmp(z,"-heap")==0 ){
  21658. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  21659. const char *zSize;
  21660. sqlite3_int64 szHeap;
  21661. zSize = cmdline_option_value(argc, argv, ++i);
  21662. szHeap = integerValue(zSize);
  21663. if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
  21664. sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
  21665. #else
  21666. (void)cmdline_option_value(argc, argv, ++i);
  21667. #endif
  21668. }else if( strcmp(z,"-pagecache")==0 ){
  21669. sqlite3_int64 n, sz;
  21670. sz = integerValue(cmdline_option_value(argc,argv,++i));
  21671. if( sz>70000 ) sz = 70000;
  21672. if( sz<0 ) sz = 0;
  21673. n = integerValue(cmdline_option_value(argc,argv,++i));
  21674. if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
  21675. n = 0xffffffffffffLL/sz;
  21676. }
  21677. sqlite3_config(SQLITE_CONFIG_PAGECACHE,
  21678. (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
  21679. data.shellFlgs |= SHFLG_Pagecache;
  21680. }else if( strcmp(z,"-lookaside")==0 ){
  21681. int n, sz;
  21682. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  21683. if( sz<0 ) sz = 0;
  21684. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  21685. if( n<0 ) n = 0;
  21686. sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
  21687. if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
  21688. }else if( strcmp(z,"-threadsafe")==0 ){
  21689. int n;
  21690. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  21691. switch( n ){
  21692. case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); break;
  21693. case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD); break;
  21694. default: sqlite3_config(SQLITE_CONFIG_SERIALIZED); break;
  21695. }
  21696. #ifdef SQLITE_ENABLE_VFSTRACE
  21697. }else if( strcmp(z,"-vfstrace")==0 ){
  21698. extern int vfstrace_register(
  21699. const char *zTraceName,
  21700. const char *zOldVfsName,
  21701. int (*xOut)(const char*,void*),
  21702. void *pOutArg,
  21703. int makeDefault
  21704. );
  21705. vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
  21706. #endif
  21707. #ifdef SQLITE_ENABLE_MULTIPLEX
  21708. }else if( strcmp(z,"-multiplex")==0 ){
  21709. extern int sqlite3_multiple_initialize(const char*,int);
  21710. sqlite3_multiplex_initialize(0, 1);
  21711. #endif
  21712. }else if( strcmp(z,"-mmap")==0 ){
  21713. sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  21714. sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
  21715. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  21716. }else if( strcmp(z,"-sorterref")==0 ){
  21717. sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  21718. sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
  21719. #endif
  21720. }else if( strcmp(z,"-vfs")==0 ){
  21721. zVfs = cmdline_option_value(argc, argv, ++i);
  21722. #ifdef SQLITE_HAVE_ZLIB
  21723. }else if( strcmp(z,"-zip")==0 ){
  21724. data.openMode = SHELL_OPEN_ZIPFILE;
  21725. #endif
  21726. }else if( strcmp(z,"-append")==0 ){
  21727. data.openMode = SHELL_OPEN_APPENDVFS;
  21728. #ifndef SQLITE_OMIT_DESERIALIZE
  21729. }else if( strcmp(z,"-deserialize")==0 ){
  21730. data.openMode = SHELL_OPEN_DESERIALIZE;
  21731. }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
  21732. data.szMax = integerValue(argv[++i]);
  21733. #endif
  21734. }else if( strcmp(z,"-readonly")==0 ){
  21735. data.openMode = SHELL_OPEN_READONLY;
  21736. }else if( strcmp(z,"-nofollow")==0 ){
  21737. data.openFlags = SQLITE_OPEN_NOFOLLOW;
  21738. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  21739. }else if( strncmp(z, "-A",2)==0 ){
  21740. /* All remaining command-line arguments are passed to the ".archive"
  21741. ** command, so ignore them */
  21742. break;
  21743. #endif
  21744. }else if( strcmp(z, "-memtrace")==0 ){
  21745. sqlite3MemTraceActivate(stderr);
  21746. }else if( strcmp(z,"-bail")==0 ){
  21747. bail_on_error = 1;
  21748. }else if( strcmp(z,"-nonce")==0 ){
  21749. free(data.zNonce);
  21750. data.zNonce = strdup(argv[++i]);
  21751. }else if( strcmp(z,"-safe")==0 ){
  21752. /* no-op - catch this on the second pass */
  21753. }
  21754. }
  21755. verify_uninitialized();
  21756. #ifdef SQLITE_SHELL_INIT_PROC
  21757. {
  21758. /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
  21759. ** of a C-function that will perform initialization actions on SQLite that
  21760. ** occur just before or after sqlite3_initialize(). Use this compile-time
  21761. ** option to embed this shell program in larger applications. */
  21762. extern void SQLITE_SHELL_INIT_PROC(void);
  21763. SQLITE_SHELL_INIT_PROC();
  21764. }
  21765. #else
  21766. /* All the sqlite3_config() calls have now been made. So it is safe
  21767. ** to call sqlite3_initialize() and process any command line -vfs option. */
  21768. sqlite3_initialize();
  21769. #endif
  21770. if( zVfs ){
  21771. sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
  21772. if( pVfs ){
  21773. sqlite3_vfs_register(pVfs, 1);
  21774. }else{
  21775. utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
  21776. exit(1);
  21777. }
  21778. }
  21779. if( data.pAuxDb->zDbFilename==0 ){
  21780. #ifndef SQLITE_OMIT_MEMORYDB
  21781. data.pAuxDb->zDbFilename = ":memory:";
  21782. warnInmemoryDb = argc==1;
  21783. #else
  21784. utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
  21785. return 1;
  21786. #endif
  21787. }
  21788. data.out = stdout;
  21789. sqlite3_appendvfs_init(0,0,0);
  21790. /* Go ahead and open the database file if it already exists. If the
  21791. ** file does not exist, delay opening it. This prevents empty database
  21792. ** files from being created if a user mistypes the database name argument
  21793. ** to the sqlite command-line tool.
  21794. */
  21795. if( access(data.pAuxDb->zDbFilename, 0)==0 ){
  21796. open_db(&data, 0);
  21797. }
  21798. /* Process the initialization file if there is one. If no -init option
  21799. ** is given on the command line, look for a file named ~/.sqliterc and
  21800. ** try to process it.
  21801. */
  21802. process_sqliterc(&data,zInitFile);
  21803. /* Make a second pass through the command-line argument and set
  21804. ** options. This second pass is delayed until after the initialization
  21805. ** file is processed so that the command-line arguments will override
  21806. ** settings in the initialization file.
  21807. */
  21808. for(i=1; i<argc; i++){
  21809. char *z = argv[i];
  21810. if( z[0]!='-' ) continue;
  21811. if( z[1]=='-' ){ z++; }
  21812. if( strcmp(z,"-init")==0 ){
  21813. i++;
  21814. }else if( strcmp(z,"-html")==0 ){
  21815. data.mode = MODE_Html;
  21816. }else if( strcmp(z,"-list")==0 ){
  21817. data.mode = MODE_List;
  21818. }else if( strcmp(z,"-quote")==0 ){
  21819. data.mode = MODE_Quote;
  21820. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
  21821. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
  21822. }else if( strcmp(z,"-line")==0 ){
  21823. data.mode = MODE_Line;
  21824. }else if( strcmp(z,"-column")==0 ){
  21825. data.mode = MODE_Column;
  21826. }else if( strcmp(z,"-json")==0 ){
  21827. data.mode = MODE_Json;
  21828. }else if( strcmp(z,"-markdown")==0 ){
  21829. data.mode = MODE_Markdown;
  21830. }else if( strcmp(z,"-table")==0 ){
  21831. data.mode = MODE_Table;
  21832. }else if( strcmp(z,"-box")==0 ){
  21833. data.mode = MODE_Box;
  21834. }else if( strcmp(z,"-csv")==0 ){
  21835. data.mode = MODE_Csv;
  21836. memcpy(data.colSeparator,",",2);
  21837. #ifdef SQLITE_HAVE_ZLIB
  21838. }else if( strcmp(z,"-zip")==0 ){
  21839. data.openMode = SHELL_OPEN_ZIPFILE;
  21840. #endif
  21841. }else if( strcmp(z,"-append")==0 ){
  21842. data.openMode = SHELL_OPEN_APPENDVFS;
  21843. #ifndef SQLITE_OMIT_DESERIALIZE
  21844. }else if( strcmp(z,"-deserialize")==0 ){
  21845. data.openMode = SHELL_OPEN_DESERIALIZE;
  21846. }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
  21847. data.szMax = integerValue(argv[++i]);
  21848. #endif
  21849. }else if( strcmp(z,"-readonly")==0 ){
  21850. data.openMode = SHELL_OPEN_READONLY;
  21851. }else if( strcmp(z,"-nofollow")==0 ){
  21852. data.openFlags |= SQLITE_OPEN_NOFOLLOW;
  21853. }else if( strcmp(z,"-ascii")==0 ){
  21854. data.mode = MODE_Ascii;
  21855. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
  21856. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
  21857. }else if( strcmp(z,"-tabs")==0 ){
  21858. data.mode = MODE_List;
  21859. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
  21860. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
  21861. }else if( strcmp(z,"-separator")==0 ){
  21862. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  21863. "%s",cmdline_option_value(argc,argv,++i));
  21864. }else if( strcmp(z,"-newline")==0 ){
  21865. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  21866. "%s",cmdline_option_value(argc,argv,++i));
  21867. }else if( strcmp(z,"-nullvalue")==0 ){
  21868. sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
  21869. "%s",cmdline_option_value(argc,argv,++i));
  21870. }else if( strcmp(z,"-header")==0 ){
  21871. data.showHeader = 1;
  21872. ShellSetFlag(&data, SHFLG_HeaderSet);
  21873. }else if( strcmp(z,"-noheader")==0 ){
  21874. data.showHeader = 0;
  21875. ShellSetFlag(&data, SHFLG_HeaderSet);
  21876. }else if( strcmp(z,"-echo")==0 ){
  21877. ShellSetFlag(&data, SHFLG_Echo);
  21878. }else if( strcmp(z,"-eqp")==0 ){
  21879. data.autoEQP = AUTOEQP_on;
  21880. }else if( strcmp(z,"-eqpfull")==0 ){
  21881. data.autoEQP = AUTOEQP_full;
  21882. }else if( strcmp(z,"-stats")==0 ){
  21883. data.statsOn = 1;
  21884. }else if( strcmp(z,"-scanstats")==0 ){
  21885. data.scanstatsOn = 1;
  21886. }else if( strcmp(z,"-backslash")==0 ){
  21887. /* Undocumented command-line option: -backslash
  21888. ** Causes C-style backslash escapes to be evaluated in SQL statements
  21889. ** prior to sending the SQL into SQLite. Useful for injecting
  21890. ** crazy bytes in the middle of SQL statements for testing and debugging.
  21891. */
  21892. ShellSetFlag(&data, SHFLG_Backslash);
  21893. }else if( strcmp(z,"-bail")==0 ){
  21894. /* No-op. The bail_on_error flag should already be set. */
  21895. }else if( strcmp(z,"-version")==0 ){
  21896. printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
  21897. return 0;
  21898. }else if( strcmp(z,"-interactive")==0 ){
  21899. stdin_is_interactive = 1;
  21900. }else if( strcmp(z,"-batch")==0 ){
  21901. stdin_is_interactive = 0;
  21902. }else if( strcmp(z,"-heap")==0 ){
  21903. i++;
  21904. }else if( strcmp(z,"-pagecache")==0 ){
  21905. i+=2;
  21906. }else if( strcmp(z,"-lookaside")==0 ){
  21907. i+=2;
  21908. }else if( strcmp(z,"-threadsafe")==0 ){
  21909. i+=2;
  21910. }else if( strcmp(z,"-nonce")==0 ){
  21911. i += 2;
  21912. }else if( strcmp(z,"-mmap")==0 ){
  21913. i++;
  21914. }else if( strcmp(z,"-memtrace")==0 ){
  21915. i++;
  21916. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  21917. }else if( strcmp(z,"-sorterref")==0 ){
  21918. i++;
  21919. #endif
  21920. }else if( strcmp(z,"-vfs")==0 ){
  21921. i++;
  21922. #ifdef SQLITE_ENABLE_VFSTRACE
  21923. }else if( strcmp(z,"-vfstrace")==0 ){
  21924. i++;
  21925. #endif
  21926. #ifdef SQLITE_ENABLE_MULTIPLEX
  21927. }else if( strcmp(z,"-multiplex")==0 ){
  21928. i++;
  21929. #endif
  21930. }else if( strcmp(z,"-help")==0 ){
  21931. usage(1);
  21932. }else if( strcmp(z,"-cmd")==0 ){
  21933. /* Run commands that follow -cmd first and separately from commands
  21934. ** that simply appear on the command-line. This seems goofy. It would
  21935. ** be better if all commands ran in the order that they appear. But
  21936. ** we retain the goofy behavior for historical compatibility. */
  21937. if( i==argc-1 ) break;
  21938. z = cmdline_option_value(argc,argv,++i);
  21939. if( z[0]=='.' ){
  21940. rc = do_meta_command(z, &data);
  21941. if( rc && bail_on_error ) return rc==2 ? 0 : rc;
  21942. }else{
  21943. open_db(&data, 0);
  21944. rc = shell_exec(&data, z, &zErrMsg);
  21945. if( zErrMsg!=0 ){
  21946. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  21947. if( bail_on_error ) return rc!=0 ? rc : 1;
  21948. }else if( rc!=0 ){
  21949. utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
  21950. if( bail_on_error ) return rc;
  21951. }
  21952. }
  21953. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  21954. }else if( strncmp(z, "-A", 2)==0 ){
  21955. if( nCmd>0 ){
  21956. utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
  21957. " with \"%s\"\n", z);
  21958. return 1;
  21959. }
  21960. open_db(&data, OPEN_DB_ZIPFILE);
  21961. if( z[2] ){
  21962. argv[i] = &z[2];
  21963. arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
  21964. }else{
  21965. arDotCommand(&data, 1, argv+i, argc-i);
  21966. }
  21967. readStdin = 0;
  21968. break;
  21969. #endif
  21970. }else if( strcmp(z,"-safe")==0 ){
  21971. data.bSafeMode = data.bSafeModePersist = 1;
  21972. }else{
  21973. utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
  21974. raw_printf(stderr,"Use -help for a list of options.\n");
  21975. return 1;
  21976. }
  21977. data.cMode = data.mode;
  21978. }
  21979. if( !readStdin ){
  21980. /* Run all arguments that do not begin with '-' as if they were separate
  21981. ** command-line inputs, except for the argToSkip argument which contains
  21982. ** the database filename.
  21983. */
  21984. for(i=0; i<nCmd; i++){
  21985. if( azCmd[i][0]=='.' ){
  21986. rc = do_meta_command(azCmd[i], &data);
  21987. if( rc ){
  21988. free(azCmd);
  21989. return rc==2 ? 0 : rc;
  21990. }
  21991. }else{
  21992. open_db(&data, 0);
  21993. rc = shell_exec(&data, azCmd[i], &zErrMsg);
  21994. if( zErrMsg || rc ){
  21995. if( zErrMsg!=0 ){
  21996. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  21997. }else{
  21998. utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
  21999. }
  22000. sqlite3_free(zErrMsg);
  22001. free(azCmd);
  22002. return rc!=0 ? rc : 1;
  22003. }
  22004. }
  22005. }
  22006. }else{
  22007. /* Run commands received from standard input
  22008. */
  22009. if( stdin_is_interactive ){
  22010. char *zHome;
  22011. char *zHistory;
  22012. int nHistory;
  22013. printf(
  22014. "SQLite version %s %.19s\n" /*extra-version-info*/
  22015. "Enter \".help\" for usage hints.\n",
  22016. sqlite3_libversion(), sqlite3_sourceid()
  22017. );
  22018. if( warnInmemoryDb ){
  22019. printf("Connected to a ");
  22020. printBold("transient in-memory database");
  22021. printf(".\nUse \".open FILENAME\" to reopen on a "
  22022. "persistent database.\n");
  22023. }
  22024. zHistory = getenv("SQLITE_HISTORY");
  22025. if( zHistory ){
  22026. zHistory = strdup(zHistory);
  22027. }else if( (zHome = find_home_dir(0))!=0 ){
  22028. nHistory = strlen30(zHome) + 20;
  22029. if( (zHistory = malloc(nHistory))!=0 ){
  22030. sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  22031. }
  22032. }
  22033. if( zHistory ){ shell_read_history(zHistory); }
  22034. #if HAVE_READLINE || HAVE_EDITLINE
  22035. rl_attempted_completion_function = readline_completion;
  22036. #elif HAVE_LINENOISE
  22037. linenoiseSetCompletionCallback(linenoise_completion);
  22038. #endif
  22039. data.in = 0;
  22040. rc = process_input(&data);
  22041. if( zHistory ){
  22042. shell_stifle_history(2000);
  22043. shell_write_history(zHistory);
  22044. free(zHistory);
  22045. }
  22046. }else{
  22047. data.in = stdin;
  22048. rc = process_input(&data);
  22049. }
  22050. }
  22051. free(azCmd);
  22052. set_table_name(&data, 0);
  22053. if( data.db ){
  22054. session_close_all(&data, -1);
  22055. close_db(data.db);
  22056. }
  22057. for(i=0; i<ArraySize(data.aAuxDb); i++){
  22058. sqlite3_free(data.aAuxDb[i].zFreeOnClose);
  22059. if( data.aAuxDb[i].db ){
  22060. session_close_all(&data, i);
  22061. close_db(data.aAuxDb[i].db);
  22062. }
  22063. }
  22064. find_home_dir(1);
  22065. output_reset(&data);
  22066. data.doXdgOpen = 0;
  22067. clearTempFile(&data);
  22068. #if !SQLITE_SHELL_IS_UTF8
  22069. for(i=0; i<argcToFree; i++) free(argvToFree[i]);
  22070. free(argvToFree);
  22071. #endif
  22072. free(data.colWidth);
  22073. free(data.zNonce);
  22074. /* Clear the global data structure so that valgrind will detect memory
  22075. ** leaks */
  22076. memset(&data, 0, sizeof(data));
  22077. return rc;
  22078. }