shell.c 156 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056
  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. /* On Windows, we normally run with output mode of TEXT so that \n characters
  120. ** are automatically translated into \r\n. However, this behavior needs
  121. ** to be disabled in some cases (ex: when generating CSV output and when
  122. ** rendering quoted strings that contain \n characters). The following
  123. ** routines take care of that.
  124. */
  125. #if defined(_WIN32) || defined(WIN32)
  126. static void setBinaryMode(FILE *out){
  127. fflush(out);
  128. _setmode(_fileno(out), _O_BINARY);
  129. }
  130. static void setTextMode(FILE *out){
  131. fflush(out);
  132. _setmode(_fileno(out), _O_TEXT);
  133. }
  134. #else
  135. # define setBinaryMode(X)
  136. # define setTextMode(X)
  137. #endif
  138. /* True if the timer is enabled */
  139. static int enableTimer = 0;
  140. /* Return the current wall-clock time */
  141. static sqlite3_int64 timeOfDay(void){
  142. static sqlite3_vfs *clockVfs = 0;
  143. sqlite3_int64 t;
  144. if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
  145. if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
  146. clockVfs->xCurrentTimeInt64(clockVfs, &t);
  147. }else{
  148. double r;
  149. clockVfs->xCurrentTime(clockVfs, &r);
  150. t = (sqlite3_int64)(r*86400000.0);
  151. }
  152. return t;
  153. }
  154. #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
  155. #include <sys/time.h>
  156. #include <sys/resource.h>
  157. /* VxWorks does not support getrusage() as far as we can determine */
  158. #if defined(_WRS_KERNEL) || defined(__RTP__)
  159. struct rusage {
  160. struct timeval ru_utime; /* user CPU time used */
  161. struct timeval ru_stime; /* system CPU time used */
  162. };
  163. #define getrusage(A,B) memset(B,0,sizeof(*B))
  164. #endif
  165. /* Saved resource information for the beginning of an operation */
  166. static struct rusage sBegin; /* CPU time at start */
  167. static sqlite3_int64 iBegin; /* Wall-clock time at start */
  168. /*
  169. ** Begin timing an operation
  170. */
  171. static void beginTimer(void){
  172. if( enableTimer ){
  173. getrusage(RUSAGE_SELF, &sBegin);
  174. iBegin = timeOfDay();
  175. }
  176. }
  177. /* Return the difference of two time_structs in seconds */
  178. static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  179. return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
  180. (double)(pEnd->tv_sec - pStart->tv_sec);
  181. }
  182. /*
  183. ** Print the timing results.
  184. */
  185. static void endTimer(void){
  186. if( enableTimer ){
  187. sqlite3_int64 iEnd = timeOfDay();
  188. struct rusage sEnd;
  189. getrusage(RUSAGE_SELF, &sEnd);
  190. printf("Run Time: real %.3f user %f sys %f\n",
  191. (iEnd - iBegin)*0.001,
  192. timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
  193. timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  194. }
  195. }
  196. #define BEGIN_TIMER beginTimer()
  197. #define END_TIMER endTimer()
  198. #define HAS_TIMER 1
  199. #elif (defined(_WIN32) || defined(WIN32))
  200. #include <windows.h>
  201. /* Saved resource information for the beginning of an operation */
  202. static HANDLE hProcess;
  203. static FILETIME ftKernelBegin;
  204. static FILETIME ftUserBegin;
  205. static sqlite3_int64 ftWallBegin;
  206. typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
  207. LPFILETIME, LPFILETIME);
  208. static GETPROCTIMES getProcessTimesAddr = NULL;
  209. /*
  210. ** Check to see if we have timer support. Return 1 if necessary
  211. ** support found (or found previously).
  212. */
  213. static int hasTimer(void){
  214. if( getProcessTimesAddr ){
  215. return 1;
  216. } else {
  217. /* GetProcessTimes() isn't supported in WIN95 and some other Windows
  218. ** versions. See if the version we are running on has it, and if it
  219. ** does, save off a pointer to it and the current process handle.
  220. */
  221. hProcess = GetCurrentProcess();
  222. if( hProcess ){
  223. HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
  224. if( NULL != hinstLib ){
  225. getProcessTimesAddr =
  226. (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
  227. if( NULL != getProcessTimesAddr ){
  228. return 1;
  229. }
  230. FreeLibrary(hinstLib);
  231. }
  232. }
  233. }
  234. return 0;
  235. }
  236. /*
  237. ** Begin timing an operation
  238. */
  239. static void beginTimer(void){
  240. if( enableTimer && getProcessTimesAddr ){
  241. FILETIME ftCreation, ftExit;
  242. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
  243. &ftKernelBegin,&ftUserBegin);
  244. ftWallBegin = timeOfDay();
  245. }
  246. }
  247. /* Return the difference of two FILETIME structs in seconds */
  248. static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
  249. sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
  250. sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
  251. return (double) ((i64End - i64Start) / 10000000.0);
  252. }
  253. /*
  254. ** Print the timing results.
  255. */
  256. static void endTimer(void){
  257. if( enableTimer && getProcessTimesAddr){
  258. FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
  259. sqlite3_int64 ftWallEnd = timeOfDay();
  260. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
  261. printf("Run Time: real %.3f user %f sys %f\n",
  262. (ftWallEnd - ftWallBegin)*0.001,
  263. timeDiff(&ftUserBegin, &ftUserEnd),
  264. timeDiff(&ftKernelBegin, &ftKernelEnd));
  265. }
  266. }
  267. #define BEGIN_TIMER beginTimer()
  268. #define END_TIMER endTimer()
  269. #define HAS_TIMER hasTimer()
  270. #else
  271. #define BEGIN_TIMER
  272. #define END_TIMER
  273. #define HAS_TIMER 0
  274. #endif
  275. /*
  276. ** Used to prevent warnings about unused parameters
  277. */
  278. #define UNUSED_PARAMETER(x) (void)(x)
  279. /*
  280. ** If the following flag is set, then command execution stops
  281. ** at an error if we are not interactive.
  282. */
  283. static int bail_on_error = 0;
  284. /*
  285. ** Threat stdin as an interactive input if the following variable
  286. ** is true. Otherwise, assume stdin is connected to a file or pipe.
  287. */
  288. static int stdin_is_interactive = 1;
  289. /*
  290. ** On Windows systems we have to know if standard output is a console
  291. ** in order to translate UTF-8 into MBCS. The following variable is
  292. ** true if translation is required.
  293. */
  294. static int stdout_is_console = 1;
  295. /*
  296. ** The following is the open SQLite database. We make a pointer
  297. ** to this database a static variable so that it can be accessed
  298. ** by the SIGINT handler to interrupt database processing.
  299. */
  300. static sqlite3 *globalDb = 0;
  301. /*
  302. ** True if an interrupt (Control-C) has been received.
  303. */
  304. static volatile int seenInterrupt = 0;
  305. /*
  306. ** This is the name of our program. It is set in main(), used
  307. ** in a number of other places, mostly for error messages.
  308. */
  309. static char *Argv0;
  310. /*
  311. ** Prompt strings. Initialized in main. Settable with
  312. ** .prompt main continue
  313. */
  314. static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
  315. static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
  316. /*
  317. ** Write I/O traces to the following stream.
  318. */
  319. #ifdef SQLITE_ENABLE_IOTRACE
  320. static FILE *iotrace = 0;
  321. #endif
  322. /*
  323. ** This routine works like printf in that its first argument is a
  324. ** format string and subsequent arguments are values to be substituted
  325. ** in place of % fields. The result of formatting this string
  326. ** is written to iotrace.
  327. */
  328. #ifdef SQLITE_ENABLE_IOTRACE
  329. static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
  330. va_list ap;
  331. char *z;
  332. if( iotrace==0 ) return;
  333. va_start(ap, zFormat);
  334. z = sqlite3_vmprintf(zFormat, ap);
  335. va_end(ap);
  336. fprintf(iotrace, "%s", z);
  337. sqlite3_free(z);
  338. }
  339. #endif
  340. /*
  341. ** Determines if a string is a number of not.
  342. */
  343. static int isNumber(const char *z, int *realnum){
  344. if( *z=='-' || *z=='+' ) z++;
  345. if( !IsDigit(*z) ){
  346. return 0;
  347. }
  348. z++;
  349. if( realnum ) *realnum = 0;
  350. while( IsDigit(*z) ){ z++; }
  351. if( *z=='.' ){
  352. z++;
  353. if( !IsDigit(*z) ) return 0;
  354. while( IsDigit(*z) ){ z++; }
  355. if( realnum ) *realnum = 1;
  356. }
  357. if( *z=='e' || *z=='E' ){
  358. z++;
  359. if( *z=='+' || *z=='-' ) z++;
  360. if( !IsDigit(*z) ) return 0;
  361. while( IsDigit(*z) ){ z++; }
  362. if( realnum ) *realnum = 1;
  363. }
  364. return *z==0;
  365. }
  366. /*
  367. ** A global char* and an SQL function to access its current value
  368. ** from within an SQL statement. This program used to use the
  369. ** sqlite_exec_printf() API to substitue a string into an SQL statement.
  370. ** The correct way to do this with sqlite3 is to use the bind API, but
  371. ** since the shell is built around the callback paradigm it would be a lot
  372. ** of work. Instead just use this hack, which is quite harmless.
  373. */
  374. static const char *zShellStatic = 0;
  375. static void shellstaticFunc(
  376. sqlite3_context *context,
  377. int argc,
  378. sqlite3_value **argv
  379. ){
  380. assert( 0==argc );
  381. assert( zShellStatic );
  382. UNUSED_PARAMETER(argc);
  383. UNUSED_PARAMETER(argv);
  384. sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
  385. }
  386. /*
  387. ** Compute a string length that is limited to what can be stored in
  388. ** lower 30 bits of a 32-bit signed integer.
  389. */
  390. static int strlen30(const char *z){
  391. const char *z2 = z;
  392. while( *z2 ){ z2++; }
  393. return 0x3fffffff & (int)(z2 - z);
  394. }
  395. /*
  396. ** This routine reads a line of text from FILE in, stores
  397. ** the text in memory obtained from malloc() and returns a pointer
  398. ** to the text. NULL is returned at end of file, or if malloc()
  399. ** fails.
  400. **
  401. ** If zLine is not NULL then it is a malloced buffer returned from
  402. ** a previous call to this routine that may be reused.
  403. */
  404. static char *local_getline(char *zLine, FILE *in){
  405. int nLine = zLine==0 ? 0 : 100;
  406. int n = 0;
  407. while( 1 ){
  408. if( n+100>nLine ){
  409. nLine = nLine*2 + 100;
  410. zLine = realloc(zLine, nLine);
  411. if( zLine==0 ) return 0;
  412. }
  413. if( fgets(&zLine[n], nLine - n, in)==0 ){
  414. if( n==0 ){
  415. free(zLine);
  416. return 0;
  417. }
  418. zLine[n] = 0;
  419. break;
  420. }
  421. while( zLine[n] ) n++;
  422. if( n>0 && zLine[n-1]=='\n' ){
  423. n--;
  424. if( n>0 && zLine[n-1]=='\r' ) n--;
  425. zLine[n] = 0;
  426. break;
  427. }
  428. }
  429. #if defined(_WIN32) || defined(WIN32)
  430. /* For interactive input on Windows systems, translate the
  431. ** multi-byte characterset characters into UTF-8. */
  432. if( stdin_is_interactive ){
  433. extern char *sqlite3_win32_mbcs_to_utf8(const char*);
  434. char *zTrans = sqlite3_win32_mbcs_to_utf8(zLine);
  435. if( zTrans ){
  436. int nTrans = strlen30(zTrans)+1;
  437. if( nTrans>nLine ){
  438. zLine = realloc(zLine, nTrans);
  439. if( zLine==0 ){
  440. sqlite3_free(zTrans);
  441. return 0;
  442. }
  443. }
  444. memcpy(zLine, zTrans, nTrans);
  445. sqlite3_free(zTrans);
  446. }
  447. }
  448. #endif /* defined(_WIN32) || defined(WIN32) */
  449. return zLine;
  450. }
  451. /*
  452. ** Retrieve a single line of input text.
  453. **
  454. ** If in==0 then read from standard input and prompt before each line.
  455. ** If isContinuation is true, then a continuation prompt is appropriate.
  456. ** If isContinuation is zero, then the main prompt should be used.
  457. **
  458. ** If zPrior is not NULL then it is a buffer from a prior call to this
  459. ** routine that can be reused.
  460. **
  461. ** The result is stored in space obtained from malloc() and must either
  462. ** be freed by the caller or else passed back into this routine via the
  463. ** zPrior argument for reuse.
  464. */
  465. static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
  466. char *zPrompt;
  467. char *zResult;
  468. if( in!=0 ){
  469. zResult = local_getline(zPrior, in);
  470. }else{
  471. zPrompt = isContinuation ? continuePrompt : mainPrompt;
  472. #if SHELL_USE_LOCAL_GETLINE
  473. printf("%s", zPrompt);
  474. fflush(stdout);
  475. zResult = local_getline(zPrior, stdin);
  476. #else
  477. free(zPrior);
  478. zResult = shell_readline(zPrompt);
  479. if( zResult && *zResult ) shell_add_history(zResult);
  480. #endif
  481. }
  482. return zResult;
  483. }
  484. /*
  485. ** Render output like fprintf(). Except, if the output is going to the
  486. ** console and if this is running on a Windows machine, translate the
  487. ** output from UTF-8 into MBCS.
  488. */
  489. #if defined(_WIN32) || defined(WIN32)
  490. void utf8_printf(FILE *out, const char *zFormat, ...){
  491. va_list ap;
  492. va_start(ap, zFormat);
  493. if( stdout_is_console && (out==stdout || out==stderr) ){
  494. extern char *sqlite3_win32_utf8_to_mbcs(const char*);
  495. char *z1 = sqlite3_vmprintf(zFormat, ap);
  496. char *z2 = sqlite3_win32_utf8_to_mbcs(z1);
  497. sqlite3_free(z1);
  498. fputs(z2, out);
  499. sqlite3_free(z2);
  500. }else{
  501. vfprintf(out, zFormat, ap);
  502. }
  503. va_end(ap);
  504. }
  505. #elif !defined(utf8_printf)
  506. # define utf8_printf fprintf
  507. #endif
  508. /*
  509. ** Render output like fprintf(). This should not be used on anything that
  510. ** includes string formatting (e.g. "%s").
  511. */
  512. #if !defined(raw_printf)
  513. # define raw_printf fprintf
  514. #endif
  515. /*
  516. ** Shell output mode information from before ".explain on",
  517. ** saved so that it can be restored by ".explain off"
  518. */
  519. typedef struct SavedModeInfo SavedModeInfo;
  520. struct SavedModeInfo {
  521. int valid; /* Is there legit data in here? */
  522. int mode; /* Mode prior to ".explain on" */
  523. int showHeader; /* The ".header" setting prior to ".explain on" */
  524. int colWidth[100]; /* Column widths prior to ".explain on" */
  525. };
  526. /*
  527. ** State information about the database connection is contained in an
  528. ** instance of the following structure.
  529. */
  530. typedef struct ShellState ShellState;
  531. struct ShellState {
  532. sqlite3 *db; /* The database */
  533. int echoOn; /* True to echo input commands */
  534. int autoExplain; /* Automatically turn on .explain mode */
  535. int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
  536. int statsOn; /* True to display memory stats before each finalize */
  537. int scanstatsOn; /* True to display scan stats before each finalize */
  538. int countChanges; /* True to display change counts */
  539. int backslashOn; /* Resolve C-style \x escapes in SQL input text */
  540. int outCount; /* Revert to stdout when reaching zero */
  541. int cnt; /* Number of records displayed so far */
  542. FILE *out; /* Write results here */
  543. FILE *traceOut; /* Output for sqlite3_trace() */
  544. int nErr; /* Number of errors seen */
  545. int mode; /* An output mode setting */
  546. int cMode; /* temporary output mode for the current query */
  547. int normalMode; /* Output mode before ".explain on" */
  548. int writableSchema; /* True if PRAGMA writable_schema=ON */
  549. int showHeader; /* True to show column names in List or Column mode */
  550. unsigned shellFlgs; /* Various flags */
  551. char *zDestTable; /* Name of destination table when MODE_Insert */
  552. char colSeparator[20]; /* Column separator character for several modes */
  553. char rowSeparator[20]; /* Row separator character for MODE_Ascii */
  554. int colWidth[100]; /* Requested width of each column when in column mode*/
  555. int actualWidth[100]; /* Actual width of each column */
  556. char nullValue[20]; /* The text to print when a NULL comes back from
  557. ** the database */
  558. char outfile[FILENAME_MAX]; /* Filename for *out */
  559. const char *zDbFilename; /* name of the database file */
  560. char *zFreeOnClose; /* Filename to free when closing */
  561. const char *zVfs; /* Name of VFS to use */
  562. sqlite3_stmt *pStmt; /* Current statement if any. */
  563. FILE *pLog; /* Write log output here */
  564. int *aiIndent; /* Array of indents used in MODE_Explain */
  565. int nIndent; /* Size of array aiIndent[] */
  566. int iIndent; /* Index of current op in aiIndent[] */
  567. };
  568. /*
  569. ** These are the allowed shellFlgs values
  570. */
  571. #define SHFLG_Scratch 0x00001 /* The --scratch option is used */
  572. #define SHFLG_Pagecache 0x00002 /* The --pagecache option is used */
  573. #define SHFLG_Lookaside 0x00004 /* Lookaside memory is used */
  574. /*
  575. ** These are the allowed modes.
  576. */
  577. #define MODE_Line 0 /* One column per line. Blank line between records */
  578. #define MODE_Column 1 /* One record per line in neat columns */
  579. #define MODE_List 2 /* One record per line with a separator */
  580. #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
  581. #define MODE_Html 4 /* Generate an XHTML table */
  582. #define MODE_Insert 5 /* Generate SQL "insert" statements */
  583. #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */
  584. #define MODE_Csv 7 /* Quote strings, numbers are plain */
  585. #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */
  586. #define MODE_Ascii 9 /* Use ASCII unit and record separators (0x1F/0x1E) */
  587. static const char *modeDescr[] = {
  588. "line",
  589. "column",
  590. "list",
  591. "semi",
  592. "html",
  593. "insert",
  594. "tcl",
  595. "csv",
  596. "explain",
  597. "ascii",
  598. };
  599. /*
  600. ** These are the column/row/line separators used by the various
  601. ** import/export modes.
  602. */
  603. #define SEP_Column "|"
  604. #define SEP_Row "\n"
  605. #define SEP_Tab "\t"
  606. #define SEP_Space " "
  607. #define SEP_Comma ","
  608. #define SEP_CrLf "\r\n"
  609. #define SEP_Unit "\x1F"
  610. #define SEP_Record "\x1E"
  611. /*
  612. ** Number of elements in an array
  613. */
  614. #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
  615. /*
  616. ** A callback for the sqlite3_log() interface.
  617. */
  618. static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  619. ShellState *p = (ShellState*)pArg;
  620. if( p->pLog==0 ) return;
  621. utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  622. fflush(p->pLog);
  623. }
  624. /*
  625. ** Output the given string as a hex-encoded blob (eg. X'1234' )
  626. */
  627. static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  628. int i;
  629. char *zBlob = (char *)pBlob;
  630. raw_printf(out,"X'");
  631. for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
  632. raw_printf(out,"'");
  633. }
  634. /*
  635. ** Output the given string as a quoted string using SQL quoting conventions.
  636. */
  637. static void output_quoted_string(FILE *out, const char *z){
  638. int i;
  639. int nSingle = 0;
  640. setBinaryMode(out);
  641. for(i=0; z[i]; i++){
  642. if( z[i]=='\'' ) nSingle++;
  643. }
  644. if( nSingle==0 ){
  645. utf8_printf(out,"'%s'",z);
  646. }else{
  647. raw_printf(out,"'");
  648. while( *z ){
  649. for(i=0; z[i] && z[i]!='\''; i++){}
  650. if( i==0 ){
  651. raw_printf(out,"''");
  652. z++;
  653. }else if( z[i]=='\'' ){
  654. utf8_printf(out,"%.*s''",i,z);
  655. z += i+1;
  656. }else{
  657. utf8_printf(out,"%s",z);
  658. break;
  659. }
  660. }
  661. raw_printf(out,"'");
  662. }
  663. setTextMode(out);
  664. }
  665. /*
  666. ** Output the given string as a quoted according to C or TCL quoting rules.
  667. */
  668. static void output_c_string(FILE *out, const char *z){
  669. unsigned int c;
  670. fputc('"', out);
  671. while( (c = *(z++))!=0 ){
  672. if( c=='\\' ){
  673. fputc(c, out);
  674. fputc(c, out);
  675. }else if( c=='"' ){
  676. fputc('\\', out);
  677. fputc('"', out);
  678. }else if( c=='\t' ){
  679. fputc('\\', out);
  680. fputc('t', out);
  681. }else if( c=='\n' ){
  682. fputc('\\', out);
  683. fputc('n', out);
  684. }else if( c=='\r' ){
  685. fputc('\\', out);
  686. fputc('r', out);
  687. }else if( !isprint(c&0xff) ){
  688. raw_printf(out, "\\%03o", c&0xff);
  689. }else{
  690. fputc(c, out);
  691. }
  692. }
  693. fputc('"', out);
  694. }
  695. /*
  696. ** Output the given string with characters that are special to
  697. ** HTML escaped.
  698. */
  699. static void output_html_string(FILE *out, const char *z){
  700. int i;
  701. if( z==0 ) z = "";
  702. while( *z ){
  703. for(i=0; z[i]
  704. && z[i]!='<'
  705. && z[i]!='&'
  706. && z[i]!='>'
  707. && z[i]!='\"'
  708. && z[i]!='\'';
  709. i++){}
  710. if( i>0 ){
  711. utf8_printf(out,"%.*s",i,z);
  712. }
  713. if( z[i]=='<' ){
  714. raw_printf(out,"&lt;");
  715. }else if( z[i]=='&' ){
  716. raw_printf(out,"&amp;");
  717. }else if( z[i]=='>' ){
  718. raw_printf(out,"&gt;");
  719. }else if( z[i]=='\"' ){
  720. raw_printf(out,"&quot;");
  721. }else if( z[i]=='\'' ){
  722. raw_printf(out,"&#39;");
  723. }else{
  724. break;
  725. }
  726. z += i + 1;
  727. }
  728. }
  729. /*
  730. ** If a field contains any character identified by a 1 in the following
  731. ** array, then the string must be quoted for CSV.
  732. */
  733. static const char needCsvQuote[] = {
  734. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  735. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  736. 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  742. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  743. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  744. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  745. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  746. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  747. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  748. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  749. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  750. };
  751. /*
  752. ** Output a single term of CSV. Actually, p->colSeparator is used for
  753. ** the separator, which may or may not be a comma. p->nullValue is
  754. ** the null value. Strings are quoted if necessary. The separator
  755. ** is only issued if bSep is true.
  756. */
  757. static void output_csv(ShellState *p, const char *z, int bSep){
  758. FILE *out = p->out;
  759. if( z==0 ){
  760. utf8_printf(out,"%s",p->nullValue);
  761. }else{
  762. int i;
  763. int nSep = strlen30(p->colSeparator);
  764. for(i=0; z[i]; i++){
  765. if( needCsvQuote[((unsigned char*)z)[i]]
  766. || (z[i]==p->colSeparator[0] &&
  767. (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
  768. i = 0;
  769. break;
  770. }
  771. }
  772. if( i==0 ){
  773. putc('"', out);
  774. for(i=0; z[i]; i++){
  775. if( z[i]=='"' ) putc('"', out);
  776. putc(z[i], out);
  777. }
  778. putc('"', out);
  779. }else{
  780. utf8_printf(out, "%s", z);
  781. }
  782. }
  783. if( bSep ){
  784. utf8_printf(p->out, "%s", p->colSeparator);
  785. }
  786. }
  787. #ifdef SIGINT
  788. /*
  789. ** This routine runs when the user presses Ctrl-C
  790. */
  791. static void interrupt_handler(int NotUsed){
  792. UNUSED_PARAMETER(NotUsed);
  793. seenInterrupt++;
  794. if( seenInterrupt>2 ) exit(1);
  795. if( globalDb ) sqlite3_interrupt(globalDb);
  796. }
  797. #endif
  798. /*
  799. ** This is the callback routine that the shell
  800. ** invokes for each row of a query result.
  801. */
  802. static int shell_callback(
  803. void *pArg,
  804. int nArg, /* Number of result columns */
  805. char **azArg, /* Text of each result column */
  806. char **azCol, /* Column names */
  807. int *aiType /* Column types */
  808. ){
  809. int i;
  810. ShellState *p = (ShellState*)pArg;
  811. switch( p->cMode ){
  812. case MODE_Line: {
  813. int w = 5;
  814. if( azArg==0 ) break;
  815. for(i=0; i<nArg; i++){
  816. int len = strlen30(azCol[i] ? azCol[i] : "");
  817. if( len>w ) w = len;
  818. }
  819. if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
  820. for(i=0; i<nArg; i++){
  821. utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
  822. azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
  823. }
  824. break;
  825. }
  826. case MODE_Explain:
  827. case MODE_Column: {
  828. static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
  829. const int *colWidth;
  830. int showHdr;
  831. char *rowSep;
  832. if( p->cMode==MODE_Column ){
  833. colWidth = p->colWidth;
  834. showHdr = p->showHeader;
  835. rowSep = p->rowSeparator;
  836. }else{
  837. colWidth = aExplainWidths;
  838. showHdr = 1;
  839. rowSep = SEP_Row;
  840. }
  841. if( p->cnt++==0 ){
  842. for(i=0; i<nArg; i++){
  843. int w, n;
  844. if( i<ArraySize(p->colWidth) ){
  845. w = colWidth[i];
  846. }else{
  847. w = 0;
  848. }
  849. if( w==0 ){
  850. w = strlen30(azCol[i] ? azCol[i] : "");
  851. if( w<10 ) w = 10;
  852. n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullValue);
  853. if( w<n ) w = n;
  854. }
  855. if( i<ArraySize(p->actualWidth) ){
  856. p->actualWidth[i] = w;
  857. }
  858. if( showHdr ){
  859. if( w<0 ){
  860. utf8_printf(p->out,"%*.*s%s",-w,-w,azCol[i],
  861. i==nArg-1 ? rowSep : " ");
  862. }else{
  863. utf8_printf(p->out,"%-*.*s%s",w,w,azCol[i],
  864. i==nArg-1 ? rowSep : " ");
  865. }
  866. }
  867. }
  868. if( showHdr ){
  869. for(i=0; i<nArg; i++){
  870. int w;
  871. if( i<ArraySize(p->actualWidth) ){
  872. w = p->actualWidth[i];
  873. if( w<0 ) w = -w;
  874. }else{
  875. w = 10;
  876. }
  877. utf8_printf(p->out,"%-*.*s%s",w,w,
  878. "----------------------------------------------------------"
  879. "----------------------------------------------------------",
  880. i==nArg-1 ? rowSep : " ");
  881. }
  882. }
  883. }
  884. if( azArg==0 ) break;
  885. for(i=0; i<nArg; i++){
  886. int w;
  887. if( i<ArraySize(p->actualWidth) ){
  888. w = p->actualWidth[i];
  889. }else{
  890. w = 10;
  891. }
  892. if( p->cMode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){
  893. w = strlen30(azArg[i]);
  894. }
  895. if( i==1 && p->aiIndent && p->pStmt ){
  896. if( p->iIndent<p->nIndent ){
  897. utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
  898. }
  899. p->iIndent++;
  900. }
  901. if( w<0 ){
  902. utf8_printf(p->out,"%*.*s%s",-w,-w,
  903. azArg[i] ? azArg[i] : p->nullValue,
  904. i==nArg-1 ? rowSep : " ");
  905. }else{
  906. utf8_printf(p->out,"%-*.*s%s",w,w,
  907. azArg[i] ? azArg[i] : p->nullValue,
  908. i==nArg-1 ? rowSep : " ");
  909. }
  910. }
  911. break;
  912. }
  913. case MODE_Semi:
  914. case MODE_List: {
  915. if( p->cnt++==0 && p->showHeader ){
  916. for(i=0; i<nArg; i++){
  917. utf8_printf(p->out,"%s%s",azCol[i],
  918. i==nArg-1 ? p->rowSeparator : p->colSeparator);
  919. }
  920. }
  921. if( azArg==0 ) break;
  922. for(i=0; i<nArg; i++){
  923. char *z = azArg[i];
  924. if( z==0 ) z = p->nullValue;
  925. utf8_printf(p->out, "%s", z);
  926. if( i<nArg-1 ){
  927. utf8_printf(p->out, "%s", p->colSeparator);
  928. }else if( p->cMode==MODE_Semi ){
  929. utf8_printf(p->out, ";%s", p->rowSeparator);
  930. }else{
  931. utf8_printf(p->out, "%s", p->rowSeparator);
  932. }
  933. }
  934. break;
  935. }
  936. case MODE_Html: {
  937. if( p->cnt++==0 && p->showHeader ){
  938. raw_printf(p->out,"<TR>");
  939. for(i=0; i<nArg; i++){
  940. raw_printf(p->out,"<TH>");
  941. output_html_string(p->out, azCol[i]);
  942. raw_printf(p->out,"</TH>\n");
  943. }
  944. raw_printf(p->out,"</TR>\n");
  945. }
  946. if( azArg==0 ) break;
  947. raw_printf(p->out,"<TR>");
  948. for(i=0; i<nArg; i++){
  949. raw_printf(p->out,"<TD>");
  950. output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  951. raw_printf(p->out,"</TD>\n");
  952. }
  953. raw_printf(p->out,"</TR>\n");
  954. break;
  955. }
  956. case MODE_Tcl: {
  957. if( p->cnt++==0 && p->showHeader ){
  958. for(i=0; i<nArg; i++){
  959. output_c_string(p->out,azCol[i] ? azCol[i] : "");
  960. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  961. }
  962. utf8_printf(p->out, "%s", p->rowSeparator);
  963. }
  964. if( azArg==0 ) break;
  965. for(i=0; i<nArg; i++){
  966. output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  967. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  968. }
  969. utf8_printf(p->out, "%s", p->rowSeparator);
  970. break;
  971. }
  972. case MODE_Csv: {
  973. setBinaryMode(p->out);
  974. if( p->cnt++==0 && p->showHeader ){
  975. for(i=0; i<nArg; i++){
  976. output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  977. }
  978. utf8_printf(p->out, "%s", p->rowSeparator);
  979. }
  980. if( nArg>0 ){
  981. for(i=0; i<nArg; i++){
  982. output_csv(p, azArg[i], i<nArg-1);
  983. }
  984. utf8_printf(p->out, "%s", p->rowSeparator);
  985. }
  986. setTextMode(p->out);
  987. break;
  988. }
  989. case MODE_Insert: {
  990. p->cnt++;
  991. if( azArg==0 ) break;
  992. utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
  993. if( p->showHeader ){
  994. raw_printf(p->out,"(");
  995. for(i=0; i<nArg; i++){
  996. char *zSep = i>0 ? ",": "";
  997. utf8_printf(p->out, "%s%s", zSep, azCol[i]);
  998. }
  999. raw_printf(p->out,")");
  1000. }
  1001. raw_printf(p->out," VALUES(");
  1002. for(i=0; i<nArg; i++){
  1003. char *zSep = i>0 ? ",": "";
  1004. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  1005. utf8_printf(p->out,"%sNULL",zSep);
  1006. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  1007. if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
  1008. output_quoted_string(p->out, azArg[i]);
  1009. }else if( aiType && (aiType[i]==SQLITE_INTEGER
  1010. || aiType[i]==SQLITE_FLOAT) ){
  1011. utf8_printf(p->out,"%s%s",zSep, azArg[i]);
  1012. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  1013. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  1014. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  1015. if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
  1016. output_hex_blob(p->out, pBlob, nBlob);
  1017. }else if( isNumber(azArg[i], 0) ){
  1018. utf8_printf(p->out,"%s%s",zSep, azArg[i]);
  1019. }else{
  1020. if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
  1021. output_quoted_string(p->out, azArg[i]);
  1022. }
  1023. }
  1024. raw_printf(p->out,");\n");
  1025. break;
  1026. }
  1027. case MODE_Ascii: {
  1028. if( p->cnt++==0 && p->showHeader ){
  1029. for(i=0; i<nArg; i++){
  1030. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  1031. utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
  1032. }
  1033. utf8_printf(p->out, "%s", p->rowSeparator);
  1034. }
  1035. if( azArg==0 ) break;
  1036. for(i=0; i<nArg; i++){
  1037. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  1038. utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
  1039. }
  1040. utf8_printf(p->out, "%s", p->rowSeparator);
  1041. break;
  1042. }
  1043. }
  1044. return 0;
  1045. }
  1046. /*
  1047. ** This is the callback routine that the SQLite library
  1048. ** invokes for each row of a query result.
  1049. */
  1050. static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  1051. /* since we don't have type info, call the shell_callback with a NULL value */
  1052. return shell_callback(pArg, nArg, azArg, azCol, NULL);
  1053. }
  1054. /*
  1055. ** Set the destination table field of the ShellState structure to
  1056. ** the name of the table given. Escape any quote characters in the
  1057. ** table name.
  1058. */
  1059. static void set_table_name(ShellState *p, const char *zName){
  1060. int i, n;
  1061. int needQuote;
  1062. char *z;
  1063. if( p->zDestTable ){
  1064. free(p->zDestTable);
  1065. p->zDestTable = 0;
  1066. }
  1067. if( zName==0 ) return;
  1068. needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
  1069. for(i=n=0; zName[i]; i++, n++){
  1070. if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
  1071. needQuote = 1;
  1072. if( zName[i]=='\'' ) n++;
  1073. }
  1074. }
  1075. if( needQuote ) n += 2;
  1076. z = p->zDestTable = malloc( n+1 );
  1077. if( z==0 ){
  1078. raw_printf(stderr,"Error: out of memory\n");
  1079. exit(1);
  1080. }
  1081. n = 0;
  1082. if( needQuote ) z[n++] = '\'';
  1083. for(i=0; zName[i]; i++){
  1084. z[n++] = zName[i];
  1085. if( zName[i]=='\'' ) z[n++] = '\'';
  1086. }
  1087. if( needQuote ) z[n++] = '\'';
  1088. z[n] = 0;
  1089. }
  1090. /* zIn is either a pointer to a NULL-terminated string in memory obtained
  1091. ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  1092. ** added to zIn, and the result returned in memory obtained from malloc().
  1093. ** zIn, if it was not NULL, is freed.
  1094. **
  1095. ** If the third argument, quote, is not '\0', then it is used as a
  1096. ** quote character for zAppend.
  1097. */
  1098. static char *appendText(char *zIn, char const *zAppend, char quote){
  1099. int len;
  1100. int i;
  1101. int nAppend = strlen30(zAppend);
  1102. int nIn = (zIn?strlen30(zIn):0);
  1103. len = nAppend+nIn+1;
  1104. if( quote ){
  1105. len += 2;
  1106. for(i=0; i<nAppend; i++){
  1107. if( zAppend[i]==quote ) len++;
  1108. }
  1109. }
  1110. zIn = (char *)realloc(zIn, len);
  1111. if( !zIn ){
  1112. return 0;
  1113. }
  1114. if( quote ){
  1115. char *zCsr = &zIn[nIn];
  1116. *zCsr++ = quote;
  1117. for(i=0; i<nAppend; i++){
  1118. *zCsr++ = zAppend[i];
  1119. if( zAppend[i]==quote ) *zCsr++ = quote;
  1120. }
  1121. *zCsr++ = quote;
  1122. *zCsr++ = '\0';
  1123. assert( (zCsr-zIn)==len );
  1124. }else{
  1125. memcpy(&zIn[nIn], zAppend, nAppend);
  1126. zIn[len-1] = '\0';
  1127. }
  1128. return zIn;
  1129. }
  1130. /*
  1131. ** Execute a query statement that will generate SQL output. Print
  1132. ** the result columns, comma-separated, on a line and then add a
  1133. ** semicolon terminator to the end of that line.
  1134. **
  1135. ** If the number of columns is 1 and that column contains text "--"
  1136. ** then write the semicolon on a separate line. That way, if a
  1137. ** "--" comment occurs at the end of the statement, the comment
  1138. ** won't consume the semicolon terminator.
  1139. */
  1140. static int run_table_dump_query(
  1141. ShellState *p, /* Query context */
  1142. const char *zSelect, /* SELECT statement to extract content */
  1143. const char *zFirstRow /* Print before first row, if not NULL */
  1144. ){
  1145. sqlite3_stmt *pSelect;
  1146. int rc;
  1147. int nResult;
  1148. int i;
  1149. const char *z;
  1150. rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
  1151. if( rc!=SQLITE_OK || !pSelect ){
  1152. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  1153. sqlite3_errmsg(p->db));
  1154. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  1155. return rc;
  1156. }
  1157. rc = sqlite3_step(pSelect);
  1158. nResult = sqlite3_column_count(pSelect);
  1159. while( rc==SQLITE_ROW ){
  1160. if( zFirstRow ){
  1161. utf8_printf(p->out, "%s", zFirstRow);
  1162. zFirstRow = 0;
  1163. }
  1164. z = (const char*)sqlite3_column_text(pSelect, 0);
  1165. utf8_printf(p->out, "%s", z);
  1166. for(i=1; i<nResult; i++){
  1167. utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
  1168. }
  1169. if( z==0 ) z = "";
  1170. while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
  1171. if( z[0] ){
  1172. raw_printf(p->out, "\n;\n");
  1173. }else{
  1174. raw_printf(p->out, ";\n");
  1175. }
  1176. rc = sqlite3_step(pSelect);
  1177. }
  1178. rc = sqlite3_finalize(pSelect);
  1179. if( rc!=SQLITE_OK ){
  1180. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  1181. sqlite3_errmsg(p->db));
  1182. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  1183. }
  1184. return rc;
  1185. }
  1186. /*
  1187. ** Allocate space and save off current error string.
  1188. */
  1189. static char *save_err_msg(
  1190. sqlite3 *db /* Database to query */
  1191. ){
  1192. int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
  1193. char *zErrMsg = sqlite3_malloc64(nErrMsg);
  1194. if( zErrMsg ){
  1195. memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
  1196. }
  1197. return zErrMsg;
  1198. }
  1199. #ifdef __linux__
  1200. /*
  1201. ** Attempt to display I/O stats on Linux using /proc/PID/io
  1202. */
  1203. static void displayLinuxIoStats(FILE *out){
  1204. FILE *in;
  1205. char z[200];
  1206. sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
  1207. in = fopen(z, "rb");
  1208. if( in==0 ) return;
  1209. while( fgets(z, sizeof(z), in)!=0 ){
  1210. static const struct {
  1211. const char *zPattern;
  1212. const char *zDesc;
  1213. } aTrans[] = {
  1214. { "rchar: ", "Bytes received by read():" },
  1215. { "wchar: ", "Bytes sent to write():" },
  1216. { "syscr: ", "Read() system calls:" },
  1217. { "syscw: ", "Write() system calls:" },
  1218. { "read_bytes: ", "Bytes read from storage:" },
  1219. { "write_bytes: ", "Bytes written to storage:" },
  1220. { "cancelled_write_bytes: ", "Cancelled write bytes:" },
  1221. };
  1222. int i;
  1223. for(i=0; i<ArraySize(aTrans); i++){
  1224. int n = (int)strlen(aTrans[i].zPattern);
  1225. if( strncmp(aTrans[i].zPattern, z, n)==0 ){
  1226. raw_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
  1227. break;
  1228. }
  1229. }
  1230. }
  1231. fclose(in);
  1232. }
  1233. #endif
  1234. /*
  1235. ** Display memory stats.
  1236. */
  1237. static int display_stats(
  1238. sqlite3 *db, /* Database to query */
  1239. ShellState *pArg, /* Pointer to ShellState */
  1240. int bReset /* True to reset the stats */
  1241. ){
  1242. int iCur;
  1243. int iHiwtr;
  1244. if( pArg && pArg->out ){
  1245. iHiwtr = iCur = -1;
  1246. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset);
  1247. raw_printf(pArg->out,
  1248. "Memory Used: %d (max %d) bytes\n",
  1249. iCur, iHiwtr);
  1250. iHiwtr = iCur = -1;
  1251. sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset);
  1252. raw_printf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n",
  1253. iCur, iHiwtr);
  1254. if( pArg->shellFlgs & SHFLG_Pagecache ){
  1255. iHiwtr = iCur = -1;
  1256. sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset);
  1257. raw_printf(pArg->out,
  1258. "Number of Pcache Pages Used: %d (max %d) pages\n",
  1259. iCur, iHiwtr);
  1260. }
  1261. iHiwtr = iCur = -1;
  1262. sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset);
  1263. raw_printf(pArg->out,
  1264. "Number of Pcache Overflow Bytes: %d (max %d) bytes\n",
  1265. iCur, iHiwtr);
  1266. if( pArg->shellFlgs & SHFLG_Scratch ){
  1267. iHiwtr = iCur = -1;
  1268. sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset);
  1269. raw_printf(pArg->out,
  1270. "Number of Scratch Allocations Used: %d (max %d)\n",
  1271. iCur, iHiwtr);
  1272. }
  1273. iHiwtr = iCur = -1;
  1274. sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset);
  1275. raw_printf(pArg->out,
  1276. "Number of Scratch Overflow Bytes: %d (max %d) bytes\n",
  1277. iCur, iHiwtr);
  1278. iHiwtr = iCur = -1;
  1279. sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset);
  1280. raw_printf(pArg->out, "Largest Allocation: %d bytes\n",
  1281. iHiwtr);
  1282. iHiwtr = iCur = -1;
  1283. sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset);
  1284. raw_printf(pArg->out, "Largest Pcache Allocation: %d bytes\n",
  1285. iHiwtr);
  1286. iHiwtr = iCur = -1;
  1287. sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset);
  1288. raw_printf(pArg->out, "Largest Scratch Allocation: %d bytes\n",
  1289. iHiwtr);
  1290. #ifdef YYTRACKMAXSTACKDEPTH
  1291. iHiwtr = iCur = -1;
  1292. sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset);
  1293. raw_printf(pArg->out, "Deepest Parser Stack: %d (max %d)\n",
  1294. iCur, iHiwtr);
  1295. #endif
  1296. }
  1297. if( pArg && pArg->out && db ){
  1298. if( pArg->shellFlgs & SHFLG_Lookaside ){
  1299. iHiwtr = iCur = -1;
  1300. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
  1301. &iCur, &iHiwtr, bReset);
  1302. raw_printf(pArg->out,
  1303. "Lookaside Slots Used: %d (max %d)\n",
  1304. iCur, iHiwtr);
  1305. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
  1306. &iCur, &iHiwtr, bReset);
  1307. raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
  1308. iHiwtr);
  1309. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
  1310. &iCur, &iHiwtr, bReset);
  1311. raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
  1312. iHiwtr);
  1313. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
  1314. &iCur, &iHiwtr, bReset);
  1315. raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
  1316. iHiwtr);
  1317. }
  1318. iHiwtr = iCur = -1;
  1319. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
  1320. raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
  1321. iCur);
  1322. iHiwtr = iCur = -1;
  1323. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
  1324. raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
  1325. iHiwtr = iCur = -1;
  1326. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
  1327. raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
  1328. iHiwtr = iCur = -1;
  1329. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
  1330. raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
  1331. iHiwtr = iCur = -1;
  1332. sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
  1333. raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
  1334. iCur);
  1335. iHiwtr = iCur = -1;
  1336. sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
  1337. raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
  1338. iCur);
  1339. }
  1340. if( pArg && pArg->out && db && pArg->pStmt ){
  1341. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
  1342. bReset);
  1343. raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
  1344. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
  1345. raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
  1346. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
  1347. raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
  1348. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
  1349. raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
  1350. }
  1351. #ifdef __linux__
  1352. displayLinuxIoStats(pArg->out);
  1353. #endif
  1354. /* Do not remove this machine readable comment: extra-stats-output-here */
  1355. return 0;
  1356. }
  1357. /*
  1358. ** Display scan stats.
  1359. */
  1360. static void display_scanstats(
  1361. sqlite3 *db, /* Database to query */
  1362. ShellState *pArg /* Pointer to ShellState */
  1363. ){
  1364. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  1365. UNUSED_PARAMETER(db);
  1366. UNUSED_PARAMETER(pArg);
  1367. #else
  1368. int i, k, n, mx;
  1369. raw_printf(pArg->out, "-------- scanstats --------\n");
  1370. mx = 0;
  1371. for(k=0; k<=mx; k++){
  1372. double rEstLoop = 1.0;
  1373. for(i=n=0; 1; i++){
  1374. sqlite3_stmt *p = pArg->pStmt;
  1375. sqlite3_int64 nLoop, nVisit;
  1376. double rEst;
  1377. int iSid;
  1378. const char *zExplain;
  1379. if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
  1380. break;
  1381. }
  1382. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
  1383. if( iSid>mx ) mx = iSid;
  1384. if( iSid!=k ) continue;
  1385. if( n==0 ){
  1386. rEstLoop = (double)nLoop;
  1387. if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
  1388. }
  1389. n++;
  1390. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
  1391. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
  1392. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
  1393. utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
  1394. rEstLoop *= rEst;
  1395. raw_printf(pArg->out,
  1396. " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
  1397. nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
  1398. );
  1399. }
  1400. }
  1401. raw_printf(pArg->out, "---------------------------\n");
  1402. #endif
  1403. }
  1404. /*
  1405. ** Parameter azArray points to a zero-terminated array of strings. zStr
  1406. ** points to a single nul-terminated string. Return non-zero if zStr
  1407. ** is equal, according to strcmp(), to any of the strings in the array.
  1408. ** Otherwise, return zero.
  1409. */
  1410. static int str_in_array(const char *zStr, const char **azArray){
  1411. int i;
  1412. for(i=0; azArray[i]; i++){
  1413. if( 0==strcmp(zStr, azArray[i]) ) return 1;
  1414. }
  1415. return 0;
  1416. }
  1417. /*
  1418. ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
  1419. ** and populate the ShellState.aiIndent[] array with the number of
  1420. ** spaces each opcode should be indented before it is output.
  1421. **
  1422. ** The indenting rules are:
  1423. **
  1424. ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
  1425. ** all opcodes that occur between the p2 jump destination and the opcode
  1426. ** itself by 2 spaces.
  1427. **
  1428. ** * For each "Goto", if the jump destination is earlier in the program
  1429. ** and ends on one of:
  1430. ** Yield SeekGt SeekLt RowSetRead Rewind
  1431. ** or if the P1 parameter is one instead of zero,
  1432. ** then indent all opcodes between the earlier instruction
  1433. ** and "Goto" by 2 spaces.
  1434. */
  1435. static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
  1436. const char *zSql; /* The text of the SQL statement */
  1437. const char *z; /* Used to check if this is an EXPLAIN */
  1438. int *abYield = 0; /* True if op is an OP_Yield */
  1439. int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
  1440. int iOp; /* Index of operation in p->aiIndent[] */
  1441. const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
  1442. "NextIfOpen", "PrevIfOpen", 0 };
  1443. const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
  1444. "Rewind", 0 };
  1445. const char *azGoto[] = { "Goto", 0 };
  1446. /* Try to figure out if this is really an EXPLAIN statement. If this
  1447. ** cannot be verified, return early. */
  1448. if( sqlite3_column_count(pSql)!=8 ){
  1449. p->cMode = p->mode;
  1450. return;
  1451. }
  1452. zSql = sqlite3_sql(pSql);
  1453. if( zSql==0 ) return;
  1454. for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
  1455. if( sqlite3_strnicmp(z, "explain", 7) ){
  1456. p->cMode = p->mode;
  1457. return;
  1458. }
  1459. for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
  1460. int i;
  1461. int iAddr = sqlite3_column_int(pSql, 0);
  1462. const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
  1463. /* Set p2 to the P2 field of the current opcode. Then, assuming that
  1464. ** p2 is an instruction address, set variable p2op to the index of that
  1465. ** instruction in the aiIndent[] array. p2 and p2op may be different if
  1466. ** the current instruction is part of a sub-program generated by an
  1467. ** SQL trigger or foreign key. */
  1468. int p2 = sqlite3_column_int(pSql, 3);
  1469. int p2op = (p2 + (iOp-iAddr));
  1470. /* Grow the p->aiIndent array as required */
  1471. if( iOp>=nAlloc ){
  1472. if( iOp==0 ){
  1473. /* Do further verfication that this is explain output. Abort if
  1474. ** it is not */
  1475. static const char *explainCols[] = {
  1476. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
  1477. int jj;
  1478. for(jj=0; jj<ArraySize(explainCols); jj++){
  1479. if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
  1480. p->cMode = p->mode;
  1481. sqlite3_reset(pSql);
  1482. return;
  1483. }
  1484. }
  1485. }
  1486. nAlloc += 100;
  1487. p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
  1488. abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
  1489. }
  1490. abYield[iOp] = str_in_array(zOp, azYield);
  1491. p->aiIndent[iOp] = 0;
  1492. p->nIndent = iOp+1;
  1493. if( str_in_array(zOp, azNext) ){
  1494. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  1495. }
  1496. if( str_in_array(zOp, azGoto) && p2op<p->nIndent
  1497. && (abYield[p2op] || sqlite3_column_int(pSql, 2))
  1498. ){
  1499. for(i=p2op+1; i<iOp; i++) p->aiIndent[i] += 2;
  1500. }
  1501. }
  1502. p->iIndent = 0;
  1503. sqlite3_free(abYield);
  1504. sqlite3_reset(pSql);
  1505. }
  1506. /*
  1507. ** Free the array allocated by explain_data_prepare().
  1508. */
  1509. static void explain_data_delete(ShellState *p){
  1510. sqlite3_free(p->aiIndent);
  1511. p->aiIndent = 0;
  1512. p->nIndent = 0;
  1513. p->iIndent = 0;
  1514. }
  1515. /*
  1516. ** Execute a statement or set of statements. Print
  1517. ** any result rows/columns depending on the current mode
  1518. ** set via the supplied callback.
  1519. **
  1520. ** This is very similar to SQLite's built-in sqlite3_exec()
  1521. ** function except it takes a slightly different callback
  1522. ** and callback data argument.
  1523. */
  1524. static int shell_exec(
  1525. sqlite3 *db, /* An open database */
  1526. const char *zSql, /* SQL to be evaluated */
  1527. int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
  1528. /* (not the same as sqlite3_exec) */
  1529. ShellState *pArg, /* Pointer to ShellState */
  1530. char **pzErrMsg /* Error msg written here */
  1531. ){
  1532. sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
  1533. int rc = SQLITE_OK; /* Return Code */
  1534. int rc2;
  1535. const char *zLeftover; /* Tail of unprocessed SQL */
  1536. if( pzErrMsg ){
  1537. *pzErrMsg = NULL;
  1538. }
  1539. while( zSql[0] && (SQLITE_OK == rc) ){
  1540. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  1541. if( SQLITE_OK != rc ){
  1542. if( pzErrMsg ){
  1543. *pzErrMsg = save_err_msg(db);
  1544. }
  1545. }else{
  1546. if( !pStmt ){
  1547. /* this happens for a comment or white-space */
  1548. zSql = zLeftover;
  1549. while( IsSpace(zSql[0]) ) zSql++;
  1550. continue;
  1551. }
  1552. /* save off the prepared statment handle and reset row count */
  1553. if( pArg ){
  1554. pArg->pStmt = pStmt;
  1555. pArg->cnt = 0;
  1556. }
  1557. /* echo the sql statement if echo on */
  1558. if( pArg && pArg->echoOn ){
  1559. const char *zStmtSql = sqlite3_sql(pStmt);
  1560. utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  1561. }
  1562. /* Show the EXPLAIN QUERY PLAN if .eqp is on */
  1563. if( pArg && pArg->autoEQP ){
  1564. sqlite3_stmt *pExplain;
  1565. char *zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s",
  1566. sqlite3_sql(pStmt));
  1567. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  1568. if( rc==SQLITE_OK ){
  1569. while( sqlite3_step(pExplain)==SQLITE_ROW ){
  1570. raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
  1571. raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
  1572. raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
  1573. utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
  1574. }
  1575. }
  1576. sqlite3_finalize(pExplain);
  1577. sqlite3_free(zEQP);
  1578. }
  1579. if( pArg ){
  1580. pArg->cMode = pArg->mode;
  1581. if( pArg->autoExplain
  1582. && sqlite3_column_count(pStmt)==8
  1583. && sqlite3_strlike("%EXPLAIN%", sqlite3_sql(pStmt),0)==0
  1584. ){
  1585. pArg->cMode = MODE_Explain;
  1586. }
  1587. /* If the shell is currently in ".explain" mode, gather the extra
  1588. ** data required to add indents to the output.*/
  1589. if( pArg->cMode==MODE_Explain ){
  1590. explain_data_prepare(pArg, pStmt);
  1591. }
  1592. }
  1593. /* perform the first step. this will tell us if we
  1594. ** have a result set or not and how wide it is.
  1595. */
  1596. rc = sqlite3_step(pStmt);
  1597. /* if we have a result set... */
  1598. if( SQLITE_ROW == rc ){
  1599. /* if we have a callback... */
  1600. if( xCallback ){
  1601. /* allocate space for col name ptr, value ptr, and type */
  1602. int nCol = sqlite3_column_count(pStmt);
  1603. void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
  1604. if( !pData ){
  1605. rc = SQLITE_NOMEM;
  1606. }else{
  1607. char **azCols = (char **)pData; /* Names of result columns */
  1608. char **azVals = &azCols[nCol]; /* Results */
  1609. int *aiTypes = (int *)&azVals[nCol]; /* Result types */
  1610. int i, x;
  1611. assert(sizeof(int) <= sizeof(char *));
  1612. /* save off ptrs to column names */
  1613. for(i=0; i<nCol; i++){
  1614. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  1615. }
  1616. do{
  1617. /* extract the data and data types */
  1618. for(i=0; i<nCol; i++){
  1619. aiTypes[i] = x = sqlite3_column_type(pStmt, i);
  1620. if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
  1621. azVals[i] = "";
  1622. }else{
  1623. azVals[i] = (char*)sqlite3_column_text(pStmt, i);
  1624. }
  1625. if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
  1626. rc = SQLITE_NOMEM;
  1627. break; /* from for */
  1628. }
  1629. } /* end for */
  1630. /* if data and types extracted successfully... */
  1631. if( SQLITE_ROW == rc ){
  1632. /* call the supplied callback with the result row data */
  1633. if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
  1634. rc = SQLITE_ABORT;
  1635. }else{
  1636. rc = sqlite3_step(pStmt);
  1637. }
  1638. }
  1639. } while( SQLITE_ROW == rc );
  1640. sqlite3_free(pData);
  1641. }
  1642. }else{
  1643. do{
  1644. rc = sqlite3_step(pStmt);
  1645. } while( rc == SQLITE_ROW );
  1646. }
  1647. }
  1648. explain_data_delete(pArg);
  1649. /* print usage stats if stats on */
  1650. if( pArg && pArg->statsOn ){
  1651. display_stats(db, pArg, 0);
  1652. }
  1653. /* print loop-counters if required */
  1654. if( pArg && pArg->scanstatsOn ){
  1655. display_scanstats(db, pArg);
  1656. }
  1657. /* Finalize the statement just executed. If this fails, save a
  1658. ** copy of the error message. Otherwise, set zSql to point to the
  1659. ** next statement to execute. */
  1660. rc2 = sqlite3_finalize(pStmt);
  1661. if( rc!=SQLITE_NOMEM ) rc = rc2;
  1662. if( rc==SQLITE_OK ){
  1663. zSql = zLeftover;
  1664. while( IsSpace(zSql[0]) ) zSql++;
  1665. }else if( pzErrMsg ){
  1666. *pzErrMsg = save_err_msg(db);
  1667. }
  1668. /* clear saved stmt handle */
  1669. if( pArg ){
  1670. pArg->pStmt = NULL;
  1671. }
  1672. }
  1673. } /* end while */
  1674. return rc;
  1675. }
  1676. /*
  1677. ** This is a different callback routine used for dumping the database.
  1678. ** Each row received by this callback consists of a table name,
  1679. ** the table type ("index" or "table") and SQL to create the table.
  1680. ** This routine should print text sufficient to recreate the table.
  1681. */
  1682. static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
  1683. int rc;
  1684. const char *zTable;
  1685. const char *zType;
  1686. const char *zSql;
  1687. const char *zPrepStmt = 0;
  1688. ShellState *p = (ShellState *)pArg;
  1689. UNUSED_PARAMETER(azCol);
  1690. if( nArg!=3 ) return 1;
  1691. zTable = azArg[0];
  1692. zType = azArg[1];
  1693. zSql = azArg[2];
  1694. if( strcmp(zTable, "sqlite_sequence")==0 ){
  1695. zPrepStmt = "DELETE FROM sqlite_sequence;\n";
  1696. }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
  1697. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  1698. }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  1699. return 0;
  1700. }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  1701. char *zIns;
  1702. if( !p->writableSchema ){
  1703. raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
  1704. p->writableSchema = 1;
  1705. }
  1706. zIns = sqlite3_mprintf(
  1707. "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
  1708. "VALUES('table','%q','%q',0,'%q');",
  1709. zTable, zTable, zSql);
  1710. utf8_printf(p->out, "%s\n", zIns);
  1711. sqlite3_free(zIns);
  1712. return 0;
  1713. }else{
  1714. utf8_printf(p->out, "%s;\n", zSql);
  1715. }
  1716. if( strcmp(zType, "table")==0 ){
  1717. sqlite3_stmt *pTableInfo = 0;
  1718. char *zSelect = 0;
  1719. char *zTableInfo = 0;
  1720. char *zTmp = 0;
  1721. int nRow = 0;
  1722. zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
  1723. zTableInfo = appendText(zTableInfo, zTable, '"');
  1724. zTableInfo = appendText(zTableInfo, ");", 0);
  1725. rc = sqlite3_prepare_v2(p->db, zTableInfo, -1, &pTableInfo, 0);
  1726. free(zTableInfo);
  1727. if( rc!=SQLITE_OK || !pTableInfo ){
  1728. return 1;
  1729. }
  1730. zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
  1731. /* Always quote the table name, even if it appears to be pure ascii,
  1732. ** in case it is a keyword. Ex: INSERT INTO "table" ... */
  1733. zTmp = appendText(zTmp, zTable, '"');
  1734. if( zTmp ){
  1735. zSelect = appendText(zSelect, zTmp, '\'');
  1736. free(zTmp);
  1737. }
  1738. zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
  1739. rc = sqlite3_step(pTableInfo);
  1740. while( rc==SQLITE_ROW ){
  1741. const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
  1742. zSelect = appendText(zSelect, "quote(", 0);
  1743. zSelect = appendText(zSelect, zText, '"');
  1744. rc = sqlite3_step(pTableInfo);
  1745. if( rc==SQLITE_ROW ){
  1746. zSelect = appendText(zSelect, "), ", 0);
  1747. }else{
  1748. zSelect = appendText(zSelect, ") ", 0);
  1749. }
  1750. nRow++;
  1751. }
  1752. rc = sqlite3_finalize(pTableInfo);
  1753. if( rc!=SQLITE_OK || nRow==0 ){
  1754. free(zSelect);
  1755. return 1;
  1756. }
  1757. zSelect = appendText(zSelect, "|| ')' FROM ", 0);
  1758. zSelect = appendText(zSelect, zTable, '"');
  1759. rc = run_table_dump_query(p, zSelect, zPrepStmt);
  1760. if( rc==SQLITE_CORRUPT ){
  1761. zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
  1762. run_table_dump_query(p, zSelect, 0);
  1763. }
  1764. free(zSelect);
  1765. }
  1766. return 0;
  1767. }
  1768. /*
  1769. ** Run zQuery. Use dump_callback() as the callback routine so that
  1770. ** the contents of the query are output as SQL statements.
  1771. **
  1772. ** If we get a SQLITE_CORRUPT error, rerun the query after appending
  1773. ** "ORDER BY rowid DESC" to the end.
  1774. */
  1775. static int run_schema_dump_query(
  1776. ShellState *p,
  1777. const char *zQuery
  1778. ){
  1779. int rc;
  1780. char *zErr = 0;
  1781. rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
  1782. if( rc==SQLITE_CORRUPT ){
  1783. char *zQ2;
  1784. int len = strlen30(zQuery);
  1785. raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  1786. if( zErr ){
  1787. utf8_printf(p->out, "/****** %s ******/\n", zErr);
  1788. sqlite3_free(zErr);
  1789. zErr = 0;
  1790. }
  1791. zQ2 = malloc( len+100 );
  1792. if( zQ2==0 ) return rc;
  1793. sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
  1794. rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
  1795. if( rc ){
  1796. utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
  1797. }else{
  1798. rc = SQLITE_CORRUPT;
  1799. }
  1800. sqlite3_free(zErr);
  1801. free(zQ2);
  1802. }
  1803. return rc;
  1804. }
  1805. /*
  1806. ** Text of a help message
  1807. */
  1808. static char zHelp[] =
  1809. ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
  1810. ".bail on|off Stop after hitting an error. Default OFF\n"
  1811. ".binary on|off Turn binary output on or off. Default OFF\n"
  1812. ".changes on|off Show number of rows changed by SQL\n"
  1813. ".clone NEWDB Clone data into NEWDB from the existing database\n"
  1814. ".databases List names and files of attached databases\n"
  1815. ".dbinfo ?DB? Show status information about the database\n"
  1816. ".dump ?TABLE? ... Dump the database in an SQL text format\n"
  1817. " If TABLE specified, only dump tables matching\n"
  1818. " LIKE pattern TABLE.\n"
  1819. ".echo on|off Turn command echo on or off\n"
  1820. ".eqp on|off Enable or disable automatic EXPLAIN QUERY PLAN\n"
  1821. ".exit Exit this program\n"
  1822. ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
  1823. ".fullschema Show schema and the content of sqlite_stat tables\n"
  1824. ".headers on|off Turn display of headers on or off\n"
  1825. ".help Show this message\n"
  1826. ".import FILE TABLE Import data from FILE into TABLE\n"
  1827. ".indexes ?TABLE? Show names of all indexes\n"
  1828. " If TABLE specified, only show indexes for tables\n"
  1829. " matching LIKE pattern TABLE.\n"
  1830. #ifdef SQLITE_ENABLE_IOTRACE
  1831. ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
  1832. #endif
  1833. ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
  1834. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1835. ".load FILE ?ENTRY? Load an extension library\n"
  1836. #endif
  1837. ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
  1838. ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
  1839. " ascii Columns/rows delimited by 0x1F and 0x1E\n"
  1840. " csv Comma-separated values\n"
  1841. " column Left-aligned columns. (See .width)\n"
  1842. " html HTML <table> code\n"
  1843. " insert SQL insert statements for TABLE\n"
  1844. " line One value per line\n"
  1845. " list Values delimited by .separator strings\n"
  1846. " tabs Tab-separated values\n"
  1847. " tcl TCL list elements\n"
  1848. ".nullvalue STRING Use STRING in place of NULL values\n"
  1849. ".once FILENAME Output for the next SQL command only to FILENAME\n"
  1850. ".open ?FILENAME? Close existing database and reopen FILENAME\n"
  1851. ".output ?FILENAME? Send output to FILENAME or stdout\n"
  1852. ".print STRING... Print literal STRING\n"
  1853. ".prompt MAIN CONTINUE Replace the standard prompts\n"
  1854. ".quit Exit this program\n"
  1855. ".read FILENAME Execute SQL in FILENAME\n"
  1856. ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
  1857. ".save FILE Write in-memory database into FILE\n"
  1858. ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
  1859. ".schema ?TABLE? Show the CREATE statements\n"
  1860. " If TABLE specified, only show tables matching\n"
  1861. " LIKE pattern TABLE.\n"
  1862. ".separator COL ?ROW? Change the column separator and optionally the row\n"
  1863. " separator for both the output mode and .import\n"
  1864. ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
  1865. ".show Show the current values for various settings\n"
  1866. ".stats ?on|off? Show stats or turn stats on or off\n"
  1867. ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
  1868. ".tables ?TABLE? List names of tables\n"
  1869. " If TABLE specified, only list tables matching\n"
  1870. " LIKE pattern TABLE.\n"
  1871. ".timeout MS Try opening locked tables for MS milliseconds\n"
  1872. ".timer on|off Turn SQL timer on or off\n"
  1873. ".trace FILE|off Output each SQL statement as it is run\n"
  1874. ".vfsinfo ?AUX? Information about the top-level VFS\n"
  1875. ".vfslist List all available VFSes\n"
  1876. ".vfsname ?AUX? Print the name of the VFS stack\n"
  1877. ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
  1878. " Negative values right-justify\n"
  1879. ;
  1880. /* Forward reference */
  1881. static int process_input(ShellState *p, FILE *in);
  1882. /*
  1883. ** Implementation of the "readfile(X)" SQL function. The entire content
  1884. ** of the file named X is read and returned as a BLOB. NULL is returned
  1885. ** if the file does not exist or is unreadable.
  1886. */
  1887. static void readfileFunc(
  1888. sqlite3_context *context,
  1889. int argc,
  1890. sqlite3_value **argv
  1891. ){
  1892. const char *zName;
  1893. FILE *in;
  1894. long nIn;
  1895. void *pBuf;
  1896. UNUSED_PARAMETER(argc);
  1897. zName = (const char*)sqlite3_value_text(argv[0]);
  1898. if( zName==0 ) return;
  1899. in = fopen(zName, "rb");
  1900. if( in==0 ) return;
  1901. fseek(in, 0, SEEK_END);
  1902. nIn = ftell(in);
  1903. rewind(in);
  1904. pBuf = sqlite3_malloc64( nIn );
  1905. if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
  1906. sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
  1907. }else{
  1908. sqlite3_free(pBuf);
  1909. }
  1910. fclose(in);
  1911. }
  1912. /*
  1913. ** Implementation of the "writefile(X,Y)" SQL function. The argument Y
  1914. ** is written into file X. The number of bytes written is returned. Or
  1915. ** NULL is returned if something goes wrong, such as being unable to open
  1916. ** file X for writing.
  1917. */
  1918. static void writefileFunc(
  1919. sqlite3_context *context,
  1920. int argc,
  1921. sqlite3_value **argv
  1922. ){
  1923. FILE *out;
  1924. const char *z;
  1925. sqlite3_int64 rc;
  1926. const char *zFile;
  1927. UNUSED_PARAMETER(argc);
  1928. zFile = (const char*)sqlite3_value_text(argv[0]);
  1929. if( zFile==0 ) return;
  1930. out = fopen(zFile, "wb");
  1931. if( out==0 ) return;
  1932. z = (const char*)sqlite3_value_blob(argv[1]);
  1933. if( z==0 ){
  1934. rc = 0;
  1935. }else{
  1936. rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
  1937. }
  1938. fclose(out);
  1939. sqlite3_result_int64(context, rc);
  1940. }
  1941. /*
  1942. ** Make sure the database is open. If it is not, then open it. If
  1943. ** the database fails to open, print an error message and exit.
  1944. */
  1945. static void open_db(ShellState *p, int keepAlive){
  1946. if( p->db==0 ){
  1947. sqlite3_initialize();
  1948. sqlite3_open(p->zDbFilename, &p->db);
  1949. globalDb = p->db;
  1950. if( p->db && sqlite3_errcode(p->db)==SQLITE_OK ){
  1951. sqlite3_create_function(p->db, "shellstatic", 0, SQLITE_UTF8, 0,
  1952. shellstaticFunc, 0, 0);
  1953. }
  1954. if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
  1955. utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
  1956. p->zDbFilename, sqlite3_errmsg(p->db));
  1957. if( keepAlive ) return;
  1958. exit(1);
  1959. }
  1960. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1961. sqlite3_enable_load_extension(p->db, 1);
  1962. #endif
  1963. sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
  1964. readfileFunc, 0, 0);
  1965. sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
  1966. writefileFunc, 0, 0);
  1967. }
  1968. }
  1969. /*
  1970. ** Do C-language style dequoting.
  1971. **
  1972. ** \a -> alarm
  1973. ** \b -> backspace
  1974. ** \t -> tab
  1975. ** \n -> newline
  1976. ** \v -> vertical tab
  1977. ** \f -> form feed
  1978. ** \r -> carriage return
  1979. ** \s -> space
  1980. ** \" -> "
  1981. ** \' -> '
  1982. ** \\ -> backslash
  1983. ** \NNN -> ascii character NNN in octal
  1984. */
  1985. static void resolve_backslashes(char *z){
  1986. int i, j;
  1987. char c;
  1988. while( *z && *z!='\\' ) z++;
  1989. for(i=j=0; (c = z[i])!=0; i++, j++){
  1990. if( c=='\\' && z[i+1]!=0 ){
  1991. c = z[++i];
  1992. if( c=='a' ){
  1993. c = '\a';
  1994. }else if( c=='b' ){
  1995. c = '\b';
  1996. }else if( c=='t' ){
  1997. c = '\t';
  1998. }else if( c=='n' ){
  1999. c = '\n';
  2000. }else if( c=='v' ){
  2001. c = '\v';
  2002. }else if( c=='f' ){
  2003. c = '\f';
  2004. }else if( c=='r' ){
  2005. c = '\r';
  2006. }else if( c=='"' ){
  2007. c = '"';
  2008. }else if( c=='\'' ){
  2009. c = '\'';
  2010. }else if( c=='\\' ){
  2011. c = '\\';
  2012. }else if( c>='0' && c<='7' ){
  2013. c -= '0';
  2014. if( z[i+1]>='0' && z[i+1]<='7' ){
  2015. i++;
  2016. c = (c<<3) + z[i] - '0';
  2017. if( z[i+1]>='0' && z[i+1]<='7' ){
  2018. i++;
  2019. c = (c<<3) + z[i] - '0';
  2020. }
  2021. }
  2022. }
  2023. }
  2024. z[j] = c;
  2025. }
  2026. if( j<i ) z[j] = 0;
  2027. }
  2028. /*
  2029. ** Return the value of a hexadecimal digit. Return -1 if the input
  2030. ** is not a hex digit.
  2031. */
  2032. static int hexDigitValue(char c){
  2033. if( c>='0' && c<='9' ) return c - '0';
  2034. if( c>='a' && c<='f' ) return c - 'a' + 10;
  2035. if( c>='A' && c<='F' ) return c - 'A' + 10;
  2036. return -1;
  2037. }
  2038. /*
  2039. ** Interpret zArg as an integer value, possibly with suffixes.
  2040. */
  2041. static sqlite3_int64 integerValue(const char *zArg){
  2042. sqlite3_int64 v = 0;
  2043. static const struct { char *zSuffix; int iMult; } aMult[] = {
  2044. { "KiB", 1024 },
  2045. { "MiB", 1024*1024 },
  2046. { "GiB", 1024*1024*1024 },
  2047. { "KB", 1000 },
  2048. { "MB", 1000000 },
  2049. { "GB", 1000000000 },
  2050. { "K", 1000 },
  2051. { "M", 1000000 },
  2052. { "G", 1000000000 },
  2053. };
  2054. int i;
  2055. int isNeg = 0;
  2056. if( zArg[0]=='-' ){
  2057. isNeg = 1;
  2058. zArg++;
  2059. }else if( zArg[0]=='+' ){
  2060. zArg++;
  2061. }
  2062. if( zArg[0]=='0' && zArg[1]=='x' ){
  2063. int x;
  2064. zArg += 2;
  2065. while( (x = hexDigitValue(zArg[0]))>=0 ){
  2066. v = (v<<4) + x;
  2067. zArg++;
  2068. }
  2069. }else{
  2070. while( IsDigit(zArg[0]) ){
  2071. v = v*10 + zArg[0] - '0';
  2072. zArg++;
  2073. }
  2074. }
  2075. for(i=0; i<ArraySize(aMult); i++){
  2076. if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
  2077. v *= aMult[i].iMult;
  2078. break;
  2079. }
  2080. }
  2081. return isNeg? -v : v;
  2082. }
  2083. /*
  2084. ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
  2085. ** for TRUE and FALSE. Return the integer value if appropriate.
  2086. */
  2087. static int booleanValue(char *zArg){
  2088. int i;
  2089. if( zArg[0]=='0' && zArg[1]=='x' ){
  2090. for(i=2; hexDigitValue(zArg[i])>=0; i++){}
  2091. }else{
  2092. for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
  2093. }
  2094. if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
  2095. if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
  2096. return 1;
  2097. }
  2098. if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
  2099. return 0;
  2100. }
  2101. utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
  2102. zArg);
  2103. return 0;
  2104. }
  2105. /*
  2106. ** Close an output file, assuming it is not stderr or stdout
  2107. */
  2108. static void output_file_close(FILE *f){
  2109. if( f && f!=stdout && f!=stderr ) fclose(f);
  2110. }
  2111. /*
  2112. ** Try to open an output file. The names "stdout" and "stderr" are
  2113. ** recognized and do the right thing. NULL is returned if the output
  2114. ** filename is "off".
  2115. */
  2116. static FILE *output_file_open(const char *zFile){
  2117. FILE *f;
  2118. if( strcmp(zFile,"stdout")==0 ){
  2119. f = stdout;
  2120. }else if( strcmp(zFile, "stderr")==0 ){
  2121. f = stderr;
  2122. }else if( strcmp(zFile, "off")==0 ){
  2123. f = 0;
  2124. }else{
  2125. f = fopen(zFile, "wb");
  2126. if( f==0 ){
  2127. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  2128. }
  2129. }
  2130. return f;
  2131. }
  2132. /*
  2133. ** A routine for handling output from sqlite3_trace().
  2134. */
  2135. static void sql_trace_callback(void *pArg, const char *z){
  2136. FILE *f = (FILE*)pArg;
  2137. if( f ){
  2138. int i = (int)strlen(z);
  2139. while( i>0 && z[i-1]==';' ){ i--; }
  2140. utf8_printf(f, "%.*s;\n", i, z);
  2141. }
  2142. }
  2143. /*
  2144. ** A no-op routine that runs with the ".breakpoint" doc-command. This is
  2145. ** a useful spot to set a debugger breakpoint.
  2146. */
  2147. static void test_breakpoint(void){
  2148. static int nCall = 0;
  2149. nCall++;
  2150. }
  2151. /*
  2152. ** An object used to read a CSV and other files for import.
  2153. */
  2154. typedef struct ImportCtx ImportCtx;
  2155. struct ImportCtx {
  2156. const char *zFile; /* Name of the input file */
  2157. FILE *in; /* Read the CSV text from this input stream */
  2158. char *z; /* Accumulated text for a field */
  2159. int n; /* Number of bytes in z */
  2160. int nAlloc; /* Space allocated for z[] */
  2161. int nLine; /* Current line number */
  2162. int cTerm; /* Character that terminated the most recent field */
  2163. int cColSep; /* The column separator character. (Usually ",") */
  2164. int cRowSep; /* The row separator character. (Usually "\n") */
  2165. };
  2166. /* Append a single byte to z[] */
  2167. static void import_append_char(ImportCtx *p, int c){
  2168. if( p->n+1>=p->nAlloc ){
  2169. p->nAlloc += p->nAlloc + 100;
  2170. p->z = sqlite3_realloc64(p->z, p->nAlloc);
  2171. if( p->z==0 ){
  2172. raw_printf(stderr, "out of memory\n");
  2173. exit(1);
  2174. }
  2175. }
  2176. p->z[p->n++] = (char)c;
  2177. }
  2178. /* Read a single field of CSV text. Compatible with rfc4180 and extended
  2179. ** with the option of having a separator other than ",".
  2180. **
  2181. ** + Input comes from p->in.
  2182. ** + Store results in p->z of length p->n. Space to hold p->z comes
  2183. ** from sqlite3_malloc64().
  2184. ** + Use p->cSep as the column separator. The default is ",".
  2185. ** + Use p->rSep as the row separator. The default is "\n".
  2186. ** + Keep track of the line number in p->nLine.
  2187. ** + Store the character that terminates the field in p->cTerm. Store
  2188. ** EOF on end-of-file.
  2189. ** + Report syntax errors on stderr
  2190. */
  2191. static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
  2192. int c;
  2193. int cSep = p->cColSep;
  2194. int rSep = p->cRowSep;
  2195. p->n = 0;
  2196. c = fgetc(p->in);
  2197. if( c==EOF || seenInterrupt ){
  2198. p->cTerm = EOF;
  2199. return 0;
  2200. }
  2201. if( c=='"' ){
  2202. int pc, ppc;
  2203. int startLine = p->nLine;
  2204. int cQuote = c;
  2205. pc = ppc = 0;
  2206. while( 1 ){
  2207. c = fgetc(p->in);
  2208. if( c==rSep ) p->nLine++;
  2209. if( c==cQuote ){
  2210. if( pc==cQuote ){
  2211. pc = 0;
  2212. continue;
  2213. }
  2214. }
  2215. if( (c==cSep && pc==cQuote)
  2216. || (c==rSep && pc==cQuote)
  2217. || (c==rSep && pc=='\r' && ppc==cQuote)
  2218. || (c==EOF && pc==cQuote)
  2219. ){
  2220. do{ p->n--; }while( p->z[p->n]!=cQuote );
  2221. p->cTerm = c;
  2222. break;
  2223. }
  2224. if( pc==cQuote && c!='\r' ){
  2225. utf8_printf(stderr, "%s:%d: unescaped %c character\n",
  2226. p->zFile, p->nLine, cQuote);
  2227. }
  2228. if( c==EOF ){
  2229. utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
  2230. p->zFile, startLine, cQuote);
  2231. p->cTerm = c;
  2232. break;
  2233. }
  2234. import_append_char(p, c);
  2235. ppc = pc;
  2236. pc = c;
  2237. }
  2238. }else{
  2239. while( c!=EOF && c!=cSep && c!=rSep ){
  2240. import_append_char(p, c);
  2241. c = fgetc(p->in);
  2242. }
  2243. if( c==rSep ){
  2244. p->nLine++;
  2245. if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
  2246. }
  2247. p->cTerm = c;
  2248. }
  2249. if( p->z ) p->z[p->n] = 0;
  2250. return p->z;
  2251. }
  2252. /* Read a single field of ASCII delimited text.
  2253. **
  2254. ** + Input comes from p->in.
  2255. ** + Store results in p->z of length p->n. Space to hold p->z comes
  2256. ** from sqlite3_malloc64().
  2257. ** + Use p->cSep as the column separator. The default is "\x1F".
  2258. ** + Use p->rSep as the row separator. The default is "\x1E".
  2259. ** + Keep track of the row number in p->nLine.
  2260. ** + Store the character that terminates the field in p->cTerm. Store
  2261. ** EOF on end-of-file.
  2262. ** + Report syntax errors on stderr
  2263. */
  2264. static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
  2265. int c;
  2266. int cSep = p->cColSep;
  2267. int rSep = p->cRowSep;
  2268. p->n = 0;
  2269. c = fgetc(p->in);
  2270. if( c==EOF || seenInterrupt ){
  2271. p->cTerm = EOF;
  2272. return 0;
  2273. }
  2274. while( c!=EOF && c!=cSep && c!=rSep ){
  2275. import_append_char(p, c);
  2276. c = fgetc(p->in);
  2277. }
  2278. if( c==rSep ){
  2279. p->nLine++;
  2280. }
  2281. p->cTerm = c;
  2282. if( p->z ) p->z[p->n] = 0;
  2283. return p->z;
  2284. }
  2285. /*
  2286. ** Try to transfer data for table zTable. If an error is seen while
  2287. ** moving forward, try to go backwards. The backwards movement won't
  2288. ** work for WITHOUT ROWID tables.
  2289. */
  2290. static void tryToCloneData(
  2291. ShellState *p,
  2292. sqlite3 *newDb,
  2293. const char *zTable
  2294. ){
  2295. sqlite3_stmt *pQuery = 0;
  2296. sqlite3_stmt *pInsert = 0;
  2297. char *zQuery = 0;
  2298. char *zInsert = 0;
  2299. int rc;
  2300. int i, j, n;
  2301. int nTable = (int)strlen(zTable);
  2302. int k = 0;
  2303. int cnt = 0;
  2304. const int spinRate = 10000;
  2305. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
  2306. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  2307. if( rc ){
  2308. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  2309. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  2310. zQuery);
  2311. goto end_data_xfer;
  2312. }
  2313. n = sqlite3_column_count(pQuery);
  2314. zInsert = sqlite3_malloc64(200 + nTable + n*3);
  2315. if( zInsert==0 ){
  2316. raw_printf(stderr, "out of memory\n");
  2317. goto end_data_xfer;
  2318. }
  2319. sqlite3_snprintf(200+nTable,zInsert,
  2320. "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
  2321. i = (int)strlen(zInsert);
  2322. for(j=1; j<n; j++){
  2323. memcpy(zInsert+i, ",?", 2);
  2324. i += 2;
  2325. }
  2326. memcpy(zInsert+i, ");", 3);
  2327. rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
  2328. if( rc ){
  2329. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  2330. sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
  2331. zQuery);
  2332. goto end_data_xfer;
  2333. }
  2334. for(k=0; k<2; k++){
  2335. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  2336. for(i=0; i<n; i++){
  2337. switch( sqlite3_column_type(pQuery, i) ){
  2338. case SQLITE_NULL: {
  2339. sqlite3_bind_null(pInsert, i+1);
  2340. break;
  2341. }
  2342. case SQLITE_INTEGER: {
  2343. sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
  2344. break;
  2345. }
  2346. case SQLITE_FLOAT: {
  2347. sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
  2348. break;
  2349. }
  2350. case SQLITE_TEXT: {
  2351. sqlite3_bind_text(pInsert, i+1,
  2352. (const char*)sqlite3_column_text(pQuery,i),
  2353. -1, SQLITE_STATIC);
  2354. break;
  2355. }
  2356. case SQLITE_BLOB: {
  2357. sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
  2358. sqlite3_column_bytes(pQuery,i),
  2359. SQLITE_STATIC);
  2360. break;
  2361. }
  2362. }
  2363. } /* End for */
  2364. rc = sqlite3_step(pInsert);
  2365. if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  2366. utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
  2367. sqlite3_errmsg(newDb));
  2368. }
  2369. sqlite3_reset(pInsert);
  2370. cnt++;
  2371. if( (cnt%spinRate)==0 ){
  2372. printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
  2373. fflush(stdout);
  2374. }
  2375. } /* End while */
  2376. if( rc==SQLITE_DONE ) break;
  2377. sqlite3_finalize(pQuery);
  2378. sqlite3_free(zQuery);
  2379. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
  2380. zTable);
  2381. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  2382. if( rc ){
  2383. utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
  2384. break;
  2385. }
  2386. } /* End for(k=0...) */
  2387. end_data_xfer:
  2388. sqlite3_finalize(pQuery);
  2389. sqlite3_finalize(pInsert);
  2390. sqlite3_free(zQuery);
  2391. sqlite3_free(zInsert);
  2392. }
  2393. /*
  2394. ** Try to transfer all rows of the schema that match zWhere. For
  2395. ** each row, invoke xForEach() on the object defined by that row.
  2396. ** If an error is encountered while moving forward through the
  2397. ** sqlite_master table, try again moving backwards.
  2398. */
  2399. static void tryToCloneSchema(
  2400. ShellState *p,
  2401. sqlite3 *newDb,
  2402. const char *zWhere,
  2403. void (*xForEach)(ShellState*,sqlite3*,const char*)
  2404. ){
  2405. sqlite3_stmt *pQuery = 0;
  2406. char *zQuery = 0;
  2407. int rc;
  2408. const unsigned char *zName;
  2409. const unsigned char *zSql;
  2410. char *zErrMsg = 0;
  2411. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  2412. " WHERE %s", zWhere);
  2413. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  2414. if( rc ){
  2415. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  2416. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  2417. zQuery);
  2418. goto end_schema_xfer;
  2419. }
  2420. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  2421. zName = sqlite3_column_text(pQuery, 0);
  2422. zSql = sqlite3_column_text(pQuery, 1);
  2423. printf("%s... ", zName); fflush(stdout);
  2424. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  2425. if( zErrMsg ){
  2426. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  2427. sqlite3_free(zErrMsg);
  2428. zErrMsg = 0;
  2429. }
  2430. if( xForEach ){
  2431. xForEach(p, newDb, (const char*)zName);
  2432. }
  2433. printf("done\n");
  2434. }
  2435. if( rc!=SQLITE_DONE ){
  2436. sqlite3_finalize(pQuery);
  2437. sqlite3_free(zQuery);
  2438. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  2439. " WHERE %s ORDER BY rowid DESC", zWhere);
  2440. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  2441. if( rc ){
  2442. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  2443. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  2444. zQuery);
  2445. goto end_schema_xfer;
  2446. }
  2447. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  2448. zName = sqlite3_column_text(pQuery, 0);
  2449. zSql = sqlite3_column_text(pQuery, 1);
  2450. printf("%s... ", zName); fflush(stdout);
  2451. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  2452. if( zErrMsg ){
  2453. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  2454. sqlite3_free(zErrMsg);
  2455. zErrMsg = 0;
  2456. }
  2457. if( xForEach ){
  2458. xForEach(p, newDb, (const char*)zName);
  2459. }
  2460. printf("done\n");
  2461. }
  2462. }
  2463. end_schema_xfer:
  2464. sqlite3_finalize(pQuery);
  2465. sqlite3_free(zQuery);
  2466. }
  2467. /*
  2468. ** Open a new database file named "zNewDb". Try to recover as much information
  2469. ** as possible out of the main database (which might be corrupt) and write it
  2470. ** into zNewDb.
  2471. */
  2472. static void tryToClone(ShellState *p, const char *zNewDb){
  2473. int rc;
  2474. sqlite3 *newDb = 0;
  2475. if( access(zNewDb,0)==0 ){
  2476. utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
  2477. return;
  2478. }
  2479. rc = sqlite3_open(zNewDb, &newDb);
  2480. if( rc ){
  2481. utf8_printf(stderr, "Cannot create output database: %s\n",
  2482. sqlite3_errmsg(newDb));
  2483. }else{
  2484. sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
  2485. sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
  2486. tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
  2487. tryToCloneSchema(p, newDb, "type!='table'", 0);
  2488. sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
  2489. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  2490. }
  2491. sqlite3_close(newDb);
  2492. }
  2493. /*
  2494. ** Change the output file back to stdout
  2495. */
  2496. static void output_reset(ShellState *p){
  2497. if( p->outfile[0]=='|' ){
  2498. #ifndef SQLITE_OMIT_POPEN
  2499. pclose(p->out);
  2500. #endif
  2501. }else{
  2502. output_file_close(p->out);
  2503. }
  2504. p->outfile[0] = 0;
  2505. p->out = stdout;
  2506. }
  2507. /*
  2508. ** Run an SQL command and return the single integer result.
  2509. */
  2510. static int db_int(ShellState *p, const char *zSql){
  2511. sqlite3_stmt *pStmt;
  2512. int res = 0;
  2513. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  2514. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  2515. res = sqlite3_column_int(pStmt,0);
  2516. }
  2517. sqlite3_finalize(pStmt);
  2518. return res;
  2519. }
  2520. /*
  2521. ** Convert a 2-byte or 4-byte big-endian integer into a native integer
  2522. */
  2523. unsigned int get2byteInt(unsigned char *a){
  2524. return (a[0]<<8) + a[1];
  2525. }
  2526. unsigned int get4byteInt(unsigned char *a){
  2527. return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
  2528. }
  2529. /*
  2530. ** Implementation of the ".info" command.
  2531. **
  2532. ** Return 1 on error, 2 to exit, and 0 otherwise.
  2533. */
  2534. static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
  2535. static const struct { const char *zName; int ofst; } aField[] = {
  2536. { "file change counter:", 24 },
  2537. { "database page count:", 28 },
  2538. { "freelist page count:", 36 },
  2539. { "schema cookie:", 40 },
  2540. { "schema format:", 44 },
  2541. { "default cache size:", 48 },
  2542. { "autovacuum top root:", 52 },
  2543. { "incremental vacuum:", 64 },
  2544. { "text encoding:", 56 },
  2545. { "user version:", 60 },
  2546. { "application id:", 68 },
  2547. { "software version:", 96 },
  2548. };
  2549. static const struct { const char *zName; const char *zSql; } aQuery[] = {
  2550. { "number of tables:",
  2551. "SELECT count(*) FROM %s WHERE type='table'" },
  2552. { "number of indexes:",
  2553. "SELECT count(*) FROM %s WHERE type='index'" },
  2554. { "number of triggers:",
  2555. "SELECT count(*) FROM %s WHERE type='trigger'" },
  2556. { "number of views:",
  2557. "SELECT count(*) FROM %s WHERE type='view'" },
  2558. { "schema size:",
  2559. "SELECT total(length(sql)) FROM %s" },
  2560. };
  2561. sqlite3_file *pFile = 0;
  2562. int i;
  2563. char *zSchemaTab;
  2564. char *zDb = nArg>=2 ? azArg[1] : "main";
  2565. unsigned char aHdr[100];
  2566. open_db(p, 0);
  2567. if( p->db==0 ) return 1;
  2568. sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
  2569. if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
  2570. return 1;
  2571. }
  2572. i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
  2573. if( i!=SQLITE_OK ){
  2574. raw_printf(stderr, "unable to read database header\n");
  2575. return 1;
  2576. }
  2577. i = get2byteInt(aHdr+16);
  2578. if( i==1 ) i = 65536;
  2579. utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
  2580. utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
  2581. utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
  2582. utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
  2583. for(i=0; i<ArraySize(aField); i++){
  2584. int ofst = aField[i].ofst;
  2585. unsigned int val = get4byteInt(aHdr + ofst);
  2586. utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
  2587. switch( ofst ){
  2588. case 56: {
  2589. if( val==1 ) raw_printf(p->out, " (utf8)");
  2590. if( val==2 ) raw_printf(p->out, " (utf16le)");
  2591. if( val==3 ) raw_printf(p->out, " (utf16be)");
  2592. }
  2593. }
  2594. raw_printf(p->out, "\n");
  2595. }
  2596. if( zDb==0 ){
  2597. zSchemaTab = sqlite3_mprintf("main.sqlite_master");
  2598. }else if( strcmp(zDb,"temp")==0 ){
  2599. zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
  2600. }else{
  2601. zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
  2602. }
  2603. for(i=0; i<ArraySize(aQuery); i++){
  2604. char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
  2605. int val = db_int(p, zSql);
  2606. sqlite3_free(zSql);
  2607. utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
  2608. }
  2609. sqlite3_free(zSchemaTab);
  2610. return 0;
  2611. }
  2612. /*
  2613. ** Print the current sqlite3_errmsg() value to stderr and return 1.
  2614. */
  2615. static int shellDatabaseError(sqlite3 *db){
  2616. const char *zErr = sqlite3_errmsg(db);
  2617. utf8_printf(stderr, "Error: %s\n", zErr);
  2618. return 1;
  2619. }
  2620. /*
  2621. ** Print an out-of-memory message to stderr and return 1.
  2622. */
  2623. static int shellNomemError(void){
  2624. raw_printf(stderr, "Error: out of memory\n");
  2625. return 1;
  2626. }
  2627. /*
  2628. ** If an input line begins with "." then invoke this routine to
  2629. ** process that line.
  2630. **
  2631. ** Return 1 on error, 2 to exit, and 0 otherwise.
  2632. */
  2633. static int do_meta_command(char *zLine, ShellState *p){
  2634. int h = 1;
  2635. int nArg = 0;
  2636. int n, c;
  2637. int rc = 0;
  2638. char *azArg[50];
  2639. /* Parse the input line into tokens.
  2640. */
  2641. while( zLine[h] && nArg<ArraySize(azArg) ){
  2642. while( IsSpace(zLine[h]) ){ h++; }
  2643. if( zLine[h]==0 ) break;
  2644. if( zLine[h]=='\'' || zLine[h]=='"' ){
  2645. int delim = zLine[h++];
  2646. azArg[nArg++] = &zLine[h];
  2647. while( zLine[h] && zLine[h]!=delim ){
  2648. if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
  2649. h++;
  2650. }
  2651. if( zLine[h]==delim ){
  2652. zLine[h++] = 0;
  2653. }
  2654. if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  2655. }else{
  2656. azArg[nArg++] = &zLine[h];
  2657. while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
  2658. if( zLine[h] ) zLine[h++] = 0;
  2659. resolve_backslashes(azArg[nArg-1]);
  2660. }
  2661. }
  2662. /* Process the input line.
  2663. */
  2664. if( nArg==0 ) return 0; /* no tokens, no error */
  2665. n = strlen30(azArg[0]);
  2666. c = azArg[0][0];
  2667. if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
  2668. || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
  2669. ){
  2670. const char *zDestFile = 0;
  2671. const char *zDb = 0;
  2672. sqlite3 *pDest;
  2673. sqlite3_backup *pBackup;
  2674. int j;
  2675. for(j=1; j<nArg; j++){
  2676. const char *z = azArg[j];
  2677. if( z[0]=='-' ){
  2678. while( z[0]=='-' ) z++;
  2679. /* No options to process at this time */
  2680. {
  2681. utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
  2682. return 1;
  2683. }
  2684. }else if( zDestFile==0 ){
  2685. zDestFile = azArg[j];
  2686. }else if( zDb==0 ){
  2687. zDb = zDestFile;
  2688. zDestFile = azArg[j];
  2689. }else{
  2690. raw_printf(stderr, "too many arguments to .backup\n");
  2691. return 1;
  2692. }
  2693. }
  2694. if( zDestFile==0 ){
  2695. raw_printf(stderr, "missing FILENAME argument on .backup\n");
  2696. return 1;
  2697. }
  2698. if( zDb==0 ) zDb = "main";
  2699. rc = sqlite3_open(zDestFile, &pDest);
  2700. if( rc!=SQLITE_OK ){
  2701. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  2702. sqlite3_close(pDest);
  2703. return 1;
  2704. }
  2705. open_db(p, 0);
  2706. pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  2707. if( pBackup==0 ){
  2708. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  2709. sqlite3_close(pDest);
  2710. return 1;
  2711. }
  2712. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  2713. sqlite3_backup_finish(pBackup);
  2714. if( rc==SQLITE_DONE ){
  2715. rc = 0;
  2716. }else{
  2717. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  2718. rc = 1;
  2719. }
  2720. sqlite3_close(pDest);
  2721. }else
  2722. if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
  2723. if( nArg==2 ){
  2724. bail_on_error = booleanValue(azArg[1]);
  2725. }else{
  2726. raw_printf(stderr, "Usage: .bail on|off\n");
  2727. rc = 1;
  2728. }
  2729. }else
  2730. if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
  2731. if( nArg==2 ){
  2732. if( booleanValue(azArg[1]) ){
  2733. setBinaryMode(p->out);
  2734. }else{
  2735. setTextMode(p->out);
  2736. }
  2737. }else{
  2738. raw_printf(stderr, "Usage: .binary on|off\n");
  2739. rc = 1;
  2740. }
  2741. }else
  2742. /* The undocumented ".breakpoint" command causes a call to the no-op
  2743. ** routine named test_breakpoint().
  2744. */
  2745. if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
  2746. test_breakpoint();
  2747. }else
  2748. if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
  2749. if( nArg==2 ){
  2750. p->countChanges = booleanValue(azArg[1]);
  2751. }else{
  2752. raw_printf(stderr, "Usage: .changes on|off\n");
  2753. rc = 1;
  2754. }
  2755. }else
  2756. if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
  2757. if( nArg==2 ){
  2758. tryToClone(p, azArg[1]);
  2759. }else{
  2760. raw_printf(stderr, "Usage: .clone FILENAME\n");
  2761. rc = 1;
  2762. }
  2763. }else
  2764. if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
  2765. ShellState data;
  2766. char *zErrMsg = 0;
  2767. open_db(p, 0);
  2768. memcpy(&data, p, sizeof(data));
  2769. data.showHeader = 1;
  2770. data.cMode = data.mode = MODE_Column;
  2771. data.colWidth[0] = 3;
  2772. data.colWidth[1] = 15;
  2773. data.colWidth[2] = 58;
  2774. data.cnt = 0;
  2775. sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
  2776. if( zErrMsg ){
  2777. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  2778. sqlite3_free(zErrMsg);
  2779. rc = 1;
  2780. }
  2781. }else
  2782. if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
  2783. rc = shell_dbinfo_command(p, nArg, azArg);
  2784. }else
  2785. if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
  2786. open_db(p, 0);
  2787. /* When playing back a "dump", the content might appear in an order
  2788. ** which causes immediate foreign key constraints to be violated.
  2789. ** So disable foreign-key constraint enforcement to prevent problems. */
  2790. if( nArg!=1 && nArg!=2 ){
  2791. raw_printf(stderr, "Usage: .dump ?LIKE-PATTERN?\n");
  2792. rc = 1;
  2793. goto meta_command_exit;
  2794. }
  2795. raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
  2796. raw_printf(p->out, "BEGIN TRANSACTION;\n");
  2797. p->writableSchema = 0;
  2798. sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
  2799. p->nErr = 0;
  2800. if( nArg==1 ){
  2801. run_schema_dump_query(p,
  2802. "SELECT name, type, sql FROM sqlite_master "
  2803. "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
  2804. );
  2805. run_schema_dump_query(p,
  2806. "SELECT name, type, sql FROM sqlite_master "
  2807. "WHERE name=='sqlite_sequence'"
  2808. );
  2809. run_table_dump_query(p,
  2810. "SELECT sql FROM sqlite_master "
  2811. "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
  2812. );
  2813. }else{
  2814. int i;
  2815. for(i=1; i<nArg; i++){
  2816. zShellStatic = azArg[i];
  2817. run_schema_dump_query(p,
  2818. "SELECT name, type, sql FROM sqlite_master "
  2819. "WHERE tbl_name LIKE shellstatic() AND type=='table'"
  2820. " AND sql NOT NULL");
  2821. run_table_dump_query(p,
  2822. "SELECT sql FROM sqlite_master "
  2823. "WHERE sql NOT NULL"
  2824. " AND type IN ('index','trigger','view')"
  2825. " AND tbl_name LIKE shellstatic()", 0
  2826. );
  2827. zShellStatic = 0;
  2828. }
  2829. }
  2830. if( p->writableSchema ){
  2831. raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
  2832. p->writableSchema = 0;
  2833. }
  2834. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  2835. sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
  2836. raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
  2837. }else
  2838. if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
  2839. if( nArg==2 ){
  2840. p->echoOn = booleanValue(azArg[1]);
  2841. }else{
  2842. raw_printf(stderr, "Usage: .echo on|off\n");
  2843. rc = 1;
  2844. }
  2845. }else
  2846. if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
  2847. if( nArg==2 ){
  2848. p->autoEQP = booleanValue(azArg[1]);
  2849. }else{
  2850. raw_printf(stderr, "Usage: .eqp on|off\n");
  2851. rc = 1;
  2852. }
  2853. }else
  2854. if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
  2855. if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
  2856. rc = 2;
  2857. }else
  2858. if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
  2859. int val = 1;
  2860. if( nArg>=2 ){
  2861. if( strcmp(azArg[1],"auto")==0 ){
  2862. val = 99;
  2863. }else{
  2864. val = booleanValue(azArg[1]);
  2865. }
  2866. }
  2867. if( val==1 && p->mode!=MODE_Explain ){
  2868. p->normalMode = p->mode;
  2869. p->mode = MODE_Explain;
  2870. p->autoExplain = 0;
  2871. }else if( val==0 ){
  2872. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  2873. p->autoExplain = 0;
  2874. }else if( val==99 ){
  2875. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  2876. p->autoExplain = 1;
  2877. }
  2878. }else
  2879. if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
  2880. ShellState data;
  2881. char *zErrMsg = 0;
  2882. int doStats = 0;
  2883. if( nArg!=1 ){
  2884. raw_printf(stderr, "Usage: .fullschema\n");
  2885. rc = 1;
  2886. goto meta_command_exit;
  2887. }
  2888. open_db(p, 0);
  2889. memcpy(&data, p, sizeof(data));
  2890. data.showHeader = 0;
  2891. data.cMode = data.mode = MODE_Semi;
  2892. rc = sqlite3_exec(p->db,
  2893. "SELECT sql FROM"
  2894. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  2895. " FROM sqlite_master UNION ALL"
  2896. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  2897. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  2898. "ORDER BY rowid",
  2899. callback, &data, &zErrMsg
  2900. );
  2901. if( rc==SQLITE_OK ){
  2902. sqlite3_stmt *pStmt;
  2903. rc = sqlite3_prepare_v2(p->db,
  2904. "SELECT rowid FROM sqlite_master"
  2905. " WHERE name GLOB 'sqlite_stat[134]'",
  2906. -1, &pStmt, 0);
  2907. doStats = sqlite3_step(pStmt)==SQLITE_ROW;
  2908. sqlite3_finalize(pStmt);
  2909. }
  2910. if( doStats==0 ){
  2911. raw_printf(p->out, "/* No STAT tables available */\n");
  2912. }else{
  2913. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  2914. sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
  2915. callback, &data, &zErrMsg);
  2916. data.cMode = data.mode = MODE_Insert;
  2917. data.zDestTable = "sqlite_stat1";
  2918. shell_exec(p->db, "SELECT * FROM sqlite_stat1",
  2919. shell_callback, &data,&zErrMsg);
  2920. data.zDestTable = "sqlite_stat3";
  2921. shell_exec(p->db, "SELECT * FROM sqlite_stat3",
  2922. shell_callback, &data,&zErrMsg);
  2923. data.zDestTable = "sqlite_stat4";
  2924. shell_exec(p->db, "SELECT * FROM sqlite_stat4",
  2925. shell_callback, &data, &zErrMsg);
  2926. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  2927. }
  2928. }else
  2929. if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
  2930. if( nArg==2 ){
  2931. p->showHeader = booleanValue(azArg[1]);
  2932. }else{
  2933. raw_printf(stderr, "Usage: .headers on|off\n");
  2934. rc = 1;
  2935. }
  2936. }else
  2937. if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  2938. utf8_printf(p->out, "%s", zHelp);
  2939. }else
  2940. if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
  2941. char *zTable; /* Insert data into this table */
  2942. char *zFile; /* Name of file to extra content from */
  2943. sqlite3_stmt *pStmt = NULL; /* A statement */
  2944. int nCol; /* Number of columns in the table */
  2945. int nByte; /* Number of bytes in an SQL string */
  2946. int i, j; /* Loop counters */
  2947. int needCommit; /* True to COMMIT or ROLLBACK at end */
  2948. int nSep; /* Number of bytes in p->colSeparator[] */
  2949. char *zSql; /* An SQL statement */
  2950. ImportCtx sCtx; /* Reader context */
  2951. char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
  2952. int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
  2953. if( nArg!=3 ){
  2954. raw_printf(stderr, "Usage: .import FILE TABLE\n");
  2955. goto meta_command_exit;
  2956. }
  2957. zFile = azArg[1];
  2958. zTable = azArg[2];
  2959. seenInterrupt = 0;
  2960. memset(&sCtx, 0, sizeof(sCtx));
  2961. open_db(p, 0);
  2962. nSep = strlen30(p->colSeparator);
  2963. if( nSep==0 ){
  2964. raw_printf(stderr,
  2965. "Error: non-null column separator required for import\n");
  2966. return 1;
  2967. }
  2968. if( nSep>1 ){
  2969. raw_printf(stderr, "Error: multi-character column separators not allowed"
  2970. " for import\n");
  2971. return 1;
  2972. }
  2973. nSep = strlen30(p->rowSeparator);
  2974. if( nSep==0 ){
  2975. raw_printf(stderr, "Error: non-null row separator required for import\n");
  2976. return 1;
  2977. }
  2978. if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
  2979. /* When importing CSV (only), if the row separator is set to the
  2980. ** default output row separator, change it to the default input
  2981. ** row separator. This avoids having to maintain different input
  2982. ** and output row separators. */
  2983. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  2984. nSep = strlen30(p->rowSeparator);
  2985. }
  2986. if( nSep>1 ){
  2987. raw_printf(stderr, "Error: multi-character row separators not allowed"
  2988. " for import\n");
  2989. return 1;
  2990. }
  2991. sCtx.zFile = zFile;
  2992. sCtx.nLine = 1;
  2993. if( sCtx.zFile[0]=='|' ){
  2994. #ifdef SQLITE_OMIT_POPEN
  2995. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  2996. return 1;
  2997. #else
  2998. sCtx.in = popen(sCtx.zFile+1, "r");
  2999. sCtx.zFile = "<pipe>";
  3000. xCloser = pclose;
  3001. #endif
  3002. }else{
  3003. sCtx.in = fopen(sCtx.zFile, "rb");
  3004. xCloser = fclose;
  3005. }
  3006. if( p->mode==MODE_Ascii ){
  3007. xRead = ascii_read_one_field;
  3008. }else{
  3009. xRead = csv_read_one_field;
  3010. }
  3011. if( sCtx.in==0 ){
  3012. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  3013. return 1;
  3014. }
  3015. sCtx.cColSep = p->colSeparator[0];
  3016. sCtx.cRowSep = p->rowSeparator[0];
  3017. zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
  3018. if( zSql==0 ){
  3019. raw_printf(stderr, "Error: out of memory\n");
  3020. xCloser(sCtx.in);
  3021. return 1;
  3022. }
  3023. nByte = strlen30(zSql);
  3024. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3025. import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
  3026. if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
  3027. char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
  3028. char cSep = '(';
  3029. while( xRead(&sCtx) ){
  3030. zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
  3031. cSep = ',';
  3032. if( sCtx.cTerm!=sCtx.cColSep ) break;
  3033. }
  3034. if( cSep=='(' ){
  3035. sqlite3_free(zCreate);
  3036. sqlite3_free(sCtx.z);
  3037. xCloser(sCtx.in);
  3038. utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
  3039. return 1;
  3040. }
  3041. zCreate = sqlite3_mprintf("%z\n)", zCreate);
  3042. rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
  3043. sqlite3_free(zCreate);
  3044. if( rc ){
  3045. utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
  3046. sqlite3_errmsg(p->db));
  3047. sqlite3_free(sCtx.z);
  3048. xCloser(sCtx.in);
  3049. return 1;
  3050. }
  3051. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3052. }
  3053. sqlite3_free(zSql);
  3054. if( rc ){
  3055. if (pStmt) sqlite3_finalize(pStmt);
  3056. utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
  3057. xCloser(sCtx.in);
  3058. return 1;
  3059. }
  3060. nCol = sqlite3_column_count(pStmt);
  3061. sqlite3_finalize(pStmt);
  3062. pStmt = 0;
  3063. if( nCol==0 ) return 0; /* no columns, no error */
  3064. zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
  3065. if( zSql==0 ){
  3066. raw_printf(stderr, "Error: out of memory\n");
  3067. xCloser(sCtx.in);
  3068. return 1;
  3069. }
  3070. sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
  3071. j = strlen30(zSql);
  3072. for(i=1; i<nCol; i++){
  3073. zSql[j++] = ',';
  3074. zSql[j++] = '?';
  3075. }
  3076. zSql[j++] = ')';
  3077. zSql[j] = 0;
  3078. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3079. sqlite3_free(zSql);
  3080. if( rc ){
  3081. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  3082. if (pStmt) sqlite3_finalize(pStmt);
  3083. xCloser(sCtx.in);
  3084. return 1;
  3085. }
  3086. needCommit = sqlite3_get_autocommit(p->db);
  3087. if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
  3088. do{
  3089. int startLine = sCtx.nLine;
  3090. for(i=0; i<nCol; i++){
  3091. char *z = xRead(&sCtx);
  3092. /*
  3093. ** Did we reach end-of-file before finding any columns?
  3094. ** If so, stop instead of NULL filling the remaining columns.
  3095. */
  3096. if( z==0 && i==0 ) break;
  3097. /*
  3098. ** Did we reach end-of-file OR end-of-line before finding any
  3099. ** columns in ASCII mode? If so, stop instead of NULL filling
  3100. ** the remaining columns.
  3101. */
  3102. if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
  3103. sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
  3104. if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
  3105. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  3106. "filling the rest with NULL\n",
  3107. sCtx.zFile, startLine, nCol, i+1);
  3108. i += 2;
  3109. while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
  3110. }
  3111. }
  3112. if( sCtx.cTerm==sCtx.cColSep ){
  3113. do{
  3114. xRead(&sCtx);
  3115. i++;
  3116. }while( sCtx.cTerm==sCtx.cColSep );
  3117. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  3118. "extras ignored\n",
  3119. sCtx.zFile, startLine, nCol, i);
  3120. }
  3121. if( i>=nCol ){
  3122. sqlite3_step(pStmt);
  3123. rc = sqlite3_reset(pStmt);
  3124. if( rc!=SQLITE_OK ){
  3125. utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
  3126. startLine, sqlite3_errmsg(p->db));
  3127. }
  3128. }
  3129. }while( sCtx.cTerm!=EOF );
  3130. xCloser(sCtx.in);
  3131. sqlite3_free(sCtx.z);
  3132. sqlite3_finalize(pStmt);
  3133. if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
  3134. }else
  3135. if( c=='i' && (strncmp(azArg[0], "indices", n)==0
  3136. || strncmp(azArg[0], "indexes", n)==0) ){
  3137. ShellState data;
  3138. char *zErrMsg = 0;
  3139. open_db(p, 0);
  3140. memcpy(&data, p, sizeof(data));
  3141. data.showHeader = 0;
  3142. data.cMode = data.mode = MODE_List;
  3143. if( nArg==1 ){
  3144. rc = sqlite3_exec(p->db,
  3145. "SELECT name FROM sqlite_master "
  3146. "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
  3147. "UNION ALL "
  3148. "SELECT name FROM sqlite_temp_master "
  3149. "WHERE type='index' "
  3150. "ORDER BY 1",
  3151. callback, &data, &zErrMsg
  3152. );
  3153. }else if( nArg==2 ){
  3154. zShellStatic = azArg[1];
  3155. rc = sqlite3_exec(p->db,
  3156. "SELECT name FROM sqlite_master "
  3157. "WHERE type='index' AND tbl_name LIKE shellstatic() "
  3158. "UNION ALL "
  3159. "SELECT name FROM sqlite_temp_master "
  3160. "WHERE type='index' AND tbl_name LIKE shellstatic() "
  3161. "ORDER BY 1",
  3162. callback, &data, &zErrMsg
  3163. );
  3164. zShellStatic = 0;
  3165. }else{
  3166. raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
  3167. rc = 1;
  3168. goto meta_command_exit;
  3169. }
  3170. if( zErrMsg ){
  3171. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  3172. sqlite3_free(zErrMsg);
  3173. rc = 1;
  3174. }else if( rc != SQLITE_OK ){
  3175. raw_printf(stderr,
  3176. "Error: querying sqlite_master and sqlite_temp_master\n");
  3177. rc = 1;
  3178. }
  3179. }else
  3180. #ifdef SQLITE_ENABLE_IOTRACE
  3181. if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
  3182. SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
  3183. if( iotrace && iotrace!=stdout ) fclose(iotrace);
  3184. iotrace = 0;
  3185. if( nArg<2 ){
  3186. sqlite3IoTrace = 0;
  3187. }else if( strcmp(azArg[1], "-")==0 ){
  3188. sqlite3IoTrace = iotracePrintf;
  3189. iotrace = stdout;
  3190. }else{
  3191. iotrace = fopen(azArg[1], "w");
  3192. if( iotrace==0 ){
  3193. utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  3194. sqlite3IoTrace = 0;
  3195. rc = 1;
  3196. }else{
  3197. sqlite3IoTrace = iotracePrintf;
  3198. }
  3199. }
  3200. }else
  3201. #endif
  3202. if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
  3203. static const struct {
  3204. const char *zLimitName; /* Name of a limit */
  3205. int limitCode; /* Integer code for that limit */
  3206. } aLimit[] = {
  3207. { "length", SQLITE_LIMIT_LENGTH },
  3208. { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
  3209. { "column", SQLITE_LIMIT_COLUMN },
  3210. { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
  3211. { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
  3212. { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
  3213. { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
  3214. { "attached", SQLITE_LIMIT_ATTACHED },
  3215. { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
  3216. { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
  3217. { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
  3218. { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
  3219. };
  3220. int i, n2;
  3221. open_db(p, 0);
  3222. if( nArg==1 ){
  3223. for(i=0; i<ArraySize(aLimit); i++){
  3224. printf("%20s %d\n", aLimit[i].zLimitName,
  3225. sqlite3_limit(p->db, aLimit[i].limitCode, -1));
  3226. }
  3227. }else if( nArg>3 ){
  3228. raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
  3229. rc = 1;
  3230. goto meta_command_exit;
  3231. }else{
  3232. int iLimit = -1;
  3233. n2 = strlen30(azArg[1]);
  3234. for(i=0; i<ArraySize(aLimit); i++){
  3235. if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
  3236. if( iLimit<0 ){
  3237. iLimit = i;
  3238. }else{
  3239. utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
  3240. rc = 1;
  3241. goto meta_command_exit;
  3242. }
  3243. }
  3244. }
  3245. if( iLimit<0 ){
  3246. utf8_printf(stderr, "unknown limit: \"%s\"\n"
  3247. "enter \".limits\" with no arguments for a list.\n",
  3248. azArg[1]);
  3249. rc = 1;
  3250. goto meta_command_exit;
  3251. }
  3252. if( nArg==3 ){
  3253. sqlite3_limit(p->db, aLimit[iLimit].limitCode,
  3254. (int)integerValue(azArg[2]));
  3255. }
  3256. printf("%20s %d\n", aLimit[iLimit].zLimitName,
  3257. sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
  3258. }
  3259. }else
  3260. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  3261. if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
  3262. const char *zFile, *zProc;
  3263. char *zErrMsg = 0;
  3264. if( nArg<2 ){
  3265. raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
  3266. rc = 1;
  3267. goto meta_command_exit;
  3268. }
  3269. zFile = azArg[1];
  3270. zProc = nArg>=3 ? azArg[2] : 0;
  3271. open_db(p, 0);
  3272. rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  3273. if( rc!=SQLITE_OK ){
  3274. utf8_printf(stderr, "Error: %s\n", zErrMsg);
  3275. sqlite3_free(zErrMsg);
  3276. rc = 1;
  3277. }
  3278. }else
  3279. #endif
  3280. if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
  3281. if( nArg!=2 ){
  3282. raw_printf(stderr, "Usage: .log FILENAME\n");
  3283. rc = 1;
  3284. }else{
  3285. const char *zFile = azArg[1];
  3286. output_file_close(p->pLog);
  3287. p->pLog = output_file_open(zFile);
  3288. }
  3289. }else
  3290. if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
  3291. const char *zMode = nArg>=2 ? azArg[1] : "";
  3292. int n2 = (int)strlen(zMode);
  3293. int c2 = zMode[0];
  3294. if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
  3295. p->mode = MODE_Line;
  3296. }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
  3297. p->mode = MODE_Column;
  3298. }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
  3299. p->mode = MODE_List;
  3300. }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
  3301. p->mode = MODE_Html;
  3302. }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
  3303. p->mode = MODE_Tcl;
  3304. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
  3305. }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
  3306. p->mode = MODE_Csv;
  3307. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  3308. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  3309. }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
  3310. p->mode = MODE_List;
  3311. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
  3312. }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
  3313. p->mode = MODE_Insert;
  3314. set_table_name(p, nArg>=3 ? azArg[2] : "table");
  3315. }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
  3316. p->mode = MODE_Ascii;
  3317. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
  3318. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
  3319. }else {
  3320. raw_printf(stderr, "Error: mode should be one of: "
  3321. "ascii column csv html insert line list tabs tcl\n");
  3322. rc = 1;
  3323. }
  3324. p->cMode = p->mode;
  3325. }else
  3326. if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
  3327. if( nArg==2 ){
  3328. sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
  3329. "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
  3330. }else{
  3331. raw_printf(stderr, "Usage: .nullvalue STRING\n");
  3332. rc = 1;
  3333. }
  3334. }else
  3335. if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
  3336. sqlite3 *savedDb = p->db;
  3337. const char *zSavedFilename = p->zDbFilename;
  3338. char *zNewFilename = 0;
  3339. p->db = 0;
  3340. if( nArg>=2 ) zNewFilename = sqlite3_mprintf("%s", azArg[1]);
  3341. p->zDbFilename = zNewFilename;
  3342. open_db(p, 1);
  3343. if( p->db!=0 ){
  3344. sqlite3_close(savedDb);
  3345. sqlite3_free(p->zFreeOnClose);
  3346. p->zFreeOnClose = zNewFilename;
  3347. }else{
  3348. sqlite3_free(zNewFilename);
  3349. p->db = savedDb;
  3350. p->zDbFilename = zSavedFilename;
  3351. }
  3352. }else
  3353. if( c=='o'
  3354. && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
  3355. ){
  3356. const char *zFile = nArg>=2 ? azArg[1] : "stdout";
  3357. if( nArg>2 ){
  3358. utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
  3359. rc = 1;
  3360. goto meta_command_exit;
  3361. }
  3362. if( n>1 && strncmp(azArg[0], "once", n)==0 ){
  3363. if( nArg<2 ){
  3364. raw_printf(stderr, "Usage: .once FILE\n");
  3365. rc = 1;
  3366. goto meta_command_exit;
  3367. }
  3368. p->outCount = 2;
  3369. }else{
  3370. p->outCount = 0;
  3371. }
  3372. output_reset(p);
  3373. if( zFile[0]=='|' ){
  3374. #ifdef SQLITE_OMIT_POPEN
  3375. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  3376. rc = 1;
  3377. p->out = stdout;
  3378. #else
  3379. p->out = popen(zFile + 1, "w");
  3380. if( p->out==0 ){
  3381. utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
  3382. p->out = stdout;
  3383. rc = 1;
  3384. }else{
  3385. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  3386. }
  3387. #endif
  3388. }else{
  3389. p->out = output_file_open(zFile);
  3390. if( p->out==0 ){
  3391. if( strcmp(zFile,"off")!=0 ){
  3392. utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
  3393. }
  3394. p->out = stdout;
  3395. rc = 1;
  3396. } else {
  3397. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  3398. }
  3399. }
  3400. }else
  3401. if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
  3402. int i;
  3403. for(i=1; i<nArg; i++){
  3404. if( i>1 ) raw_printf(p->out, " ");
  3405. utf8_printf(p->out, "%s", azArg[i]);
  3406. }
  3407. raw_printf(p->out, "\n");
  3408. }else
  3409. if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
  3410. if( nArg >= 2) {
  3411. strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  3412. }
  3413. if( nArg >= 3) {
  3414. strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  3415. }
  3416. }else
  3417. if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
  3418. rc = 2;
  3419. }else
  3420. if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
  3421. FILE *alt;
  3422. if( nArg!=2 ){
  3423. raw_printf(stderr, "Usage: .read FILE\n");
  3424. rc = 1;
  3425. goto meta_command_exit;
  3426. }
  3427. alt = fopen(azArg[1], "rb");
  3428. if( alt==0 ){
  3429. utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
  3430. rc = 1;
  3431. }else{
  3432. rc = process_input(p, alt);
  3433. fclose(alt);
  3434. }
  3435. }else
  3436. if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
  3437. const char *zSrcFile;
  3438. const char *zDb;
  3439. sqlite3 *pSrc;
  3440. sqlite3_backup *pBackup;
  3441. int nTimeout = 0;
  3442. if( nArg==2 ){
  3443. zSrcFile = azArg[1];
  3444. zDb = "main";
  3445. }else if( nArg==3 ){
  3446. zSrcFile = azArg[2];
  3447. zDb = azArg[1];
  3448. }else{
  3449. raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
  3450. rc = 1;
  3451. goto meta_command_exit;
  3452. }
  3453. rc = sqlite3_open(zSrcFile, &pSrc);
  3454. if( rc!=SQLITE_OK ){
  3455. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  3456. sqlite3_close(pSrc);
  3457. return 1;
  3458. }
  3459. open_db(p, 0);
  3460. pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  3461. if( pBackup==0 ){
  3462. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  3463. sqlite3_close(pSrc);
  3464. return 1;
  3465. }
  3466. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  3467. || rc==SQLITE_BUSY ){
  3468. if( rc==SQLITE_BUSY ){
  3469. if( nTimeout++ >= 3 ) break;
  3470. sqlite3_sleep(100);
  3471. }
  3472. }
  3473. sqlite3_backup_finish(pBackup);
  3474. if( rc==SQLITE_DONE ){
  3475. rc = 0;
  3476. }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  3477. raw_printf(stderr, "Error: source database is busy\n");
  3478. rc = 1;
  3479. }else{
  3480. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  3481. rc = 1;
  3482. }
  3483. sqlite3_close(pSrc);
  3484. }else
  3485. if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
  3486. if( nArg==2 ){
  3487. p->scanstatsOn = booleanValue(azArg[1]);
  3488. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  3489. raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
  3490. #endif
  3491. }else{
  3492. raw_printf(stderr, "Usage: .scanstats on|off\n");
  3493. rc = 1;
  3494. }
  3495. }else
  3496. if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
  3497. ShellState data;
  3498. char *zErrMsg = 0;
  3499. open_db(p, 0);
  3500. memcpy(&data, p, sizeof(data));
  3501. data.showHeader = 0;
  3502. data.cMode = data.mode = MODE_Semi;
  3503. if( nArg==2 ){
  3504. int i;
  3505. for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
  3506. if( strcmp(azArg[1],"sqlite_master")==0 ){
  3507. char *new_argv[2], *new_colv[2];
  3508. new_argv[0] = "CREATE TABLE sqlite_master (\n"
  3509. " type text,\n"
  3510. " name text,\n"
  3511. " tbl_name text,\n"
  3512. " rootpage integer,\n"
  3513. " sql text\n"
  3514. ")";
  3515. new_argv[1] = 0;
  3516. new_colv[0] = "sql";
  3517. new_colv[1] = 0;
  3518. callback(&data, 1, new_argv, new_colv);
  3519. rc = SQLITE_OK;
  3520. }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
  3521. char *new_argv[2], *new_colv[2];
  3522. new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
  3523. " type text,\n"
  3524. " name text,\n"
  3525. " tbl_name text,\n"
  3526. " rootpage integer,\n"
  3527. " sql text\n"
  3528. ")";
  3529. new_argv[1] = 0;
  3530. new_colv[0] = "sql";
  3531. new_colv[1] = 0;
  3532. callback(&data, 1, new_argv, new_colv);
  3533. rc = SQLITE_OK;
  3534. }else{
  3535. zShellStatic = azArg[1];
  3536. rc = sqlite3_exec(p->db,
  3537. "SELECT sql FROM "
  3538. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  3539. " FROM sqlite_master UNION ALL"
  3540. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  3541. "WHERE lower(tbl_name) LIKE shellstatic()"
  3542. " AND type!='meta' AND sql NOTNULL "
  3543. "ORDER BY rowid",
  3544. callback, &data, &zErrMsg);
  3545. zShellStatic = 0;
  3546. }
  3547. }else if( nArg==1 ){
  3548. rc = sqlite3_exec(p->db,
  3549. "SELECT sql FROM "
  3550. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  3551. " FROM sqlite_master UNION ALL"
  3552. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  3553. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  3554. "ORDER BY rowid",
  3555. callback, &data, &zErrMsg
  3556. );
  3557. }else{
  3558. raw_printf(stderr, "Usage: .schema ?LIKE-PATTERN?\n");
  3559. rc = 1;
  3560. goto meta_command_exit;
  3561. }
  3562. if( zErrMsg ){
  3563. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  3564. sqlite3_free(zErrMsg);
  3565. rc = 1;
  3566. }else if( rc != SQLITE_OK ){
  3567. raw_printf(stderr,"Error: querying schema information\n");
  3568. rc = 1;
  3569. }else{
  3570. rc = 0;
  3571. }
  3572. }else
  3573. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  3574. if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
  3575. extern int sqlite3SelectTrace;
  3576. sqlite3SelectTrace = integerValue(azArg[1]);
  3577. }else
  3578. #endif
  3579. #ifdef SQLITE_DEBUG
  3580. /* Undocumented commands for internal testing. Subject to change
  3581. ** without notice. */
  3582. if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
  3583. if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
  3584. int i, v;
  3585. for(i=1; i<nArg; i++){
  3586. v = booleanValue(azArg[i]);
  3587. utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
  3588. }
  3589. }
  3590. if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
  3591. int i; sqlite3_int64 v;
  3592. for(i=1; i<nArg; i++){
  3593. char zBuf[200];
  3594. v = integerValue(azArg[i]);
  3595. sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
  3596. utf8_printf(p->out, "%s", zBuf);
  3597. }
  3598. }
  3599. }else
  3600. #endif
  3601. if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
  3602. if( nArg<2 || nArg>3 ){
  3603. raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
  3604. rc = 1;
  3605. }
  3606. if( nArg>=2 ){
  3607. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
  3608. "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
  3609. }
  3610. if( nArg>=3 ){
  3611. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
  3612. "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
  3613. }
  3614. }else
  3615. if( c=='s'
  3616. && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
  3617. ){
  3618. char *zCmd;
  3619. int i, x;
  3620. if( nArg<2 ){
  3621. raw_printf(stderr, "Usage: .system COMMAND\n");
  3622. rc = 1;
  3623. goto meta_command_exit;
  3624. }
  3625. zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
  3626. for(i=2; i<nArg; i++){
  3627. zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
  3628. zCmd, azArg[i]);
  3629. }
  3630. x = system(zCmd);
  3631. sqlite3_free(zCmd);
  3632. if( x ) raw_printf(stderr, "System command returns %d\n", x);
  3633. }else
  3634. if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
  3635. int i;
  3636. if( nArg!=1 ){
  3637. raw_printf(stderr, "Usage: .show\n");
  3638. rc = 1;
  3639. goto meta_command_exit;
  3640. }
  3641. utf8_printf(p->out, "%12.12s: %s\n","echo", p->echoOn ? "on" : "off");
  3642. utf8_printf(p->out, "%12.12s: %s\n","eqp", p->autoEQP ? "on" : "off");
  3643. utf8_printf(p->out, "%12.12s: %s\n","explain",
  3644. p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
  3645. utf8_printf(p->out,"%12.12s: %s\n","headers", p->showHeader ? "on" : "off");
  3646. utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
  3647. utf8_printf(p->out, "%12.12s: ", "nullvalue");
  3648. output_c_string(p->out, p->nullValue);
  3649. raw_printf(p->out, "\n");
  3650. utf8_printf(p->out,"%12.12s: %s\n","output",
  3651. strlen30(p->outfile) ? p->outfile : "stdout");
  3652. utf8_printf(p->out,"%12.12s: ", "colseparator");
  3653. output_c_string(p->out, p->colSeparator);
  3654. raw_printf(p->out, "\n");
  3655. utf8_printf(p->out,"%12.12s: ", "rowseparator");
  3656. output_c_string(p->out, p->rowSeparator);
  3657. raw_printf(p->out, "\n");
  3658. utf8_printf(p->out, "%12.12s: %s\n","stats", p->statsOn ? "on" : "off");
  3659. utf8_printf(p->out, "%12.12s: ", "width");
  3660. for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
  3661. raw_printf(p->out, "%d ", p->colWidth[i]);
  3662. }
  3663. raw_printf(p->out, "\n");
  3664. }else
  3665. if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
  3666. if( nArg==2 ){
  3667. p->statsOn = booleanValue(azArg[1]);
  3668. }else if( nArg==1 ){
  3669. display_stats(p->db, p, 0);
  3670. }else{
  3671. raw_printf(stderr, "Usage: .stats ?on|off?\n");
  3672. rc = 1;
  3673. }
  3674. }else
  3675. if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){
  3676. sqlite3_stmt *pStmt;
  3677. char **azResult;
  3678. int nRow, nAlloc;
  3679. char *zSql = 0;
  3680. int ii;
  3681. open_db(p, 0);
  3682. rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
  3683. if( rc ) return shellDatabaseError(p->db);
  3684. /* Create an SQL statement to query for the list of tables in the
  3685. ** main and all attached databases where the table name matches the
  3686. ** LIKE pattern bound to variable "?1". */
  3687. zSql = sqlite3_mprintf(
  3688. "SELECT name FROM sqlite_master"
  3689. " WHERE type IN ('table','view')"
  3690. " AND name NOT LIKE 'sqlite_%%'"
  3691. " AND name LIKE ?1");
  3692. while( zSql && sqlite3_step(pStmt)==SQLITE_ROW ){
  3693. const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
  3694. if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue;
  3695. if( strcmp(zDbName,"temp")==0 ){
  3696. zSql = sqlite3_mprintf(
  3697. "%z UNION ALL "
  3698. "SELECT 'temp.' || name FROM sqlite_temp_master"
  3699. " WHERE type IN ('table','view')"
  3700. " AND name NOT LIKE 'sqlite_%%'"
  3701. " AND name LIKE ?1", zSql);
  3702. }else{
  3703. zSql = sqlite3_mprintf(
  3704. "%z UNION ALL "
  3705. "SELECT '%q.' || name FROM \"%w\".sqlite_master"
  3706. " WHERE type IN ('table','view')"
  3707. " AND name NOT LIKE 'sqlite_%%'"
  3708. " AND name LIKE ?1", zSql, zDbName, zDbName);
  3709. }
  3710. }
  3711. rc = sqlite3_finalize(pStmt);
  3712. if( zSql && rc==SQLITE_OK ){
  3713. zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
  3714. if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3715. }
  3716. sqlite3_free(zSql);
  3717. if( !zSql ) return shellNomemError();
  3718. if( rc ) return shellDatabaseError(p->db);
  3719. /* Run the SQL statement prepared by the above block. Store the results
  3720. ** as an array of nul-terminated strings in azResult[]. */
  3721. nRow = nAlloc = 0;
  3722. azResult = 0;
  3723. if( nArg>1 ){
  3724. sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
  3725. }else{
  3726. sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
  3727. }
  3728. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  3729. if( nRow>=nAlloc ){
  3730. char **azNew;
  3731. int n2 = nAlloc*2 + 10;
  3732. azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
  3733. if( azNew==0 ){
  3734. rc = shellNomemError();
  3735. break;
  3736. }
  3737. nAlloc = n2;
  3738. azResult = azNew;
  3739. }
  3740. azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  3741. if( 0==azResult[nRow] ){
  3742. rc = shellNomemError();
  3743. break;
  3744. }
  3745. nRow++;
  3746. }
  3747. if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
  3748. rc = shellDatabaseError(p->db);
  3749. }
  3750. /* Pretty-print the contents of array azResult[] to the output */
  3751. if( rc==0 && nRow>0 ){
  3752. int len, maxlen = 0;
  3753. int i, j;
  3754. int nPrintCol, nPrintRow;
  3755. for(i=0; i<nRow; i++){
  3756. len = strlen30(azResult[i]);
  3757. if( len>maxlen ) maxlen = len;
  3758. }
  3759. nPrintCol = 80/(maxlen+2);
  3760. if( nPrintCol<1 ) nPrintCol = 1;
  3761. nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  3762. for(i=0; i<nPrintRow; i++){
  3763. for(j=i; j<nRow; j+=nPrintRow){
  3764. char *zSp = j<nPrintRow ? "" : " ";
  3765. utf8_printf(p->out, "%s%-*s", zSp, maxlen,
  3766. azResult[j] ? azResult[j]:"");
  3767. }
  3768. raw_printf(p->out, "\n");
  3769. }
  3770. }
  3771. for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
  3772. sqlite3_free(azResult);
  3773. }else
  3774. if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
  3775. static const struct {
  3776. const char *zCtrlName; /* Name of a test-control option */
  3777. int ctrlCode; /* Integer code for that option */
  3778. } aCtrl[] = {
  3779. { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
  3780. { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
  3781. { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
  3782. { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
  3783. { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
  3784. { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
  3785. { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
  3786. { "assert", SQLITE_TESTCTRL_ASSERT },
  3787. { "always", SQLITE_TESTCTRL_ALWAYS },
  3788. { "reserve", SQLITE_TESTCTRL_RESERVE },
  3789. { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
  3790. { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
  3791. { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
  3792. { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
  3793. { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
  3794. { "imposter", SQLITE_TESTCTRL_IMPOSTER },
  3795. };
  3796. int testctrl = -1;
  3797. int rc2 = 0;
  3798. int i, n2;
  3799. open_db(p, 0);
  3800. /* convert testctrl text option to value. allow any unique prefix
  3801. ** of the option name, or a numerical value. */
  3802. n2 = strlen30(azArg[1]);
  3803. for(i=0; i<ArraySize(aCtrl); i++){
  3804. if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
  3805. if( testctrl<0 ){
  3806. testctrl = aCtrl[i].ctrlCode;
  3807. }else{
  3808. utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
  3809. testctrl = -1;
  3810. break;
  3811. }
  3812. }
  3813. }
  3814. if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
  3815. if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
  3816. utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
  3817. }else{
  3818. switch(testctrl){
  3819. /* sqlite3_test_control(int, db, int) */
  3820. case SQLITE_TESTCTRL_OPTIMIZATIONS:
  3821. case SQLITE_TESTCTRL_RESERVE:
  3822. if( nArg==3 ){
  3823. int opt = (int)strtol(azArg[2], 0, 0);
  3824. rc2 = sqlite3_test_control(testctrl, p->db, opt);
  3825. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  3826. } else {
  3827. utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
  3828. azArg[1]);
  3829. }
  3830. break;
  3831. /* sqlite3_test_control(int) */
  3832. case SQLITE_TESTCTRL_PRNG_SAVE:
  3833. case SQLITE_TESTCTRL_PRNG_RESTORE:
  3834. case SQLITE_TESTCTRL_PRNG_RESET:
  3835. case SQLITE_TESTCTRL_BYTEORDER:
  3836. if( nArg==2 ){
  3837. rc2 = sqlite3_test_control(testctrl);
  3838. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  3839. } else {
  3840. utf8_printf(stderr,"Error: testctrl %s takes no options\n",
  3841. azArg[1]);
  3842. }
  3843. break;
  3844. /* sqlite3_test_control(int, uint) */
  3845. case SQLITE_TESTCTRL_PENDING_BYTE:
  3846. if( nArg==3 ){
  3847. unsigned int opt = (unsigned int)integerValue(azArg[2]);
  3848. rc2 = sqlite3_test_control(testctrl, opt);
  3849. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  3850. } else {
  3851. utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
  3852. " int option\n", azArg[1]);
  3853. }
  3854. break;
  3855. /* sqlite3_test_control(int, int) */
  3856. case SQLITE_TESTCTRL_ASSERT:
  3857. case SQLITE_TESTCTRL_ALWAYS:
  3858. case SQLITE_TESTCTRL_NEVER_CORRUPT:
  3859. if( nArg==3 ){
  3860. int opt = booleanValue(azArg[2]);
  3861. rc2 = sqlite3_test_control(testctrl, opt);
  3862. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  3863. } else {
  3864. utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
  3865. azArg[1]);
  3866. }
  3867. break;
  3868. /* sqlite3_test_control(int, char *) */
  3869. #ifdef SQLITE_N_KEYWORD
  3870. case SQLITE_TESTCTRL_ISKEYWORD:
  3871. if( nArg==3 ){
  3872. const char *opt = azArg[2];
  3873. rc2 = sqlite3_test_control(testctrl, opt);
  3874. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  3875. } else {
  3876. utf8_printf(stderr,
  3877. "Error: testctrl %s takes a single char * option\n",
  3878. azArg[1]);
  3879. }
  3880. break;
  3881. #endif
  3882. case SQLITE_TESTCTRL_IMPOSTER:
  3883. if( nArg==5 ){
  3884. rc2 = sqlite3_test_control(testctrl, p->db,
  3885. azArg[2],
  3886. integerValue(azArg[3]),
  3887. integerValue(azArg[4]));
  3888. raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  3889. }else{
  3890. raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
  3891. }
  3892. break;
  3893. case SQLITE_TESTCTRL_BITVEC_TEST:
  3894. case SQLITE_TESTCTRL_FAULT_INSTALL:
  3895. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
  3896. case SQLITE_TESTCTRL_SCRATCHMALLOC:
  3897. default:
  3898. utf8_printf(stderr,
  3899. "Error: CLI support for testctrl %s not implemented\n",
  3900. azArg[1]);
  3901. break;
  3902. }
  3903. }
  3904. }else
  3905. if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
  3906. open_db(p, 0);
  3907. sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
  3908. }else
  3909. if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
  3910. if( nArg==2 ){
  3911. enableTimer = booleanValue(azArg[1]);
  3912. if( enableTimer && !HAS_TIMER ){
  3913. raw_printf(stderr, "Error: timer not available on this system.\n");
  3914. enableTimer = 0;
  3915. }
  3916. }else{
  3917. raw_printf(stderr, "Usage: .timer on|off\n");
  3918. rc = 1;
  3919. }
  3920. }else
  3921. if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
  3922. open_db(p, 0);
  3923. if( nArg!=2 ){
  3924. raw_printf(stderr, "Usage: .trace FILE|off\n");
  3925. rc = 1;
  3926. goto meta_command_exit;
  3927. }
  3928. output_file_close(p->traceOut);
  3929. p->traceOut = output_file_open(azArg[1]);
  3930. #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
  3931. if( p->traceOut==0 ){
  3932. sqlite3_trace(p->db, 0, 0);
  3933. }else{
  3934. sqlite3_trace(p->db, sql_trace_callback, p->traceOut);
  3935. }
  3936. #endif
  3937. }else
  3938. #if SQLITE_USER_AUTHENTICATION
  3939. if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
  3940. if( nArg<2 ){
  3941. raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
  3942. rc = 1;
  3943. goto meta_command_exit;
  3944. }
  3945. open_db(p, 0);
  3946. if( strcmp(azArg[1],"login")==0 ){
  3947. if( nArg!=4 ){
  3948. raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
  3949. rc = 1;
  3950. goto meta_command_exit;
  3951. }
  3952. rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
  3953. (int)strlen(azArg[3]));
  3954. if( rc ){
  3955. utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
  3956. rc = 1;
  3957. }
  3958. }else if( strcmp(azArg[1],"add")==0 ){
  3959. if( nArg!=5 ){
  3960. raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
  3961. rc = 1;
  3962. goto meta_command_exit;
  3963. }
  3964. rc = sqlite3_user_add(p->db, azArg[2],
  3965. azArg[3], (int)strlen(azArg[3]),
  3966. booleanValue(azArg[4]));
  3967. if( rc ){
  3968. raw_printf(stderr, "User-Add failed: %d\n", rc);
  3969. rc = 1;
  3970. }
  3971. }else if( strcmp(azArg[1],"edit")==0 ){
  3972. if( nArg!=5 ){
  3973. raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
  3974. rc = 1;
  3975. goto meta_command_exit;
  3976. }
  3977. rc = sqlite3_user_change(p->db, azArg[2],
  3978. azArg[3], (int)strlen(azArg[3]),
  3979. booleanValue(azArg[4]));
  3980. if( rc ){
  3981. raw_printf(stderr, "User-Edit failed: %d\n", rc);
  3982. rc = 1;
  3983. }
  3984. }else if( strcmp(azArg[1],"delete")==0 ){
  3985. if( nArg!=3 ){
  3986. raw_printf(stderr, "Usage: .user delete USER\n");
  3987. rc = 1;
  3988. goto meta_command_exit;
  3989. }
  3990. rc = sqlite3_user_delete(p->db, azArg[2]);
  3991. if( rc ){
  3992. raw_printf(stderr, "User-Delete failed: %d\n", rc);
  3993. rc = 1;
  3994. }
  3995. }else{
  3996. raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
  3997. rc = 1;
  3998. goto meta_command_exit;
  3999. }
  4000. }else
  4001. #endif /* SQLITE_USER_AUTHENTICATION */
  4002. if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
  4003. utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
  4004. sqlite3_libversion(), sqlite3_sourceid());
  4005. }else
  4006. if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
  4007. const char *zDbName = nArg==2 ? azArg[1] : "main";
  4008. sqlite3_vfs *pVfs;
  4009. if( p->db ){
  4010. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
  4011. if( pVfs ){
  4012. utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
  4013. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  4014. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  4015. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  4016. }
  4017. }
  4018. }else
  4019. if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
  4020. sqlite3_vfs *pVfs;
  4021. sqlite3_vfs *pCurrent = 0;
  4022. if( p->db ){
  4023. sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
  4024. }
  4025. for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
  4026. utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
  4027. pVfs==pCurrent ? " <--- CURRENT" : "");
  4028. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  4029. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  4030. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  4031. if( pVfs->pNext ){
  4032. raw_printf(p->out, "-----------------------------------\n");
  4033. }
  4034. }
  4035. }else
  4036. if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
  4037. const char *zDbName = nArg==2 ? azArg[1] : "main";
  4038. char *zVfsName = 0;
  4039. if( p->db ){
  4040. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
  4041. if( zVfsName ){
  4042. utf8_printf(p->out, "%s\n", zVfsName);
  4043. sqlite3_free(zVfsName);
  4044. }
  4045. }
  4046. }else
  4047. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  4048. if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
  4049. extern int sqlite3WhereTrace;
  4050. sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
  4051. }else
  4052. #endif
  4053. if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
  4054. int j;
  4055. assert( nArg<=ArraySize(azArg) );
  4056. for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
  4057. p->colWidth[j-1] = (int)integerValue(azArg[j]);
  4058. }
  4059. }else
  4060. {
  4061. utf8_printf(stderr, "Error: unknown command or invalid arguments: "
  4062. " \"%s\". Enter \".help\" for help\n", azArg[0]);
  4063. rc = 1;
  4064. }
  4065. meta_command_exit:
  4066. if( p->outCount ){
  4067. p->outCount--;
  4068. if( p->outCount==0 ) output_reset(p);
  4069. }
  4070. return rc;
  4071. }
  4072. /*
  4073. ** Return TRUE if a semicolon occurs anywhere in the first N characters
  4074. ** of string z[].
  4075. */
  4076. static int line_contains_semicolon(const char *z, int N){
  4077. int i;
  4078. for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
  4079. return 0;
  4080. }
  4081. /*
  4082. ** Test to see if a line consists entirely of whitespace.
  4083. */
  4084. static int _all_whitespace(const char *z){
  4085. for(; *z; z++){
  4086. if( IsSpace(z[0]) ) continue;
  4087. if( *z=='/' && z[1]=='*' ){
  4088. z += 2;
  4089. while( *z && (*z!='*' || z[1]!='/') ){ z++; }
  4090. if( *z==0 ) return 0;
  4091. z++;
  4092. continue;
  4093. }
  4094. if( *z=='-' && z[1]=='-' ){
  4095. z += 2;
  4096. while( *z && *z!='\n' ){ z++; }
  4097. if( *z==0 ) return 1;
  4098. continue;
  4099. }
  4100. return 0;
  4101. }
  4102. return 1;
  4103. }
  4104. /*
  4105. ** Return TRUE if the line typed in is an SQL command terminator other
  4106. ** than a semi-colon. The SQL Server style "go" command is understood
  4107. ** as is the Oracle "/".
  4108. */
  4109. static int line_is_command_terminator(const char *zLine){
  4110. while( IsSpace(zLine[0]) ){ zLine++; };
  4111. if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
  4112. return 1; /* Oracle */
  4113. }
  4114. if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
  4115. && _all_whitespace(&zLine[2]) ){
  4116. return 1; /* SQL Server */
  4117. }
  4118. return 0;
  4119. }
  4120. /*
  4121. ** Return true if zSql is a complete SQL statement. Return false if it
  4122. ** ends in the middle of a string literal or C-style comment.
  4123. */
  4124. static int line_is_complete(char *zSql, int nSql){
  4125. int rc;
  4126. if( zSql==0 ) return 1;
  4127. zSql[nSql] = ';';
  4128. zSql[nSql+1] = 0;
  4129. rc = sqlite3_complete(zSql);
  4130. zSql[nSql] = 0;
  4131. return rc;
  4132. }
  4133. /*
  4134. ** Read input from *in and process it. If *in==0 then input
  4135. ** is interactive - the user is typing it it. Otherwise, input
  4136. ** is coming from a file or device. A prompt is issued and history
  4137. ** is saved only if input is interactive. An interrupt signal will
  4138. ** cause this routine to exit immediately, unless input is interactive.
  4139. **
  4140. ** Return the number of errors.
  4141. */
  4142. static int process_input(ShellState *p, FILE *in){
  4143. char *zLine = 0; /* A single input line */
  4144. char *zSql = 0; /* Accumulated SQL text */
  4145. int nLine; /* Length of current line */
  4146. int nSql = 0; /* Bytes of zSql[] used */
  4147. int nAlloc = 0; /* Allocated zSql[] space */
  4148. int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
  4149. char *zErrMsg; /* Error message returned */
  4150. int rc; /* Error code */
  4151. int errCnt = 0; /* Number of errors seen */
  4152. int lineno = 0; /* Current line number */
  4153. int startline = 0; /* Line number for start of current input */
  4154. while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
  4155. fflush(p->out);
  4156. zLine = one_input_line(in, zLine, nSql>0);
  4157. if( zLine==0 ){
  4158. /* End of input */
  4159. if( stdin_is_interactive ) printf("\n");
  4160. break;
  4161. }
  4162. if( seenInterrupt ){
  4163. if( in!=0 ) break;
  4164. seenInterrupt = 0;
  4165. }
  4166. lineno++;
  4167. if( nSql==0 && _all_whitespace(zLine) ){
  4168. if( p->echoOn ) printf("%s\n", zLine);
  4169. continue;
  4170. }
  4171. if( zLine && zLine[0]=='.' && nSql==0 ){
  4172. if( p->echoOn ) printf("%s\n", zLine);
  4173. rc = do_meta_command(zLine, p);
  4174. if( rc==2 ){ /* exit requested */
  4175. break;
  4176. }else if( rc ){
  4177. errCnt++;
  4178. }
  4179. continue;
  4180. }
  4181. if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
  4182. memcpy(zLine,";",2);
  4183. }
  4184. nLine = strlen30(zLine);
  4185. if( nSql+nLine+2>=nAlloc ){
  4186. nAlloc = nSql+nLine+100;
  4187. zSql = realloc(zSql, nAlloc);
  4188. if( zSql==0 ){
  4189. raw_printf(stderr, "Error: out of memory\n");
  4190. exit(1);
  4191. }
  4192. }
  4193. nSqlPrior = nSql;
  4194. if( nSql==0 ){
  4195. int i;
  4196. for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
  4197. assert( nAlloc>0 && zSql!=0 );
  4198. memcpy(zSql, zLine+i, nLine+1-i);
  4199. startline = lineno;
  4200. nSql = nLine-i;
  4201. }else{
  4202. zSql[nSql++] = '\n';
  4203. memcpy(zSql+nSql, zLine, nLine+1);
  4204. nSql += nLine;
  4205. }
  4206. if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  4207. && sqlite3_complete(zSql) ){
  4208. p->cnt = 0;
  4209. open_db(p, 0);
  4210. if( p->backslashOn ) resolve_backslashes(zSql);
  4211. BEGIN_TIMER;
  4212. rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
  4213. END_TIMER;
  4214. if( rc || zErrMsg ){
  4215. char zPrefix[100];
  4216. if( in!=0 || !stdin_is_interactive ){
  4217. sqlite3_snprintf(sizeof(zPrefix), zPrefix,
  4218. "Error: near line %d:", startline);
  4219. }else{
  4220. sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
  4221. }
  4222. if( zErrMsg!=0 ){
  4223. utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
  4224. sqlite3_free(zErrMsg);
  4225. zErrMsg = 0;
  4226. }else{
  4227. utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
  4228. }
  4229. errCnt++;
  4230. }else if( p->countChanges ){
  4231. raw_printf(p->out, "changes: %3d total_changes: %d\n",
  4232. sqlite3_changes(p->db), sqlite3_total_changes(p->db));
  4233. }
  4234. nSql = 0;
  4235. if( p->outCount ){
  4236. output_reset(p);
  4237. p->outCount = 0;
  4238. }
  4239. }else if( nSql && _all_whitespace(zSql) ){
  4240. if( p->echoOn ) printf("%s\n", zSql);
  4241. nSql = 0;
  4242. }
  4243. }
  4244. if( nSql ){
  4245. if( !_all_whitespace(zSql) ){
  4246. utf8_printf(stderr, "Error: incomplete SQL: %s\n", zSql);
  4247. errCnt++;
  4248. }
  4249. }
  4250. free(zSql);
  4251. free(zLine);
  4252. return errCnt>0;
  4253. }
  4254. /*
  4255. ** Return a pathname which is the user's home directory. A
  4256. ** 0 return indicates an error of some kind.
  4257. */
  4258. static char *find_home_dir(void){
  4259. static char *home_dir = NULL;
  4260. if( home_dir ) return home_dir;
  4261. #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
  4262. && !defined(__RTP__) && !defined(_WRS_KERNEL)
  4263. {
  4264. struct passwd *pwent;
  4265. uid_t uid = getuid();
  4266. if( (pwent=getpwuid(uid)) != NULL) {
  4267. home_dir = pwent->pw_dir;
  4268. }
  4269. }
  4270. #endif
  4271. #if defined(_WIN32_WCE)
  4272. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  4273. */
  4274. home_dir = "/";
  4275. #else
  4276. #if defined(_WIN32) || defined(WIN32)
  4277. if (!home_dir) {
  4278. home_dir = getenv("USERPROFILE");
  4279. }
  4280. #endif
  4281. if (!home_dir) {
  4282. home_dir = getenv("HOME");
  4283. }
  4284. #if defined(_WIN32) || defined(WIN32)
  4285. if (!home_dir) {
  4286. char *zDrive, *zPath;
  4287. int n;
  4288. zDrive = getenv("HOMEDRIVE");
  4289. zPath = getenv("HOMEPATH");
  4290. if( zDrive && zPath ){
  4291. n = strlen30(zDrive) + strlen30(zPath) + 1;
  4292. home_dir = malloc( n );
  4293. if( home_dir==0 ) return 0;
  4294. sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  4295. return home_dir;
  4296. }
  4297. home_dir = "c:\\";
  4298. }
  4299. #endif
  4300. #endif /* !_WIN32_WCE */
  4301. if( home_dir ){
  4302. int n = strlen30(home_dir) + 1;
  4303. char *z = malloc( n );
  4304. if( z ) memcpy(z, home_dir, n);
  4305. home_dir = z;
  4306. }
  4307. return home_dir;
  4308. }
  4309. /*
  4310. ** Read input from the file given by sqliterc_override. Or if that
  4311. ** parameter is NULL, take input from ~/.sqliterc
  4312. **
  4313. ** Returns the number of errors.
  4314. */
  4315. static void process_sqliterc(
  4316. ShellState *p, /* Configuration data */
  4317. const char *sqliterc_override /* Name of config file. NULL to use default */
  4318. ){
  4319. char *home_dir = NULL;
  4320. const char *sqliterc = sqliterc_override;
  4321. char *zBuf = 0;
  4322. FILE *in = NULL;
  4323. if (sqliterc == NULL) {
  4324. home_dir = find_home_dir();
  4325. if( home_dir==0 ){
  4326. raw_printf(stderr, "-- warning: cannot find home directory;"
  4327. " cannot read ~/.sqliterc\n");
  4328. return;
  4329. }
  4330. sqlite3_initialize();
  4331. zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
  4332. sqliterc = zBuf;
  4333. }
  4334. in = fopen(sqliterc,"rb");
  4335. if( in ){
  4336. if( stdin_is_interactive ){
  4337. utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
  4338. }
  4339. process_input(p,in);
  4340. fclose(in);
  4341. }
  4342. sqlite3_free(zBuf);
  4343. }
  4344. /*
  4345. ** Show available command line options
  4346. */
  4347. static const char zOptions[] =
  4348. " -ascii set output mode to 'ascii'\n"
  4349. " -bail stop after hitting an error\n"
  4350. " -batch force batch I/O\n"
  4351. " -column set output mode to 'column'\n"
  4352. " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
  4353. " -csv set output mode to 'csv'\n"
  4354. " -echo print commands before execution\n"
  4355. " -init FILENAME read/process named file\n"
  4356. " -[no]header turn headers on or off\n"
  4357. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  4358. " -heap SIZE Size of heap for memsys3 or memsys5\n"
  4359. #endif
  4360. " -help show this message\n"
  4361. " -html set output mode to HTML\n"
  4362. " -interactive force interactive I/O\n"
  4363. " -line set output mode to 'line'\n"
  4364. " -list set output mode to 'list'\n"
  4365. " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
  4366. " -mmap N default mmap size set to N\n"
  4367. #ifdef SQLITE_ENABLE_MULTIPLEX
  4368. " -multiplex enable the multiplexor VFS\n"
  4369. #endif
  4370. " -newline SEP set output row separator. Default: '\\n'\n"
  4371. " -nullvalue TEXT set text string for NULL values. Default ''\n"
  4372. " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
  4373. " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
  4374. " -separator SEP set output column separator. Default: '|'\n"
  4375. " -stats print memory stats before each finalize\n"
  4376. " -version show SQLite version\n"
  4377. " -vfs NAME use NAME as the default VFS\n"
  4378. #ifdef SQLITE_ENABLE_VFSTRACE
  4379. " -vfstrace enable tracing of all VFS calls\n"
  4380. #endif
  4381. ;
  4382. static void usage(int showDetail){
  4383. utf8_printf(stderr,
  4384. "Usage: %s [OPTIONS] FILENAME [SQL]\n"
  4385. "FILENAME is the name of an SQLite database. A new database is created\n"
  4386. "if the file does not previously exist.\n", Argv0);
  4387. if( showDetail ){
  4388. utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
  4389. }else{
  4390. raw_printf(stderr, "Use the -help option for additional information\n");
  4391. }
  4392. exit(1);
  4393. }
  4394. /*
  4395. ** Initialize the state information in data
  4396. */
  4397. static void main_init(ShellState *data) {
  4398. memset(data, 0, sizeof(*data));
  4399. data->normalMode = data->cMode = data->mode = MODE_List;
  4400. data->autoExplain = 1;
  4401. memcpy(data->colSeparator,SEP_Column, 2);
  4402. memcpy(data->rowSeparator,SEP_Row, 2);
  4403. data->showHeader = 0;
  4404. data->shellFlgs = SHFLG_Lookaside;
  4405. sqlite3_config(SQLITE_CONFIG_URI, 1);
  4406. sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
  4407. sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
  4408. sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  4409. sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
  4410. }
  4411. /*
  4412. ** Output text to the console in a font that attracts extra attention.
  4413. */
  4414. #ifdef _WIN32
  4415. static void printBold(const char *zText){
  4416. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  4417. CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
  4418. GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
  4419. SetConsoleTextAttribute(out,
  4420. FOREGROUND_RED|FOREGROUND_INTENSITY
  4421. );
  4422. printf("%s", zText);
  4423. SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
  4424. }
  4425. #else
  4426. static void printBold(const char *zText){
  4427. printf("\033[1m%s\033[0m", zText);
  4428. }
  4429. #endif
  4430. /*
  4431. ** Get the argument to an --option. Throw an error and die if no argument
  4432. ** is available.
  4433. */
  4434. static char *cmdline_option_value(int argc, char **argv, int i){
  4435. if( i==argc ){
  4436. utf8_printf(stderr, "%s: Error: missing argument to %s\n",
  4437. argv[0], argv[argc-1]);
  4438. exit(1);
  4439. }
  4440. return argv[i];
  4441. }
  4442. int SQLITE_CDECL main(int argc, char **argv){
  4443. char *zErrMsg = 0;
  4444. ShellState data;
  4445. const char *zInitFile = 0;
  4446. int i;
  4447. int rc = 0;
  4448. int warnInmemoryDb = 0;
  4449. int readStdin = 1;
  4450. int nCmd = 0;
  4451. char **azCmd = 0;
  4452. #if USE_SYSTEM_SQLITE+0!=1
  4453. if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
  4454. utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
  4455. sqlite3_sourceid(), SQLITE_SOURCE_ID);
  4456. exit(1);
  4457. }
  4458. #endif
  4459. setBinaryMode(stdin);
  4460. setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
  4461. Argv0 = argv[0];
  4462. main_init(&data);
  4463. stdin_is_interactive = isatty(0);
  4464. stdout_is_console = isatty(1);
  4465. /* Make sure we have a valid signal handler early, before anything
  4466. ** else is done.
  4467. */
  4468. #ifdef SIGINT
  4469. signal(SIGINT, interrupt_handler);
  4470. #endif
  4471. #ifdef SQLITE_SHELL_DBNAME_PROC
  4472. {
  4473. /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
  4474. ** of a C-function that will provide the name of the database file. Use
  4475. ** this compile-time option to embed this shell program in larger
  4476. ** applications. */
  4477. extern void SQLITE_SHELL_DBNAME_PROC(const char**);
  4478. SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
  4479. warnInmemoryDb = 0;
  4480. }
  4481. #endif
  4482. /* Do an initial pass through the command-line argument to locate
  4483. ** the name of the database file, the name of the initialization file,
  4484. ** the size of the alternative malloc heap,
  4485. ** and the first command to execute.
  4486. */
  4487. for(i=1; i<argc; i++){
  4488. char *z;
  4489. z = argv[i];
  4490. if( z[0]!='-' ){
  4491. if( data.zDbFilename==0 ){
  4492. data.zDbFilename = z;
  4493. }else{
  4494. /* Excesss arguments are interpreted as SQL (or dot-commands) and
  4495. ** mean that nothing is read from stdin */
  4496. readStdin = 0;
  4497. nCmd++;
  4498. azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
  4499. if( azCmd==0 ){
  4500. raw_printf(stderr, "out of memory\n");
  4501. exit(1);
  4502. }
  4503. azCmd[nCmd-1] = z;
  4504. }
  4505. }
  4506. if( z[1]=='-' ) z++;
  4507. if( strcmp(z,"-separator")==0
  4508. || strcmp(z,"-nullvalue")==0
  4509. || strcmp(z,"-newline")==0
  4510. || strcmp(z,"-cmd")==0
  4511. ){
  4512. (void)cmdline_option_value(argc, argv, ++i);
  4513. }else if( strcmp(z,"-init")==0 ){
  4514. zInitFile = cmdline_option_value(argc, argv, ++i);
  4515. }else if( strcmp(z,"-batch")==0 ){
  4516. /* Need to check for batch mode here to so we can avoid printing
  4517. ** informational messages (like from process_sqliterc) before
  4518. ** we do the actual processing of arguments later in a second pass.
  4519. */
  4520. stdin_is_interactive = 0;
  4521. }else if( strcmp(z,"-heap")==0 ){
  4522. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  4523. const char *zSize;
  4524. sqlite3_int64 szHeap;
  4525. zSize = cmdline_option_value(argc, argv, ++i);
  4526. szHeap = integerValue(zSize);
  4527. if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
  4528. sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
  4529. #endif
  4530. }else if( strcmp(z,"-scratch")==0 ){
  4531. int n, sz;
  4532. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  4533. if( sz>400000 ) sz = 400000;
  4534. if( sz<2500 ) sz = 2500;
  4535. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  4536. if( n>10 ) n = 10;
  4537. if( n<1 ) n = 1;
  4538. sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
  4539. data.shellFlgs |= SHFLG_Scratch;
  4540. }else if( strcmp(z,"-pagecache")==0 ){
  4541. int n, sz;
  4542. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  4543. if( sz>70000 ) sz = 70000;
  4544. if( sz<0 ) sz = 0;
  4545. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  4546. sqlite3_config(SQLITE_CONFIG_PAGECACHE,
  4547. (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
  4548. data.shellFlgs |= SHFLG_Pagecache;
  4549. }else if( strcmp(z,"-lookaside")==0 ){
  4550. int n, sz;
  4551. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  4552. if( sz<0 ) sz = 0;
  4553. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  4554. if( n<0 ) n = 0;
  4555. sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
  4556. if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
  4557. #ifdef SQLITE_ENABLE_VFSTRACE
  4558. }else if( strcmp(z,"-vfstrace")==0 ){
  4559. extern int vfstrace_register(
  4560. const char *zTraceName,
  4561. const char *zOldVfsName,
  4562. int (*xOut)(const char*,void*),
  4563. void *pOutArg,
  4564. int makeDefault
  4565. );
  4566. vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
  4567. #endif
  4568. #ifdef SQLITE_ENABLE_MULTIPLEX
  4569. }else if( strcmp(z,"-multiplex")==0 ){
  4570. extern int sqlite3_multiple_initialize(const char*,int);
  4571. sqlite3_multiplex_initialize(0, 1);
  4572. #endif
  4573. }else if( strcmp(z,"-mmap")==0 ){
  4574. sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  4575. sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
  4576. }else if( strcmp(z,"-vfs")==0 ){
  4577. sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
  4578. if( pVfs ){
  4579. sqlite3_vfs_register(pVfs, 1);
  4580. }else{
  4581. utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
  4582. exit(1);
  4583. }
  4584. }
  4585. }
  4586. if( data.zDbFilename==0 ){
  4587. #ifndef SQLITE_OMIT_MEMORYDB
  4588. data.zDbFilename = ":memory:";
  4589. warnInmemoryDb = argc==1;
  4590. #else
  4591. utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
  4592. return 1;
  4593. #endif
  4594. }
  4595. data.out = stdout;
  4596. /* Go ahead and open the database file if it already exists. If the
  4597. ** file does not exist, delay opening it. This prevents empty database
  4598. ** files from being created if a user mistypes the database name argument
  4599. ** to the sqlite command-line tool.
  4600. */
  4601. if( access(data.zDbFilename, 0)==0 ){
  4602. open_db(&data, 0);
  4603. }
  4604. /* Process the initialization file if there is one. If no -init option
  4605. ** is given on the command line, look for a file named ~/.sqliterc and
  4606. ** try to process it.
  4607. */
  4608. process_sqliterc(&data,zInitFile);
  4609. /* Make a second pass through the command-line argument and set
  4610. ** options. This second pass is delayed until after the initialization
  4611. ** file is processed so that the command-line arguments will override
  4612. ** settings in the initialization file.
  4613. */
  4614. for(i=1; i<argc; i++){
  4615. char *z = argv[i];
  4616. if( z[0]!='-' ) continue;
  4617. if( z[1]=='-' ){ z++; }
  4618. if( strcmp(z,"-init")==0 ){
  4619. i++;
  4620. }else if( strcmp(z,"-html")==0 ){
  4621. data.mode = MODE_Html;
  4622. }else if( strcmp(z,"-list")==0 ){
  4623. data.mode = MODE_List;
  4624. }else if( strcmp(z,"-line")==0 ){
  4625. data.mode = MODE_Line;
  4626. }else if( strcmp(z,"-column")==0 ){
  4627. data.mode = MODE_Column;
  4628. }else if( strcmp(z,"-csv")==0 ){
  4629. data.mode = MODE_Csv;
  4630. memcpy(data.colSeparator,",",2);
  4631. }else if( strcmp(z,"-ascii")==0 ){
  4632. data.mode = MODE_Ascii;
  4633. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  4634. SEP_Unit);
  4635. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  4636. SEP_Record);
  4637. }else if( strcmp(z,"-separator")==0 ){
  4638. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  4639. "%s",cmdline_option_value(argc,argv,++i));
  4640. }else if( strcmp(z,"-newline")==0 ){
  4641. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  4642. "%s",cmdline_option_value(argc,argv,++i));
  4643. }else if( strcmp(z,"-nullvalue")==0 ){
  4644. sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
  4645. "%s",cmdline_option_value(argc,argv,++i));
  4646. }else if( strcmp(z,"-header")==0 ){
  4647. data.showHeader = 1;
  4648. }else if( strcmp(z,"-noheader")==0 ){
  4649. data.showHeader = 0;
  4650. }else if( strcmp(z,"-echo")==0 ){
  4651. data.echoOn = 1;
  4652. }else if( strcmp(z,"-eqp")==0 ){
  4653. data.autoEQP = 1;
  4654. }else if( strcmp(z,"-stats")==0 ){
  4655. data.statsOn = 1;
  4656. }else if( strcmp(z,"-scanstats")==0 ){
  4657. data.scanstatsOn = 1;
  4658. }else if( strcmp(z,"-backslash")==0 ){
  4659. /* Undocumented command-line option: -backslash
  4660. ** Causes C-style backslash escapes to be evaluated in SQL statements
  4661. ** prior to sending the SQL into SQLite. Useful for injecting
  4662. ** crazy bytes in the middle of SQL statements for testing and debugging.
  4663. */
  4664. data.backslashOn = 1;
  4665. }else if( strcmp(z,"-bail")==0 ){
  4666. bail_on_error = 1;
  4667. }else if( strcmp(z,"-version")==0 ){
  4668. printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
  4669. return 0;
  4670. }else if( strcmp(z,"-interactive")==0 ){
  4671. stdin_is_interactive = 1;
  4672. }else if( strcmp(z,"-batch")==0 ){
  4673. stdin_is_interactive = 0;
  4674. }else if( strcmp(z,"-heap")==0 ){
  4675. i++;
  4676. }else if( strcmp(z,"-scratch")==0 ){
  4677. i+=2;
  4678. }else if( strcmp(z,"-pagecache")==0 ){
  4679. i+=2;
  4680. }else if( strcmp(z,"-lookaside")==0 ){
  4681. i+=2;
  4682. }else if( strcmp(z,"-mmap")==0 ){
  4683. i++;
  4684. }else if( strcmp(z,"-vfs")==0 ){
  4685. i++;
  4686. #ifdef SQLITE_ENABLE_VFSTRACE
  4687. }else if( strcmp(z,"-vfstrace")==0 ){
  4688. i++;
  4689. #endif
  4690. #ifdef SQLITE_ENABLE_MULTIPLEX
  4691. }else if( strcmp(z,"-multiplex")==0 ){
  4692. i++;
  4693. #endif
  4694. }else if( strcmp(z,"-help")==0 ){
  4695. usage(1);
  4696. }else if( strcmp(z,"-cmd")==0 ){
  4697. /* Run commands that follow -cmd first and separately from commands
  4698. ** that simply appear on the command-line. This seems goofy. It would
  4699. ** be better if all commands ran in the order that they appear. But
  4700. ** we retain the goofy behavior for historical compatibility. */
  4701. if( i==argc-1 ) break;
  4702. z = cmdline_option_value(argc,argv,++i);
  4703. if( z[0]=='.' ){
  4704. rc = do_meta_command(z, &data);
  4705. if( rc && bail_on_error ) return rc==2 ? 0 : rc;
  4706. }else{
  4707. open_db(&data, 0);
  4708. rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
  4709. if( zErrMsg!=0 ){
  4710. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  4711. if( bail_on_error ) return rc!=0 ? rc : 1;
  4712. }else if( rc!=0 ){
  4713. utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
  4714. if( bail_on_error ) return rc;
  4715. }
  4716. }
  4717. }else{
  4718. utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
  4719. raw_printf(stderr,"Use -help for a list of options.\n");
  4720. return 1;
  4721. }
  4722. data.cMode = data.mode;
  4723. }
  4724. if( !readStdin ){
  4725. /* Run all arguments that do not begin with '-' as if they were separate
  4726. ** command-line inputs, except for the argToSkip argument which contains
  4727. ** the database filename.
  4728. */
  4729. for(i=0; i<nCmd; i++){
  4730. if( azCmd[i][0]=='.' ){
  4731. rc = do_meta_command(azCmd[i], &data);
  4732. if( rc ) return rc==2 ? 0 : rc;
  4733. }else{
  4734. open_db(&data, 0);
  4735. rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
  4736. if( zErrMsg!=0 ){
  4737. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  4738. return rc!=0 ? rc : 1;
  4739. }else if( rc!=0 ){
  4740. utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
  4741. return rc;
  4742. }
  4743. }
  4744. }
  4745. free(azCmd);
  4746. }else{
  4747. /* Run commands received from standard input
  4748. */
  4749. if( stdin_is_interactive ){
  4750. char *zHome;
  4751. char *zHistory = 0;
  4752. int nHistory;
  4753. printf(
  4754. "SQLite version %s %.19s\n" /*extra-version-info*/
  4755. "Enter \".help\" for usage hints.\n",
  4756. sqlite3_libversion(), sqlite3_sourceid()
  4757. );
  4758. if( warnInmemoryDb ){
  4759. printf("Connected to a ");
  4760. printBold("transient in-memory database");
  4761. printf(".\nUse \".open FILENAME\" to reopen on a "
  4762. "persistent database.\n");
  4763. }
  4764. zHome = find_home_dir();
  4765. if( zHome ){
  4766. nHistory = strlen30(zHome) + 20;
  4767. if( (zHistory = malloc(nHistory))!=0 ){
  4768. sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  4769. }
  4770. }
  4771. if( zHistory ){ shell_read_history(zHistory); }
  4772. rc = process_input(&data, 0);
  4773. if( zHistory ){
  4774. shell_stifle_history(100);
  4775. shell_write_history(zHistory);
  4776. free(zHistory);
  4777. }
  4778. }else{
  4779. rc = process_input(&data, stdin);
  4780. }
  4781. }
  4782. set_table_name(&data, 0);
  4783. if( data.db ){
  4784. sqlite3_close(data.db);
  4785. }
  4786. sqlite3_free(data.zFreeOnClose);
  4787. return rc;
  4788. }