shell.c 260 KB

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