shell.c 239 KB

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