tclsqlite.c 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806
  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. ** A TCL Interface to SQLite. Append this file to sqlite3.c and
  13. ** compile the whole thing to build a TCL-enabled version of SQLite.
  14. **
  15. ** Compile-time options:
  16. **
  17. ** -DTCLSH=1 Add a "main()" routine that works as a tclsh.
  18. **
  19. ** -DSQLITE_TCLMD5 When used in conjuction with -DTCLSH=1, add
  20. ** four new commands to the TCL interpreter for
  21. ** generating MD5 checksums: md5, md5file,
  22. ** md5-10x8, and md5file-10x8.
  23. **
  24. ** -DSQLITE_TEST When used in conjuction with -DTCLSH=1, add
  25. ** hundreds of new commands used for testing
  26. ** SQLite. This option implies -DSQLITE_TCLMD5.
  27. */
  28. #include "tcl.h"
  29. #include <errno.h>
  30. /*
  31. ** Some additional include files are needed if this file is not
  32. ** appended to the amalgamation.
  33. */
  34. #ifndef SQLITE_AMALGAMATION
  35. # include "sqlite3.h"
  36. # include <stdlib.h>
  37. # include <string.h>
  38. # include <assert.h>
  39. typedef unsigned char u8;
  40. #endif
  41. #include <ctype.h>
  42. /* Used to get the current process ID */
  43. #if !defined(_WIN32)
  44. # include <unistd.h>
  45. # define GETPID getpid
  46. #elif !defined(_WIN32_WCE)
  47. # ifndef SQLITE_AMALGAMATION
  48. # define WIN32_LEAN_AND_MEAN
  49. # include <windows.h>
  50. # endif
  51. # define GETPID (int)GetCurrentProcessId
  52. #endif
  53. /*
  54. * Windows needs to know which symbols to export. Unix does not.
  55. * BUILD_sqlite should be undefined for Unix.
  56. */
  57. #ifdef BUILD_sqlite
  58. #undef TCL_STORAGE_CLASS
  59. #define TCL_STORAGE_CLASS DLLEXPORT
  60. #endif /* BUILD_sqlite */
  61. #define NUM_PREPARED_STMTS 10
  62. #define MAX_PREPARED_STMTS 100
  63. /* Forward declaration */
  64. typedef struct SqliteDb SqliteDb;
  65. /*
  66. ** New SQL functions can be created as TCL scripts. Each such function
  67. ** is described by an instance of the following structure.
  68. */
  69. typedef struct SqlFunc SqlFunc;
  70. struct SqlFunc {
  71. Tcl_Interp *interp; /* The TCL interpret to execute the function */
  72. Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
  73. SqliteDb *pDb; /* Database connection that owns this function */
  74. int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
  75. char *zName; /* Name of this function */
  76. SqlFunc *pNext; /* Next function on the list of them all */
  77. };
  78. /*
  79. ** New collation sequences function can be created as TCL scripts. Each such
  80. ** function is described by an instance of the following structure.
  81. */
  82. typedef struct SqlCollate SqlCollate;
  83. struct SqlCollate {
  84. Tcl_Interp *interp; /* The TCL interpret to execute the function */
  85. char *zScript; /* The script to be run */
  86. SqlCollate *pNext; /* Next function on the list of them all */
  87. };
  88. /*
  89. ** Prepared statements are cached for faster execution. Each prepared
  90. ** statement is described by an instance of the following structure.
  91. */
  92. typedef struct SqlPreparedStmt SqlPreparedStmt;
  93. struct SqlPreparedStmt {
  94. SqlPreparedStmt *pNext; /* Next in linked list */
  95. SqlPreparedStmt *pPrev; /* Previous on the list */
  96. sqlite3_stmt *pStmt; /* The prepared statement */
  97. int nSql; /* chars in zSql[] */
  98. const char *zSql; /* Text of the SQL statement */
  99. int nParm; /* Size of apParm array */
  100. Tcl_Obj **apParm; /* Array of referenced object pointers */
  101. };
  102. typedef struct IncrblobChannel IncrblobChannel;
  103. /*
  104. ** There is one instance of this structure for each SQLite database
  105. ** that has been opened by the SQLite TCL interface.
  106. **
  107. ** If this module is built with SQLITE_TEST defined (to create the SQLite
  108. ** testfixture executable), then it may be configured to use either
  109. ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
  110. ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
  111. */
  112. struct SqliteDb {
  113. sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
  114. Tcl_Interp *interp; /* The interpreter used for this database */
  115. char *zBusy; /* The busy callback routine */
  116. char *zCommit; /* The commit hook callback routine */
  117. char *zTrace; /* The trace callback routine */
  118. char *zProfile; /* The profile callback routine */
  119. char *zProgress; /* The progress callback routine */
  120. char *zAuth; /* The authorization callback routine */
  121. int disableAuth; /* Disable the authorizer if it exists */
  122. char *zNull; /* Text to substitute for an SQL NULL value */
  123. SqlFunc *pFunc; /* List of SQL functions */
  124. Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
  125. Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
  126. Tcl_Obj *pWalHook; /* WAL hook script (if any) */
  127. Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
  128. SqlCollate *pCollate; /* List of SQL collation functions */
  129. int rc; /* Return code of most recent sqlite3_exec() */
  130. Tcl_Obj *pCollateNeeded; /* Collation needed script */
  131. SqlPreparedStmt *stmtList; /* List of prepared statements*/
  132. SqlPreparedStmt *stmtLast; /* Last statement in the list */
  133. int maxStmt; /* The next maximum number of stmtList */
  134. int nStmt; /* Number of statements in stmtList */
  135. IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
  136. int nStep, nSort, nIndex; /* Statistics for most recent operation */
  137. int nTransaction; /* Number of nested [transaction] methods */
  138. #ifdef SQLITE_TEST
  139. int bLegacyPrepare; /* True to use sqlite3_prepare() */
  140. #endif
  141. };
  142. struct IncrblobChannel {
  143. sqlite3_blob *pBlob; /* sqlite3 blob handle */
  144. SqliteDb *pDb; /* Associated database connection */
  145. int iSeek; /* Current seek offset */
  146. Tcl_Channel channel; /* Channel identifier */
  147. IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
  148. IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
  149. };
  150. /*
  151. ** Compute a string length that is limited to what can be stored in
  152. ** lower 30 bits of a 32-bit signed integer.
  153. */
  154. static int strlen30(const char *z){
  155. const char *z2 = z;
  156. while( *z2 ){ z2++; }
  157. return 0x3fffffff & (int)(z2 - z);
  158. }
  159. #ifndef SQLITE_OMIT_INCRBLOB
  160. /*
  161. ** Close all incrblob channels opened using database connection pDb.
  162. ** This is called when shutting down the database connection.
  163. */
  164. static void closeIncrblobChannels(SqliteDb *pDb){
  165. IncrblobChannel *p;
  166. IncrblobChannel *pNext;
  167. for(p=pDb->pIncrblob; p; p=pNext){
  168. pNext = p->pNext;
  169. /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
  170. ** which deletes the IncrblobChannel structure at *p. So do not
  171. ** call Tcl_Free() here.
  172. */
  173. Tcl_UnregisterChannel(pDb->interp, p->channel);
  174. }
  175. }
  176. /*
  177. ** Close an incremental blob channel.
  178. */
  179. static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
  180. IncrblobChannel *p = (IncrblobChannel *)instanceData;
  181. int rc = sqlite3_blob_close(p->pBlob);
  182. sqlite3 *db = p->pDb->db;
  183. /* Remove the channel from the SqliteDb.pIncrblob list. */
  184. if( p->pNext ){
  185. p->pNext->pPrev = p->pPrev;
  186. }
  187. if( p->pPrev ){
  188. p->pPrev->pNext = p->pNext;
  189. }
  190. if( p->pDb->pIncrblob==p ){
  191. p->pDb->pIncrblob = p->pNext;
  192. }
  193. /* Free the IncrblobChannel structure */
  194. Tcl_Free((char *)p);
  195. if( rc!=SQLITE_OK ){
  196. Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
  197. return TCL_ERROR;
  198. }
  199. return TCL_OK;
  200. }
  201. /*
  202. ** Read data from an incremental blob channel.
  203. */
  204. static int incrblobInput(
  205. ClientData instanceData,
  206. char *buf,
  207. int bufSize,
  208. int *errorCodePtr
  209. ){
  210. IncrblobChannel *p = (IncrblobChannel *)instanceData;
  211. int nRead = bufSize; /* Number of bytes to read */
  212. int nBlob; /* Total size of the blob */
  213. int rc; /* sqlite error code */
  214. nBlob = sqlite3_blob_bytes(p->pBlob);
  215. if( (p->iSeek+nRead)>nBlob ){
  216. nRead = nBlob-p->iSeek;
  217. }
  218. if( nRead<=0 ){
  219. return 0;
  220. }
  221. rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
  222. if( rc!=SQLITE_OK ){
  223. *errorCodePtr = rc;
  224. return -1;
  225. }
  226. p->iSeek += nRead;
  227. return nRead;
  228. }
  229. /*
  230. ** Write data to an incremental blob channel.
  231. */
  232. static int incrblobOutput(
  233. ClientData instanceData,
  234. CONST char *buf,
  235. int toWrite,
  236. int *errorCodePtr
  237. ){
  238. IncrblobChannel *p = (IncrblobChannel *)instanceData;
  239. int nWrite = toWrite; /* Number of bytes to write */
  240. int nBlob; /* Total size of the blob */
  241. int rc; /* sqlite error code */
  242. nBlob = sqlite3_blob_bytes(p->pBlob);
  243. if( (p->iSeek+nWrite)>nBlob ){
  244. *errorCodePtr = EINVAL;
  245. return -1;
  246. }
  247. if( nWrite<=0 ){
  248. return 0;
  249. }
  250. rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
  251. if( rc!=SQLITE_OK ){
  252. *errorCodePtr = EIO;
  253. return -1;
  254. }
  255. p->iSeek += nWrite;
  256. return nWrite;
  257. }
  258. /*
  259. ** Seek an incremental blob channel.
  260. */
  261. static int incrblobSeek(
  262. ClientData instanceData,
  263. long offset,
  264. int seekMode,
  265. int *errorCodePtr
  266. ){
  267. IncrblobChannel *p = (IncrblobChannel *)instanceData;
  268. switch( seekMode ){
  269. case SEEK_SET:
  270. p->iSeek = offset;
  271. break;
  272. case SEEK_CUR:
  273. p->iSeek += offset;
  274. break;
  275. case SEEK_END:
  276. p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
  277. break;
  278. default: assert(!"Bad seekMode");
  279. }
  280. return p->iSeek;
  281. }
  282. static void incrblobWatch(ClientData instanceData, int mode){
  283. /* NO-OP */
  284. }
  285. static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
  286. return TCL_ERROR;
  287. }
  288. static Tcl_ChannelType IncrblobChannelType = {
  289. "incrblob", /* typeName */
  290. TCL_CHANNEL_VERSION_2, /* version */
  291. incrblobClose, /* closeProc */
  292. incrblobInput, /* inputProc */
  293. incrblobOutput, /* outputProc */
  294. incrblobSeek, /* seekProc */
  295. 0, /* setOptionProc */
  296. 0, /* getOptionProc */
  297. incrblobWatch, /* watchProc (this is a no-op) */
  298. incrblobHandle, /* getHandleProc (always returns error) */
  299. 0, /* close2Proc */
  300. 0, /* blockModeProc */
  301. 0, /* flushProc */
  302. 0, /* handlerProc */
  303. 0, /* wideSeekProc */
  304. };
  305. /*
  306. ** Create a new incrblob channel.
  307. */
  308. static int createIncrblobChannel(
  309. Tcl_Interp *interp,
  310. SqliteDb *pDb,
  311. const char *zDb,
  312. const char *zTable,
  313. const char *zColumn,
  314. sqlite_int64 iRow,
  315. int isReadonly
  316. ){
  317. IncrblobChannel *p;
  318. sqlite3 *db = pDb->db;
  319. sqlite3_blob *pBlob;
  320. int rc;
  321. int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
  322. /* This variable is used to name the channels: "incrblob_[incr count]" */
  323. static int count = 0;
  324. char zChannel[64];
  325. rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
  326. if( rc!=SQLITE_OK ){
  327. Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
  328. return TCL_ERROR;
  329. }
  330. p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
  331. p->iSeek = 0;
  332. p->pBlob = pBlob;
  333. sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
  334. p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
  335. Tcl_RegisterChannel(interp, p->channel);
  336. /* Link the new channel into the SqliteDb.pIncrblob list. */
  337. p->pNext = pDb->pIncrblob;
  338. p->pPrev = 0;
  339. if( p->pNext ){
  340. p->pNext->pPrev = p;
  341. }
  342. pDb->pIncrblob = p;
  343. p->pDb = pDb;
  344. Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
  345. return TCL_OK;
  346. }
  347. #else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
  348. #define closeIncrblobChannels(pDb)
  349. #endif
  350. /*
  351. ** Look at the script prefix in pCmd. We will be executing this script
  352. ** after first appending one or more arguments. This routine analyzes
  353. ** the script to see if it is safe to use Tcl_EvalObjv() on the script
  354. ** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
  355. ** faster.
  356. **
  357. ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
  358. ** command name followed by zero or more arguments with no [...] or $
  359. ** or {...} or ; to be seen anywhere. Most callback scripts consist
  360. ** of just a single procedure name and they meet this requirement.
  361. */
  362. static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
  363. /* We could try to do something with Tcl_Parse(). But we will instead
  364. ** just do a search for forbidden characters. If any of the forbidden
  365. ** characters appear in pCmd, we will report the string as unsafe.
  366. */
  367. const char *z;
  368. int n;
  369. z = Tcl_GetStringFromObj(pCmd, &n);
  370. while( n-- > 0 ){
  371. int c = *(z++);
  372. if( c=='$' || c=='[' || c==';' ) return 0;
  373. }
  374. return 1;
  375. }
  376. /*
  377. ** Find an SqlFunc structure with the given name. Or create a new
  378. ** one if an existing one cannot be found. Return a pointer to the
  379. ** structure.
  380. */
  381. static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
  382. SqlFunc *p, *pNew;
  383. int i;
  384. pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 );
  385. pNew->zName = (char*)&pNew[1];
  386. for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
  387. pNew->zName[i] = 0;
  388. for(p=pDb->pFunc; p; p=p->pNext){
  389. if( strcmp(p->zName, pNew->zName)==0 ){
  390. Tcl_Free((char*)pNew);
  391. return p;
  392. }
  393. }
  394. pNew->interp = pDb->interp;
  395. pNew->pDb = pDb;
  396. pNew->pScript = 0;
  397. pNew->pNext = pDb->pFunc;
  398. pDb->pFunc = pNew;
  399. return pNew;
  400. }
  401. /*
  402. ** Free a single SqlPreparedStmt object.
  403. */
  404. static void dbFreeStmt(SqlPreparedStmt *pStmt){
  405. #ifdef SQLITE_TEST
  406. if( sqlite3_sql(pStmt->pStmt)==0 ){
  407. Tcl_Free((char *)pStmt->zSql);
  408. }
  409. #endif
  410. sqlite3_finalize(pStmt->pStmt);
  411. Tcl_Free((char *)pStmt);
  412. }
  413. /*
  414. ** Finalize and free a list of prepared statements
  415. */
  416. static void flushStmtCache(SqliteDb *pDb){
  417. SqlPreparedStmt *pPreStmt;
  418. SqlPreparedStmt *pNext;
  419. for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
  420. pNext = pPreStmt->pNext;
  421. dbFreeStmt(pPreStmt);
  422. }
  423. pDb->nStmt = 0;
  424. pDb->stmtLast = 0;
  425. pDb->stmtList = 0;
  426. }
  427. /*
  428. ** TCL calls this procedure when an sqlite3 database command is
  429. ** deleted.
  430. */
  431. static void DbDeleteCmd(void *db){
  432. SqliteDb *pDb = (SqliteDb*)db;
  433. flushStmtCache(pDb);
  434. closeIncrblobChannels(pDb);
  435. sqlite3_close(pDb->db);
  436. while( pDb->pFunc ){
  437. SqlFunc *pFunc = pDb->pFunc;
  438. pDb->pFunc = pFunc->pNext;
  439. assert( pFunc->pDb==pDb );
  440. Tcl_DecrRefCount(pFunc->pScript);
  441. Tcl_Free((char*)pFunc);
  442. }
  443. while( pDb->pCollate ){
  444. SqlCollate *pCollate = pDb->pCollate;
  445. pDb->pCollate = pCollate->pNext;
  446. Tcl_Free((char*)pCollate);
  447. }
  448. if( pDb->zBusy ){
  449. Tcl_Free(pDb->zBusy);
  450. }
  451. if( pDb->zTrace ){
  452. Tcl_Free(pDb->zTrace);
  453. }
  454. if( pDb->zProfile ){
  455. Tcl_Free(pDb->zProfile);
  456. }
  457. if( pDb->zAuth ){
  458. Tcl_Free(pDb->zAuth);
  459. }
  460. if( pDb->zNull ){
  461. Tcl_Free(pDb->zNull);
  462. }
  463. if( pDb->pUpdateHook ){
  464. Tcl_DecrRefCount(pDb->pUpdateHook);
  465. }
  466. if( pDb->pRollbackHook ){
  467. Tcl_DecrRefCount(pDb->pRollbackHook);
  468. }
  469. if( pDb->pWalHook ){
  470. Tcl_DecrRefCount(pDb->pWalHook);
  471. }
  472. if( pDb->pCollateNeeded ){
  473. Tcl_DecrRefCount(pDb->pCollateNeeded);
  474. }
  475. Tcl_Free((char*)pDb);
  476. }
  477. /*
  478. ** This routine is called when a database file is locked while trying
  479. ** to execute SQL.
  480. */
  481. static int DbBusyHandler(void *cd, int nTries){
  482. SqliteDb *pDb = (SqliteDb*)cd;
  483. int rc;
  484. char zVal[30];
  485. sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
  486. rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
  487. if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
  488. return 0;
  489. }
  490. return 1;
  491. }
  492. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  493. /*
  494. ** This routine is invoked as the 'progress callback' for the database.
  495. */
  496. static int DbProgressHandler(void *cd){
  497. SqliteDb *pDb = (SqliteDb*)cd;
  498. int rc;
  499. assert( pDb->zProgress );
  500. rc = Tcl_Eval(pDb->interp, pDb->zProgress);
  501. if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
  502. return 1;
  503. }
  504. return 0;
  505. }
  506. #endif
  507. #ifndef SQLITE_OMIT_TRACE
  508. /*
  509. ** This routine is called by the SQLite trace handler whenever a new
  510. ** block of SQL is executed. The TCL script in pDb->zTrace is executed.
  511. */
  512. static void DbTraceHandler(void *cd, const char *zSql){
  513. SqliteDb *pDb = (SqliteDb*)cd;
  514. Tcl_DString str;
  515. Tcl_DStringInit(&str);
  516. Tcl_DStringAppend(&str, pDb->zTrace, -1);
  517. Tcl_DStringAppendElement(&str, zSql);
  518. Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
  519. Tcl_DStringFree(&str);
  520. Tcl_ResetResult(pDb->interp);
  521. }
  522. #endif
  523. #ifndef SQLITE_OMIT_TRACE
  524. /*
  525. ** This routine is called by the SQLite profile handler after a statement
  526. ** SQL has executed. The TCL script in pDb->zProfile is evaluated.
  527. */
  528. static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
  529. SqliteDb *pDb = (SqliteDb*)cd;
  530. Tcl_DString str;
  531. char zTm[100];
  532. sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
  533. Tcl_DStringInit(&str);
  534. Tcl_DStringAppend(&str, pDb->zProfile, -1);
  535. Tcl_DStringAppendElement(&str, zSql);
  536. Tcl_DStringAppendElement(&str, zTm);
  537. Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
  538. Tcl_DStringFree(&str);
  539. Tcl_ResetResult(pDb->interp);
  540. }
  541. #endif
  542. /*
  543. ** This routine is called when a transaction is committed. The
  544. ** TCL script in pDb->zCommit is executed. If it returns non-zero or
  545. ** if it throws an exception, the transaction is rolled back instead
  546. ** of being committed.
  547. */
  548. static int DbCommitHandler(void *cd){
  549. SqliteDb *pDb = (SqliteDb*)cd;
  550. int rc;
  551. rc = Tcl_Eval(pDb->interp, pDb->zCommit);
  552. if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
  553. return 1;
  554. }
  555. return 0;
  556. }
  557. static void DbRollbackHandler(void *clientData){
  558. SqliteDb *pDb = (SqliteDb*)clientData;
  559. assert(pDb->pRollbackHook);
  560. if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
  561. Tcl_BackgroundError(pDb->interp);
  562. }
  563. }
  564. /*
  565. ** This procedure handles wal_hook callbacks.
  566. */
  567. static int DbWalHandler(
  568. void *clientData,
  569. sqlite3 *db,
  570. const char *zDb,
  571. int nEntry
  572. ){
  573. int ret = SQLITE_OK;
  574. Tcl_Obj *p;
  575. SqliteDb *pDb = (SqliteDb*)clientData;
  576. Tcl_Interp *interp = pDb->interp;
  577. assert(pDb->pWalHook);
  578. p = Tcl_DuplicateObj(pDb->pWalHook);
  579. Tcl_IncrRefCount(p);
  580. Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
  581. Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
  582. if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
  583. || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
  584. ){
  585. Tcl_BackgroundError(interp);
  586. }
  587. Tcl_DecrRefCount(p);
  588. return ret;
  589. }
  590. #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
  591. static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
  592. char zBuf[64];
  593. sprintf(zBuf, "%d", iArg);
  594. Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
  595. sprintf(zBuf, "%d", nArg);
  596. Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
  597. }
  598. #else
  599. # define setTestUnlockNotifyVars(x,y,z)
  600. #endif
  601. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  602. static void DbUnlockNotify(void **apArg, int nArg){
  603. int i;
  604. for(i=0; i<nArg; i++){
  605. const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
  606. SqliteDb *pDb = (SqliteDb *)apArg[i];
  607. setTestUnlockNotifyVars(pDb->interp, i, nArg);
  608. assert( pDb->pUnlockNotify);
  609. Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
  610. Tcl_DecrRefCount(pDb->pUnlockNotify);
  611. pDb->pUnlockNotify = 0;
  612. }
  613. }
  614. #endif
  615. static void DbUpdateHandler(
  616. void *p,
  617. int op,
  618. const char *zDb,
  619. const char *zTbl,
  620. sqlite_int64 rowid
  621. ){
  622. SqliteDb *pDb = (SqliteDb *)p;
  623. Tcl_Obj *pCmd;
  624. assert( pDb->pUpdateHook );
  625. assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
  626. pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
  627. Tcl_IncrRefCount(pCmd);
  628. Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
  629. ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
  630. Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
  631. Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
  632. Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
  633. Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
  634. Tcl_DecrRefCount(pCmd);
  635. }
  636. static void tclCollateNeeded(
  637. void *pCtx,
  638. sqlite3 *db,
  639. int enc,
  640. const char *zName
  641. ){
  642. SqliteDb *pDb = (SqliteDb *)pCtx;
  643. Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
  644. Tcl_IncrRefCount(pScript);
  645. Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
  646. Tcl_EvalObjEx(pDb->interp, pScript, 0);
  647. Tcl_DecrRefCount(pScript);
  648. }
  649. /*
  650. ** This routine is called to evaluate an SQL collation function implemented
  651. ** using TCL script.
  652. */
  653. static int tclSqlCollate(
  654. void *pCtx,
  655. int nA,
  656. const void *zA,
  657. int nB,
  658. const void *zB
  659. ){
  660. SqlCollate *p = (SqlCollate *)pCtx;
  661. Tcl_Obj *pCmd;
  662. pCmd = Tcl_NewStringObj(p->zScript, -1);
  663. Tcl_IncrRefCount(pCmd);
  664. Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
  665. Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
  666. Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
  667. Tcl_DecrRefCount(pCmd);
  668. return (atoi(Tcl_GetStringResult(p->interp)));
  669. }
  670. /*
  671. ** This routine is called to evaluate an SQL function implemented
  672. ** using TCL script.
  673. */
  674. static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
  675. SqlFunc *p = sqlite3_user_data(context);
  676. Tcl_Obj *pCmd;
  677. int i;
  678. int rc;
  679. if( argc==0 ){
  680. /* If there are no arguments to the function, call Tcl_EvalObjEx on the
  681. ** script object directly. This allows the TCL compiler to generate
  682. ** bytecode for the command on the first invocation and thus make
  683. ** subsequent invocations much faster. */
  684. pCmd = p->pScript;
  685. Tcl_IncrRefCount(pCmd);
  686. rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
  687. Tcl_DecrRefCount(pCmd);
  688. }else{
  689. /* If there are arguments to the function, make a shallow copy of the
  690. ** script object, lappend the arguments, then evaluate the copy.
  691. **
  692. ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
  693. ** The new Tcl_Obj contains pointers to the original list elements.
  694. ** That way, when Tcl_EvalObjv() is run and shimmers the first element
  695. ** of the list to tclCmdNameType, that alternate representation will
  696. ** be preserved and reused on the next invocation.
  697. */
  698. Tcl_Obj **aArg;
  699. int nArg;
  700. if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
  701. sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
  702. return;
  703. }
  704. pCmd = Tcl_NewListObj(nArg, aArg);
  705. Tcl_IncrRefCount(pCmd);
  706. for(i=0; i<argc; i++){
  707. sqlite3_value *pIn = argv[i];
  708. Tcl_Obj *pVal;
  709. /* Set pVal to contain the i'th column of this row. */
  710. switch( sqlite3_value_type(pIn) ){
  711. case SQLITE_BLOB: {
  712. int bytes = sqlite3_value_bytes(pIn);
  713. pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
  714. break;
  715. }
  716. case SQLITE_INTEGER: {
  717. sqlite_int64 v = sqlite3_value_int64(pIn);
  718. if( v>=-2147483647 && v<=2147483647 ){
  719. pVal = Tcl_NewIntObj((int)v);
  720. }else{
  721. pVal = Tcl_NewWideIntObj(v);
  722. }
  723. break;
  724. }
  725. case SQLITE_FLOAT: {
  726. double r = sqlite3_value_double(pIn);
  727. pVal = Tcl_NewDoubleObj(r);
  728. break;
  729. }
  730. case SQLITE_NULL: {
  731. pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
  732. break;
  733. }
  734. default: {
  735. int bytes = sqlite3_value_bytes(pIn);
  736. pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
  737. break;
  738. }
  739. }
  740. rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
  741. if( rc ){
  742. Tcl_DecrRefCount(pCmd);
  743. sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
  744. return;
  745. }
  746. }
  747. if( !p->useEvalObjv ){
  748. /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
  749. ** is a list without a string representation. To prevent this from
  750. ** happening, make sure pCmd has a valid string representation */
  751. Tcl_GetString(pCmd);
  752. }
  753. rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
  754. Tcl_DecrRefCount(pCmd);
  755. }
  756. if( rc && rc!=TCL_RETURN ){
  757. sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
  758. }else{
  759. Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
  760. int n;
  761. u8 *data;
  762. const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
  763. char c = zType[0];
  764. if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
  765. /* Only return a BLOB type if the Tcl variable is a bytearray and
  766. ** has no string representation. */
  767. data = Tcl_GetByteArrayFromObj(pVar, &n);
  768. sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
  769. }else if( c=='b' && strcmp(zType,"boolean")==0 ){
  770. Tcl_GetIntFromObj(0, pVar, &n);
  771. sqlite3_result_int(context, n);
  772. }else if( c=='d' && strcmp(zType,"double")==0 ){
  773. double r;
  774. Tcl_GetDoubleFromObj(0, pVar, &r);
  775. sqlite3_result_double(context, r);
  776. }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
  777. (c=='i' && strcmp(zType,"int")==0) ){
  778. Tcl_WideInt v;
  779. Tcl_GetWideIntFromObj(0, pVar, &v);
  780. sqlite3_result_int64(context, v);
  781. }else{
  782. data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
  783. sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
  784. }
  785. }
  786. }
  787. #ifndef SQLITE_OMIT_AUTHORIZATION
  788. /*
  789. ** This is the authentication function. It appends the authentication
  790. ** type code and the two arguments to zCmd[] then invokes the result
  791. ** on the interpreter. The reply is examined to determine if the
  792. ** authentication fails or succeeds.
  793. */
  794. static int auth_callback(
  795. void *pArg,
  796. int code,
  797. const char *zArg1,
  798. const char *zArg2,
  799. const char *zArg3,
  800. const char *zArg4
  801. ){
  802. char *zCode;
  803. Tcl_DString str;
  804. int rc;
  805. const char *zReply;
  806. SqliteDb *pDb = (SqliteDb*)pArg;
  807. if( pDb->disableAuth ) return SQLITE_OK;
  808. switch( code ){
  809. case SQLITE_COPY : zCode="SQLITE_COPY"; break;
  810. case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
  811. case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
  812. case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
  813. case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
  814. case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
  815. case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
  816. case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
  817. case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
  818. case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
  819. case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
  820. case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
  821. case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
  822. case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
  823. case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
  824. case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
  825. case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
  826. case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
  827. case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
  828. case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
  829. case SQLITE_READ : zCode="SQLITE_READ"; break;
  830. case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
  831. case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
  832. case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
  833. case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
  834. case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
  835. case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
  836. case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
  837. case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
  838. case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
  839. case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
  840. case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
  841. case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
  842. default : zCode="????"; break;
  843. }
  844. Tcl_DStringInit(&str);
  845. Tcl_DStringAppend(&str, pDb->zAuth, -1);
  846. Tcl_DStringAppendElement(&str, zCode);
  847. Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
  848. Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
  849. Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
  850. Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
  851. rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
  852. Tcl_DStringFree(&str);
  853. zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
  854. if( strcmp(zReply,"SQLITE_OK")==0 ){
  855. rc = SQLITE_OK;
  856. }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
  857. rc = SQLITE_DENY;
  858. }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
  859. rc = SQLITE_IGNORE;
  860. }else{
  861. rc = 999;
  862. }
  863. return rc;
  864. }
  865. #endif /* SQLITE_OMIT_AUTHORIZATION */
  866. /*
  867. ** This routine reads a line of text from FILE in, stores
  868. ** the text in memory obtained from malloc() and returns a pointer
  869. ** to the text. NULL is returned at end of file, or if malloc()
  870. ** fails.
  871. **
  872. ** The interface is like "readline" but no command-line editing
  873. ** is done.
  874. **
  875. ** copied from shell.c from '.import' command
  876. */
  877. static char *local_getline(char *zPrompt, FILE *in){
  878. char *zLine;
  879. int nLine;
  880. int n;
  881. nLine = 100;
  882. zLine = malloc( nLine );
  883. if( zLine==0 ) return 0;
  884. n = 0;
  885. while( 1 ){
  886. if( n+100>nLine ){
  887. nLine = nLine*2 + 100;
  888. zLine = realloc(zLine, nLine);
  889. if( zLine==0 ) return 0;
  890. }
  891. if( fgets(&zLine[n], nLine - n, in)==0 ){
  892. if( n==0 ){
  893. free(zLine);
  894. return 0;
  895. }
  896. zLine[n] = 0;
  897. break;
  898. }
  899. while( zLine[n] ){ n++; }
  900. if( n>0 && zLine[n-1]=='\n' ){
  901. n--;
  902. zLine[n] = 0;
  903. break;
  904. }
  905. }
  906. zLine = realloc( zLine, n+1 );
  907. return zLine;
  908. }
  909. /*
  910. ** This function is part of the implementation of the command:
  911. **
  912. ** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
  913. **
  914. ** It is invoked after evaluating the script SCRIPT to commit or rollback
  915. ** the transaction or savepoint opened by the [transaction] command.
  916. */
  917. static int DbTransPostCmd(
  918. ClientData data[], /* data[0] is the Sqlite3Db* for $db */
  919. Tcl_Interp *interp, /* Tcl interpreter */
  920. int result /* Result of evaluating SCRIPT */
  921. ){
  922. static const char *azEnd[] = {
  923. "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
  924. "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
  925. "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
  926. "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
  927. };
  928. SqliteDb *pDb = (SqliteDb*)data[0];
  929. int rc = result;
  930. const char *zEnd;
  931. pDb->nTransaction--;
  932. zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
  933. pDb->disableAuth++;
  934. if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
  935. /* This is a tricky scenario to handle. The most likely cause of an
  936. ** error is that the exec() above was an attempt to commit the
  937. ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
  938. ** that an IO-error has occurred. In either case, throw a Tcl exception
  939. ** and try to rollback the transaction.
  940. **
  941. ** But it could also be that the user executed one or more BEGIN,
  942. ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
  943. ** this method's logic. Not clear how this would be best handled.
  944. */
  945. if( rc!=TCL_ERROR ){
  946. Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
  947. rc = TCL_ERROR;
  948. }
  949. sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
  950. }
  951. pDb->disableAuth--;
  952. return rc;
  953. }
  954. /*
  955. ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
  956. ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
  957. ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
  958. ** on whether or not the [db_use_legacy_prepare] command has been used to
  959. ** configure the connection.
  960. */
  961. static int dbPrepare(
  962. SqliteDb *pDb, /* Database object */
  963. const char *zSql, /* SQL to compile */
  964. sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
  965. const char **pzOut /* OUT: Pointer to next SQL statement */
  966. ){
  967. #ifdef SQLITE_TEST
  968. if( pDb->bLegacyPrepare ){
  969. return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
  970. }
  971. #endif
  972. return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
  973. }
  974. /*
  975. ** Search the cache for a prepared-statement object that implements the
  976. ** first SQL statement in the buffer pointed to by parameter zIn. If
  977. ** no such prepared-statement can be found, allocate and prepare a new
  978. ** one. In either case, bind the current values of the relevant Tcl
  979. ** variables to any $var, :var or @var variables in the statement. Before
  980. ** returning, set *ppPreStmt to point to the prepared-statement object.
  981. **
  982. ** Output parameter *pzOut is set to point to the next SQL statement in
  983. ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
  984. ** next statement.
  985. **
  986. ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
  987. ** and an error message loaded into interpreter pDb->interp.
  988. */
  989. static int dbPrepareAndBind(
  990. SqliteDb *pDb, /* Database object */
  991. char const *zIn, /* SQL to compile */
  992. char const **pzOut, /* OUT: Pointer to next SQL statement */
  993. SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
  994. ){
  995. const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
  996. sqlite3_stmt *pStmt; /* Prepared statement object */
  997. SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
  998. int nSql; /* Length of zSql in bytes */
  999. int nVar; /* Number of variables in statement */
  1000. int iParm = 0; /* Next free entry in apParm */
  1001. int i;
  1002. Tcl_Interp *interp = pDb->interp;
  1003. *ppPreStmt = 0;
  1004. /* Trim spaces from the start of zSql and calculate the remaining length. */
  1005. while( isspace(zSql[0]) ){ zSql++; }
  1006. nSql = strlen30(zSql);
  1007. for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
  1008. int n = pPreStmt->nSql;
  1009. if( nSql>=n
  1010. && memcmp(pPreStmt->zSql, zSql, n)==0
  1011. && (zSql[n]==0 || zSql[n-1]==';')
  1012. ){
  1013. pStmt = pPreStmt->pStmt;
  1014. *pzOut = &zSql[pPreStmt->nSql];
  1015. /* When a prepared statement is found, unlink it from the
  1016. ** cache list. It will later be added back to the beginning
  1017. ** of the cache list in order to implement LRU replacement.
  1018. */
  1019. if( pPreStmt->pPrev ){
  1020. pPreStmt->pPrev->pNext = pPreStmt->pNext;
  1021. }else{
  1022. pDb->stmtList = pPreStmt->pNext;
  1023. }
  1024. if( pPreStmt->pNext ){
  1025. pPreStmt->pNext->pPrev = pPreStmt->pPrev;
  1026. }else{
  1027. pDb->stmtLast = pPreStmt->pPrev;
  1028. }
  1029. pDb->nStmt--;
  1030. nVar = sqlite3_bind_parameter_count(pStmt);
  1031. break;
  1032. }
  1033. }
  1034. /* If no prepared statement was found. Compile the SQL text. Also allocate
  1035. ** a new SqlPreparedStmt structure. */
  1036. if( pPreStmt==0 ){
  1037. int nByte;
  1038. if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
  1039. Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
  1040. return TCL_ERROR;
  1041. }
  1042. if( pStmt==0 ){
  1043. if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
  1044. /* A compile-time error in the statement. */
  1045. Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
  1046. return TCL_ERROR;
  1047. }else{
  1048. /* The statement was a no-op. Continue to the next statement
  1049. ** in the SQL string.
  1050. */
  1051. return TCL_OK;
  1052. }
  1053. }
  1054. assert( pPreStmt==0 );
  1055. nVar = sqlite3_bind_parameter_count(pStmt);
  1056. nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
  1057. pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
  1058. memset(pPreStmt, 0, nByte);
  1059. pPreStmt->pStmt = pStmt;
  1060. pPreStmt->nSql = (int)(*pzOut - zSql);
  1061. pPreStmt->zSql = sqlite3_sql(pStmt);
  1062. pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
  1063. #ifdef SQLITE_TEST
  1064. if( pPreStmt->zSql==0 ){
  1065. char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
  1066. memcpy(zCopy, zSql, pPreStmt->nSql);
  1067. zCopy[pPreStmt->nSql] = '\0';
  1068. pPreStmt->zSql = zCopy;
  1069. }
  1070. #endif
  1071. }
  1072. assert( pPreStmt );
  1073. assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
  1074. assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
  1075. /* Bind values to parameters that begin with $ or : */
  1076. for(i=1; i<=nVar; i++){
  1077. const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
  1078. if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
  1079. Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
  1080. if( pVar ){
  1081. int n;
  1082. u8 *data;
  1083. const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
  1084. char c = zType[0];
  1085. if( zVar[0]=='@' ||
  1086. (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
  1087. /* Load a BLOB type if the Tcl variable is a bytearray and
  1088. ** it has no string representation or the host
  1089. ** parameter name begins with "@". */
  1090. data = Tcl_GetByteArrayFromObj(pVar, &n);
  1091. sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
  1092. Tcl_IncrRefCount(pVar);
  1093. pPreStmt->apParm[iParm++] = pVar;
  1094. }else if( c=='b' && strcmp(zType,"boolean")==0 ){
  1095. Tcl_GetIntFromObj(interp, pVar, &n);
  1096. sqlite3_bind_int(pStmt, i, n);
  1097. }else if( c=='d' && strcmp(zType,"double")==0 ){
  1098. double r;
  1099. Tcl_GetDoubleFromObj(interp, pVar, &r);
  1100. sqlite3_bind_double(pStmt, i, r);
  1101. }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
  1102. (c=='i' && strcmp(zType,"int")==0) ){
  1103. Tcl_WideInt v;
  1104. Tcl_GetWideIntFromObj(interp, pVar, &v);
  1105. sqlite3_bind_int64(pStmt, i, v);
  1106. }else{
  1107. data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
  1108. sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
  1109. Tcl_IncrRefCount(pVar);
  1110. pPreStmt->apParm[iParm++] = pVar;
  1111. }
  1112. }else{
  1113. sqlite3_bind_null(pStmt, i);
  1114. }
  1115. }
  1116. }
  1117. pPreStmt->nParm = iParm;
  1118. *ppPreStmt = pPreStmt;
  1119. return TCL_OK;
  1120. }
  1121. /*
  1122. ** Release a statement reference obtained by calling dbPrepareAndBind().
  1123. ** There should be exactly one call to this function for each call to
  1124. ** dbPrepareAndBind().
  1125. **
  1126. ** If the discard parameter is non-zero, then the statement is deleted
  1127. ** immediately. Otherwise it is added to the LRU list and may be returned
  1128. ** by a subsequent call to dbPrepareAndBind().
  1129. */
  1130. static void dbReleaseStmt(
  1131. SqliteDb *pDb, /* Database handle */
  1132. SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
  1133. int discard /* True to delete (not cache) the pPreStmt */
  1134. ){
  1135. int i;
  1136. /* Free the bound string and blob parameters */
  1137. for(i=0; i<pPreStmt->nParm; i++){
  1138. Tcl_DecrRefCount(pPreStmt->apParm[i]);
  1139. }
  1140. pPreStmt->nParm = 0;
  1141. if( pDb->maxStmt<=0 || discard ){
  1142. /* If the cache is turned off, deallocated the statement */
  1143. dbFreeStmt(pPreStmt);
  1144. }else{
  1145. /* Add the prepared statement to the beginning of the cache list. */
  1146. pPreStmt->pNext = pDb->stmtList;
  1147. pPreStmt->pPrev = 0;
  1148. if( pDb->stmtList ){
  1149. pDb->stmtList->pPrev = pPreStmt;
  1150. }
  1151. pDb->stmtList = pPreStmt;
  1152. if( pDb->stmtLast==0 ){
  1153. assert( pDb->nStmt==0 );
  1154. pDb->stmtLast = pPreStmt;
  1155. }else{
  1156. assert( pDb->nStmt>0 );
  1157. }
  1158. pDb->nStmt++;
  1159. /* If we have too many statement in cache, remove the surplus from
  1160. ** the end of the cache list. */
  1161. while( pDb->nStmt>pDb->maxStmt ){
  1162. SqlPreparedStmt *pLast = pDb->stmtLast;
  1163. pDb->stmtLast = pLast->pPrev;
  1164. pDb->stmtLast->pNext = 0;
  1165. pDb->nStmt--;
  1166. dbFreeStmt(pLast);
  1167. }
  1168. }
  1169. }
  1170. /*
  1171. ** Structure used with dbEvalXXX() functions:
  1172. **
  1173. ** dbEvalInit()
  1174. ** dbEvalStep()
  1175. ** dbEvalFinalize()
  1176. ** dbEvalRowInfo()
  1177. ** dbEvalColumnValue()
  1178. */
  1179. typedef struct DbEvalContext DbEvalContext;
  1180. struct DbEvalContext {
  1181. SqliteDb *pDb; /* Database handle */
  1182. Tcl_Obj *pSql; /* Object holding string zSql */
  1183. const char *zSql; /* Remaining SQL to execute */
  1184. SqlPreparedStmt *pPreStmt; /* Current statement */
  1185. int nCol; /* Number of columns returned by pStmt */
  1186. Tcl_Obj *pArray; /* Name of array variable */
  1187. Tcl_Obj **apColName; /* Array of column names */
  1188. };
  1189. /*
  1190. ** Release any cache of column names currently held as part of
  1191. ** the DbEvalContext structure passed as the first argument.
  1192. */
  1193. static void dbReleaseColumnNames(DbEvalContext *p){
  1194. if( p->apColName ){
  1195. int i;
  1196. for(i=0; i<p->nCol; i++){
  1197. Tcl_DecrRefCount(p->apColName[i]);
  1198. }
  1199. Tcl_Free((char *)p->apColName);
  1200. p->apColName = 0;
  1201. }
  1202. p->nCol = 0;
  1203. }
  1204. /*
  1205. ** Initialize a DbEvalContext structure.
  1206. **
  1207. ** If pArray is not NULL, then it contains the name of a Tcl array
  1208. ** variable. The "*" member of this array is set to a list containing
  1209. ** the names of the columns returned by the statement as part of each
  1210. ** call to dbEvalStep(), in order from left to right. e.g. if the names
  1211. ** of the returned columns are a, b and c, it does the equivalent of the
  1212. ** tcl command:
  1213. **
  1214. ** set ${pArray}(*) {a b c}
  1215. */
  1216. static void dbEvalInit(
  1217. DbEvalContext *p, /* Pointer to structure to initialize */
  1218. SqliteDb *pDb, /* Database handle */
  1219. Tcl_Obj *pSql, /* Object containing SQL script */
  1220. Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
  1221. ){
  1222. memset(p, 0, sizeof(DbEvalContext));
  1223. p->pDb = pDb;
  1224. p->zSql = Tcl_GetString(pSql);
  1225. p->pSql = pSql;
  1226. Tcl_IncrRefCount(pSql);
  1227. if( pArray ){
  1228. p->pArray = pArray;
  1229. Tcl_IncrRefCount(pArray);
  1230. }
  1231. }
  1232. /*
  1233. ** Obtain information about the row that the DbEvalContext passed as the
  1234. ** first argument currently points to.
  1235. */
  1236. static void dbEvalRowInfo(
  1237. DbEvalContext *p, /* Evaluation context */
  1238. int *pnCol, /* OUT: Number of column names */
  1239. Tcl_Obj ***papColName /* OUT: Array of column names */
  1240. ){
  1241. /* Compute column names */
  1242. if( 0==p->apColName ){
  1243. sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
  1244. int i; /* Iterator variable */
  1245. int nCol; /* Number of columns returned by pStmt */
  1246. Tcl_Obj **apColName = 0; /* Array of column names */
  1247. p->nCol = nCol = sqlite3_column_count(pStmt);
  1248. if( nCol>0 && (papColName || p->pArray) ){
  1249. apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
  1250. for(i=0; i<nCol; i++){
  1251. apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
  1252. Tcl_IncrRefCount(apColName[i]);
  1253. }
  1254. p->apColName = apColName;
  1255. }
  1256. /* If results are being stored in an array variable, then create
  1257. ** the array(*) entry for that array
  1258. */
  1259. if( p->pArray ){
  1260. Tcl_Interp *interp = p->pDb->interp;
  1261. Tcl_Obj *pColList = Tcl_NewObj();
  1262. Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
  1263. for(i=0; i<nCol; i++){
  1264. Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
  1265. }
  1266. Tcl_IncrRefCount(pStar);
  1267. Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
  1268. Tcl_DecrRefCount(pStar);
  1269. }
  1270. }
  1271. if( papColName ){
  1272. *papColName = p->apColName;
  1273. }
  1274. if( pnCol ){
  1275. *pnCol = p->nCol;
  1276. }
  1277. }
  1278. /*
  1279. ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
  1280. ** returned, then an error message is stored in the interpreter before
  1281. ** returning.
  1282. **
  1283. ** A return value of TCL_OK means there is a row of data available. The
  1284. ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
  1285. ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
  1286. ** is returned, then the SQL script has finished executing and there are
  1287. ** no further rows available. This is similar to SQLITE_DONE.
  1288. */
  1289. static int dbEvalStep(DbEvalContext *p){
  1290. const char *zPrevSql = 0; /* Previous value of p->zSql */
  1291. while( p->zSql[0] || p->pPreStmt ){
  1292. int rc;
  1293. if( p->pPreStmt==0 ){
  1294. zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
  1295. rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
  1296. if( rc!=TCL_OK ) return rc;
  1297. }else{
  1298. int rcs;
  1299. SqliteDb *pDb = p->pDb;
  1300. SqlPreparedStmt *pPreStmt = p->pPreStmt;
  1301. sqlite3_stmt *pStmt = pPreStmt->pStmt;
  1302. rcs = sqlite3_step(pStmt);
  1303. if( rcs==SQLITE_ROW ){
  1304. return TCL_OK;
  1305. }
  1306. if( p->pArray ){
  1307. dbEvalRowInfo(p, 0, 0);
  1308. }
  1309. rcs = sqlite3_reset(pStmt);
  1310. pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
  1311. pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
  1312. pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
  1313. dbReleaseColumnNames(p);
  1314. p->pPreStmt = 0;
  1315. if( rcs!=SQLITE_OK ){
  1316. /* If a run-time error occurs, report the error and stop reading
  1317. ** the SQL. */
  1318. dbReleaseStmt(pDb, pPreStmt, 1);
  1319. #if SQLITE_TEST
  1320. if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
  1321. /* If the runtime error was an SQLITE_SCHEMA, and the database
  1322. ** handle is configured to use the legacy sqlite3_prepare()
  1323. ** interface, retry prepare()/step() on the same SQL statement.
  1324. ** This only happens once. If there is a second SQLITE_SCHEMA
  1325. ** error, the error will be returned to the caller. */
  1326. p->zSql = zPrevSql;
  1327. continue;
  1328. }
  1329. #endif
  1330. Tcl_SetObjResult(pDb->interp,
  1331. Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
  1332. return TCL_ERROR;
  1333. }else{
  1334. dbReleaseStmt(pDb, pPreStmt, 0);
  1335. }
  1336. }
  1337. }
  1338. /* Finished */
  1339. return TCL_BREAK;
  1340. }
  1341. /*
  1342. ** Free all resources currently held by the DbEvalContext structure passed
  1343. ** as the first argument. There should be exactly one call to this function
  1344. ** for each call to dbEvalInit().
  1345. */
  1346. static void dbEvalFinalize(DbEvalContext *p){
  1347. if( p->pPreStmt ){
  1348. sqlite3_reset(p->pPreStmt->pStmt);
  1349. dbReleaseStmt(p->pDb, p->pPreStmt, 0);
  1350. p->pPreStmt = 0;
  1351. }
  1352. if( p->pArray ){
  1353. Tcl_DecrRefCount(p->pArray);
  1354. p->pArray = 0;
  1355. }
  1356. Tcl_DecrRefCount(p->pSql);
  1357. dbReleaseColumnNames(p);
  1358. }
  1359. /*
  1360. ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
  1361. ** the value for the iCol'th column of the row currently pointed to by
  1362. ** the DbEvalContext structure passed as the first argument.
  1363. */
  1364. static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
  1365. sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
  1366. switch( sqlite3_column_type(pStmt, iCol) ){
  1367. case SQLITE_BLOB: {
  1368. int bytes = sqlite3_column_bytes(pStmt, iCol);
  1369. const char *zBlob = sqlite3_column_blob(pStmt, iCol);
  1370. if( !zBlob ) bytes = 0;
  1371. return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
  1372. }
  1373. case SQLITE_INTEGER: {
  1374. sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
  1375. if( v>=-2147483647 && v<=2147483647 ){
  1376. return Tcl_NewIntObj((int)v);
  1377. }else{
  1378. return Tcl_NewWideIntObj(v);
  1379. }
  1380. }
  1381. case SQLITE_FLOAT: {
  1382. return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
  1383. }
  1384. case SQLITE_NULL: {
  1385. return Tcl_NewStringObj(p->pDb->zNull, -1);
  1386. }
  1387. }
  1388. return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
  1389. }
  1390. /*
  1391. ** If using Tcl version 8.6 or greater, use the NR functions to avoid
  1392. ** recursive evalution of scripts by the [db eval] and [db trans]
  1393. ** commands. Even if the headers used while compiling the extension
  1394. ** are 8.6 or newer, the code still tests the Tcl version at runtime.
  1395. ** This allows stubs-enabled builds to be used with older Tcl libraries.
  1396. */
  1397. #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
  1398. # define SQLITE_TCL_NRE 1
  1399. static int DbUseNre(void){
  1400. int major, minor;
  1401. Tcl_GetVersion(&major, &minor, 0, 0);
  1402. return( (major==8 && minor>=6) || major>8 );
  1403. }
  1404. #else
  1405. /*
  1406. ** Compiling using headers earlier than 8.6. In this case NR cannot be
  1407. ** used, so DbUseNre() to always return zero. Add #defines for the other
  1408. ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
  1409. ** even though the only invocations of them are within conditional blocks
  1410. ** of the form:
  1411. **
  1412. ** if( DbUseNre() ) { ... }
  1413. */
  1414. # define SQLITE_TCL_NRE 0
  1415. # define DbUseNre() 0
  1416. # define Tcl_NRAddCallback(a,b,c,d,e,f) 0
  1417. # define Tcl_NREvalObj(a,b,c) 0
  1418. # define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
  1419. #endif
  1420. /*
  1421. ** This function is part of the implementation of the command:
  1422. **
  1423. ** $db eval SQL ?ARRAYNAME? SCRIPT
  1424. */
  1425. static int DbEvalNextCmd(
  1426. ClientData data[], /* data[0] is the (DbEvalContext*) */
  1427. Tcl_Interp *interp, /* Tcl interpreter */
  1428. int result /* Result so far */
  1429. ){
  1430. int rc = result; /* Return code */
  1431. /* The first element of the data[] array is a pointer to a DbEvalContext
  1432. ** structure allocated using Tcl_Alloc(). The second element of data[]
  1433. ** is a pointer to a Tcl_Obj containing the script to run for each row
  1434. ** returned by the queries encapsulated in data[0]. */
  1435. DbEvalContext *p = (DbEvalContext *)data[0];
  1436. Tcl_Obj *pScript = (Tcl_Obj *)data[1];
  1437. Tcl_Obj *pArray = p->pArray;
  1438. while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
  1439. int i;
  1440. int nCol;
  1441. Tcl_Obj **apColName;
  1442. dbEvalRowInfo(p, &nCol, &apColName);
  1443. for(i=0; i<nCol; i++){
  1444. Tcl_Obj *pVal = dbEvalColumnValue(p, i);
  1445. if( pArray==0 ){
  1446. Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
  1447. }else{
  1448. Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
  1449. }
  1450. }
  1451. /* The required interpreter variables are now populated with the data
  1452. ** from the current row. If using NRE, schedule callbacks to evaluate
  1453. ** script pScript, then to invoke this function again to fetch the next
  1454. ** row (or clean up if there is no next row or the script throws an
  1455. ** exception). After scheduling the callbacks, return control to the
  1456. ** caller.
  1457. **
  1458. ** If not using NRE, evaluate pScript directly and continue with the
  1459. ** next iteration of this while(...) loop. */
  1460. if( DbUseNre() ){
  1461. Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
  1462. return Tcl_NREvalObj(interp, pScript, 0);
  1463. }else{
  1464. rc = Tcl_EvalObjEx(interp, pScript, 0);
  1465. }
  1466. }
  1467. Tcl_DecrRefCount(pScript);
  1468. dbEvalFinalize(p);
  1469. Tcl_Free((char *)p);
  1470. if( rc==TCL_OK || rc==TCL_BREAK ){
  1471. Tcl_ResetResult(interp);
  1472. rc = TCL_OK;
  1473. }
  1474. return rc;
  1475. }
  1476. /*
  1477. ** The "sqlite" command below creates a new Tcl command for each
  1478. ** connection it opens to an SQLite database. This routine is invoked
  1479. ** whenever one of those connection-specific commands is executed
  1480. ** in Tcl. For example, if you run Tcl code like this:
  1481. **
  1482. ** sqlite3 db1 "my_database"
  1483. ** db1 close
  1484. **
  1485. ** The first command opens a connection to the "my_database" database
  1486. ** and calls that connection "db1". The second command causes this
  1487. ** subroutine to be invoked.
  1488. */
  1489. static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
  1490. SqliteDb *pDb = (SqliteDb*)cd;
  1491. int choice;
  1492. int rc = TCL_OK;
  1493. static const char *DB_strs[] = {
  1494. "authorizer", "backup", "busy",
  1495. "cache", "changes", "close",
  1496. "collate", "collation_needed", "commit_hook",
  1497. "complete", "copy", "enable_load_extension",
  1498. "errorcode", "eval", "exists",
  1499. "function", "incrblob", "interrupt",
  1500. "last_insert_rowid", "nullvalue", "onecolumn",
  1501. "profile", "progress", "rekey",
  1502. "restore", "rollback_hook", "status",
  1503. "timeout", "total_changes", "trace",
  1504. "transaction", "unlock_notify", "update_hook",
  1505. "version", "wal_hook", 0
  1506. };
  1507. enum DB_enum {
  1508. DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
  1509. DB_CACHE, DB_CHANGES, DB_CLOSE,
  1510. DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
  1511. DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
  1512. DB_ERRORCODE, DB_EVAL, DB_EXISTS,
  1513. DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
  1514. DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
  1515. DB_PROFILE, DB_PROGRESS, DB_REKEY,
  1516. DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS,
  1517. DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
  1518. DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
  1519. DB_VERSION, DB_WAL_HOOK
  1520. };
  1521. /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
  1522. if( objc<2 ){
  1523. Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
  1524. return TCL_ERROR;
  1525. }
  1526. if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
  1527. return TCL_ERROR;
  1528. }
  1529. switch( (enum DB_enum)choice ){
  1530. /* $db authorizer ?CALLBACK?
  1531. **
  1532. ** Invoke the given callback to authorize each SQL operation as it is
  1533. ** compiled. 5 arguments are appended to the callback before it is
  1534. ** invoked:
  1535. **
  1536. ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
  1537. ** (2) First descriptive name (depends on authorization type)
  1538. ** (3) Second descriptive name
  1539. ** (4) Name of the database (ex: "main", "temp")
  1540. ** (5) Name of trigger that is doing the access
  1541. **
  1542. ** The callback should return on of the following strings: SQLITE_OK,
  1543. ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
  1544. **
  1545. ** If this method is invoked with no arguments, the current authorization
  1546. ** callback string is returned.
  1547. */
  1548. case DB_AUTHORIZER: {
  1549. #ifdef SQLITE_OMIT_AUTHORIZATION
  1550. Tcl_AppendResult(interp, "authorization not available in this build", 0);
  1551. return TCL_ERROR;
  1552. #else
  1553. if( objc>3 ){
  1554. Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
  1555. return TCL_ERROR;
  1556. }else if( objc==2 ){
  1557. if( pDb->zAuth ){
  1558. Tcl_AppendResult(interp, pDb->zAuth, 0);
  1559. }
  1560. }else{
  1561. char *zAuth;
  1562. int len;
  1563. if( pDb->zAuth ){
  1564. Tcl_Free(pDb->zAuth);
  1565. }
  1566. zAuth = Tcl_GetStringFromObj(objv[2], &len);
  1567. if( zAuth && len>0 ){
  1568. pDb->zAuth = Tcl_Alloc( len + 1 );
  1569. memcpy(pDb->zAuth, zAuth, len+1);
  1570. }else{
  1571. pDb->zAuth = 0;
  1572. }
  1573. if( pDb->zAuth ){
  1574. pDb->interp = interp;
  1575. sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
  1576. }else{
  1577. sqlite3_set_authorizer(pDb->db, 0, 0);
  1578. }
  1579. }
  1580. #endif
  1581. break;
  1582. }
  1583. /* $db backup ?DATABASE? FILENAME
  1584. **
  1585. ** Open or create a database file named FILENAME. Transfer the
  1586. ** content of local database DATABASE (default: "main") into the
  1587. ** FILENAME database.
  1588. */
  1589. case DB_BACKUP: {
  1590. const char *zDestFile;
  1591. const char *zSrcDb;
  1592. sqlite3 *pDest;
  1593. sqlite3_backup *pBackup;
  1594. if( objc==3 ){
  1595. zSrcDb = "main";
  1596. zDestFile = Tcl_GetString(objv[2]);
  1597. }else if( objc==4 ){
  1598. zSrcDb = Tcl_GetString(objv[2]);
  1599. zDestFile = Tcl_GetString(objv[3]);
  1600. }else{
  1601. Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
  1602. return TCL_ERROR;
  1603. }
  1604. rc = sqlite3_open(zDestFile, &pDest);
  1605. if( rc!=SQLITE_OK ){
  1606. Tcl_AppendResult(interp, "cannot open target database: ",
  1607. sqlite3_errmsg(pDest), (char*)0);
  1608. sqlite3_close(pDest);
  1609. return TCL_ERROR;
  1610. }
  1611. pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
  1612. if( pBackup==0 ){
  1613. Tcl_AppendResult(interp, "backup failed: ",
  1614. sqlite3_errmsg(pDest), (char*)0);
  1615. sqlite3_close(pDest);
  1616. return TCL_ERROR;
  1617. }
  1618. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  1619. sqlite3_backup_finish(pBackup);
  1620. if( rc==SQLITE_DONE ){
  1621. rc = TCL_OK;
  1622. }else{
  1623. Tcl_AppendResult(interp, "backup failed: ",
  1624. sqlite3_errmsg(pDest), (char*)0);
  1625. rc = TCL_ERROR;
  1626. }
  1627. sqlite3_close(pDest);
  1628. break;
  1629. }
  1630. /* $db busy ?CALLBACK?
  1631. **
  1632. ** Invoke the given callback if an SQL statement attempts to open
  1633. ** a locked database file.
  1634. */
  1635. case DB_BUSY: {
  1636. if( objc>3 ){
  1637. Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
  1638. return TCL_ERROR;
  1639. }else if( objc==2 ){
  1640. if( pDb->zBusy ){
  1641. Tcl_AppendResult(interp, pDb->zBusy, 0);
  1642. }
  1643. }else{
  1644. char *zBusy;
  1645. int len;
  1646. if( pDb->zBusy ){
  1647. Tcl_Free(pDb->zBusy);
  1648. }
  1649. zBusy = Tcl_GetStringFromObj(objv[2], &len);
  1650. if( zBusy && len>0 ){
  1651. pDb->zBusy = Tcl_Alloc( len + 1 );
  1652. memcpy(pDb->zBusy, zBusy, len+1);
  1653. }else{
  1654. pDb->zBusy = 0;
  1655. }
  1656. if( pDb->zBusy ){
  1657. pDb->interp = interp;
  1658. sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
  1659. }else{
  1660. sqlite3_busy_handler(pDb->db, 0, 0);
  1661. }
  1662. }
  1663. break;
  1664. }
  1665. /* $db cache flush
  1666. ** $db cache size n
  1667. **
  1668. ** Flush the prepared statement cache, or set the maximum number of
  1669. ** cached statements.
  1670. */
  1671. case DB_CACHE: {
  1672. char *subCmd;
  1673. int n;
  1674. if( objc<=2 ){
  1675. Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
  1676. return TCL_ERROR;
  1677. }
  1678. subCmd = Tcl_GetStringFromObj( objv[2], 0 );
  1679. if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
  1680. if( objc!=3 ){
  1681. Tcl_WrongNumArgs(interp, 2, objv, "flush");
  1682. return TCL_ERROR;
  1683. }else{
  1684. flushStmtCache( pDb );
  1685. }
  1686. }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
  1687. if( objc!=4 ){
  1688. Tcl_WrongNumArgs(interp, 2, objv, "size n");
  1689. return TCL_ERROR;
  1690. }else{
  1691. if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
  1692. Tcl_AppendResult( interp, "cannot convert \"",
  1693. Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
  1694. return TCL_ERROR;
  1695. }else{
  1696. if( n<0 ){
  1697. flushStmtCache( pDb );
  1698. n = 0;
  1699. }else if( n>MAX_PREPARED_STMTS ){
  1700. n = MAX_PREPARED_STMTS;
  1701. }
  1702. pDb->maxStmt = n;
  1703. }
  1704. }
  1705. }else{
  1706. Tcl_AppendResult( interp, "bad option \"",
  1707. Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
  1708. return TCL_ERROR;
  1709. }
  1710. break;
  1711. }
  1712. /* $db changes
  1713. **
  1714. ** Return the number of rows that were modified, inserted, or deleted by
  1715. ** the most recent INSERT, UPDATE or DELETE statement, not including
  1716. ** any changes made by trigger programs.
  1717. */
  1718. case DB_CHANGES: {
  1719. Tcl_Obj *pResult;
  1720. if( objc!=2 ){
  1721. Tcl_WrongNumArgs(interp, 2, objv, "");
  1722. return TCL_ERROR;
  1723. }
  1724. pResult = Tcl_GetObjResult(interp);
  1725. Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
  1726. break;
  1727. }
  1728. /* $db close
  1729. **
  1730. ** Shutdown the database
  1731. */
  1732. case DB_CLOSE: {
  1733. Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
  1734. break;
  1735. }
  1736. /*
  1737. ** $db collate NAME SCRIPT
  1738. **
  1739. ** Create a new SQL collation function called NAME. Whenever
  1740. ** that function is called, invoke SCRIPT to evaluate the function.
  1741. */
  1742. case DB_COLLATE: {
  1743. SqlCollate *pCollate;
  1744. char *zName;
  1745. char *zScript;
  1746. int nScript;
  1747. if( objc!=4 ){
  1748. Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
  1749. return TCL_ERROR;
  1750. }
  1751. zName = Tcl_GetStringFromObj(objv[2], 0);
  1752. zScript = Tcl_GetStringFromObj(objv[3], &nScript);
  1753. pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
  1754. if( pCollate==0 ) return TCL_ERROR;
  1755. pCollate->interp = interp;
  1756. pCollate->pNext = pDb->pCollate;
  1757. pCollate->zScript = (char*)&pCollate[1];
  1758. pDb->pCollate = pCollate;
  1759. memcpy(pCollate->zScript, zScript, nScript+1);
  1760. if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
  1761. pCollate, tclSqlCollate) ){
  1762. Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
  1763. return TCL_ERROR;
  1764. }
  1765. break;
  1766. }
  1767. /*
  1768. ** $db collation_needed SCRIPT
  1769. **
  1770. ** Create a new SQL collation function called NAME. Whenever
  1771. ** that function is called, invoke SCRIPT to evaluate the function.
  1772. */
  1773. case DB_COLLATION_NEEDED: {
  1774. if( objc!=3 ){
  1775. Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
  1776. return TCL_ERROR;
  1777. }
  1778. if( pDb->pCollateNeeded ){
  1779. Tcl_DecrRefCount(pDb->pCollateNeeded);
  1780. }
  1781. pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
  1782. Tcl_IncrRefCount(pDb->pCollateNeeded);
  1783. sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
  1784. break;
  1785. }
  1786. /* $db commit_hook ?CALLBACK?
  1787. **
  1788. ** Invoke the given callback just before committing every SQL transaction.
  1789. ** If the callback throws an exception or returns non-zero, then the
  1790. ** transaction is aborted. If CALLBACK is an empty string, the callback
  1791. ** is disabled.
  1792. */
  1793. case DB_COMMIT_HOOK: {
  1794. if( objc>3 ){
  1795. Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
  1796. return TCL_ERROR;
  1797. }else if( objc==2 ){
  1798. if( pDb->zCommit ){
  1799. Tcl_AppendResult(interp, pDb->zCommit, 0);
  1800. }
  1801. }else{
  1802. char *zCommit;
  1803. int len;
  1804. if( pDb->zCommit ){
  1805. Tcl_Free(pDb->zCommit);
  1806. }
  1807. zCommit = Tcl_GetStringFromObj(objv[2], &len);
  1808. if( zCommit && len>0 ){
  1809. pDb->zCommit = Tcl_Alloc( len + 1 );
  1810. memcpy(pDb->zCommit, zCommit, len+1);
  1811. }else{
  1812. pDb->zCommit = 0;
  1813. }
  1814. if( pDb->zCommit ){
  1815. pDb->interp = interp;
  1816. sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
  1817. }else{
  1818. sqlite3_commit_hook(pDb->db, 0, 0);
  1819. }
  1820. }
  1821. break;
  1822. }
  1823. /* $db complete SQL
  1824. **
  1825. ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
  1826. ** additional lines of input are needed. This is similar to the
  1827. ** built-in "info complete" command of Tcl.
  1828. */
  1829. case DB_COMPLETE: {
  1830. #ifndef SQLITE_OMIT_COMPLETE
  1831. Tcl_Obj *pResult;
  1832. int isComplete;
  1833. if( objc!=3 ){
  1834. Tcl_WrongNumArgs(interp, 2, objv, "SQL");
  1835. return TCL_ERROR;
  1836. }
  1837. isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
  1838. pResult = Tcl_GetObjResult(interp);
  1839. Tcl_SetBooleanObj(pResult, isComplete);
  1840. #endif
  1841. break;
  1842. }
  1843. /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
  1844. **
  1845. ** Copy data into table from filename, optionally using SEPARATOR
  1846. ** as column separators. If a column contains a null string, or the
  1847. ** value of NULLINDICATOR, a NULL is inserted for the column.
  1848. ** conflict-algorithm is one of the sqlite conflict algorithms:
  1849. ** rollback, abort, fail, ignore, replace
  1850. ** On success, return the number of lines processed, not necessarily same
  1851. ** as 'db changes' due to conflict-algorithm selected.
  1852. **
  1853. ** This code is basically an implementation/enhancement of
  1854. ** the sqlite3 shell.c ".import" command.
  1855. **
  1856. ** This command usage is equivalent to the sqlite2.x COPY statement,
  1857. ** which imports file data into a table using the PostgreSQL COPY file format:
  1858. ** $db copy $conflit_algo $table_name $filename \t \\N
  1859. */
  1860. case DB_COPY: {
  1861. char *zTable; /* Insert data into this table */
  1862. char *zFile; /* The file from which to extract data */
  1863. char *zConflict; /* The conflict algorithm to use */
  1864. sqlite3_stmt *pStmt; /* A statement */
  1865. int nCol; /* Number of columns in the table */
  1866. int nByte; /* Number of bytes in an SQL string */
  1867. int i, j; /* Loop counters */
  1868. int nSep; /* Number of bytes in zSep[] */
  1869. int nNull; /* Number of bytes in zNull[] */
  1870. char *zSql; /* An SQL statement */
  1871. char *zLine; /* A single line of input from the file */
  1872. char **azCol; /* zLine[] broken up into columns */
  1873. char *zCommit; /* How to commit changes */
  1874. FILE *in; /* The input file */
  1875. int lineno = 0; /* Line number of input file */
  1876. char zLineNum[80]; /* Line number print buffer */
  1877. Tcl_Obj *pResult; /* interp result */
  1878. char *zSep;
  1879. char *zNull;
  1880. if( objc<5 || objc>7 ){
  1881. Tcl_WrongNumArgs(interp, 2, objv,
  1882. "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
  1883. return TCL_ERROR;
  1884. }
  1885. if( objc>=6 ){
  1886. zSep = Tcl_GetStringFromObj(objv[5], 0);
  1887. }else{
  1888. zSep = "\t";
  1889. }
  1890. if( objc>=7 ){
  1891. zNull = Tcl_GetStringFromObj(objv[6], 0);
  1892. }else{
  1893. zNull = "";
  1894. }
  1895. zConflict = Tcl_GetStringFromObj(objv[2], 0);
  1896. zTable = Tcl_GetStringFromObj(objv[3], 0);
  1897. zFile = Tcl_GetStringFromObj(objv[4], 0);
  1898. nSep = strlen30(zSep);
  1899. nNull = strlen30(zNull);
  1900. if( nSep==0 ){
  1901. Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
  1902. return TCL_ERROR;
  1903. }
  1904. if(strcmp(zConflict, "rollback") != 0 &&
  1905. strcmp(zConflict, "abort" ) != 0 &&
  1906. strcmp(zConflict, "fail" ) != 0 &&
  1907. strcmp(zConflict, "ignore" ) != 0 &&
  1908. strcmp(zConflict, "replace" ) != 0 ) {
  1909. Tcl_AppendResult(interp, "Error: \"", zConflict,
  1910. "\", conflict-algorithm must be one of: rollback, "
  1911. "abort, fail, ignore, or replace", 0);
  1912. return TCL_ERROR;
  1913. }
  1914. zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
  1915. if( zSql==0 ){
  1916. Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
  1917. return TCL_ERROR;
  1918. }
  1919. nByte = strlen30(zSql);
  1920. rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
  1921. sqlite3_free(zSql);
  1922. if( rc ){
  1923. Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
  1924. nCol = 0;
  1925. }else{
  1926. nCol = sqlite3_column_count(pStmt);
  1927. }
  1928. sqlite3_finalize(pStmt);
  1929. if( nCol==0 ) {
  1930. return TCL_ERROR;
  1931. }
  1932. zSql = malloc( nByte + 50 + nCol*2 );
  1933. if( zSql==0 ) {
  1934. Tcl_AppendResult(interp, "Error: can't malloc()", 0);
  1935. return TCL_ERROR;
  1936. }
  1937. sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
  1938. zConflict, zTable);
  1939. j = strlen30(zSql);
  1940. for(i=1; i<nCol; i++){
  1941. zSql[j++] = ',';
  1942. zSql[j++] = '?';
  1943. }
  1944. zSql[j++] = ')';
  1945. zSql[j] = 0;
  1946. rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
  1947. free(zSql);
  1948. if( rc ){
  1949. Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
  1950. sqlite3_finalize(pStmt);
  1951. return TCL_ERROR;
  1952. }
  1953. in = fopen(zFile, "rb");
  1954. if( in==0 ){
  1955. Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
  1956. sqlite3_finalize(pStmt);
  1957. return TCL_ERROR;
  1958. }
  1959. azCol = malloc( sizeof(azCol[0])*(nCol+1) );
  1960. if( azCol==0 ) {
  1961. Tcl_AppendResult(interp, "Error: can't malloc()", 0);
  1962. fclose(in);
  1963. return TCL_ERROR;
  1964. }
  1965. (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
  1966. zCommit = "COMMIT";
  1967. while( (zLine = local_getline(0, in))!=0 ){
  1968. char *z;
  1969. lineno++;
  1970. azCol[0] = zLine;
  1971. for(i=0, z=zLine; *z; z++){
  1972. if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
  1973. *z = 0;
  1974. i++;
  1975. if( i<nCol ){
  1976. azCol[i] = &z[nSep];
  1977. z += nSep-1;
  1978. }
  1979. }
  1980. }
  1981. if( i+1!=nCol ){
  1982. char *zErr;
  1983. int nErr = strlen30(zFile) + 200;
  1984. zErr = malloc(nErr);
  1985. if( zErr ){
  1986. sqlite3_snprintf(nErr, zErr,
  1987. "Error: %s line %d: expected %d columns of data but found %d",
  1988. zFile, lineno, nCol, i+1);
  1989. Tcl_AppendResult(interp, zErr, 0);
  1990. free(zErr);
  1991. }
  1992. zCommit = "ROLLBACK";
  1993. break;
  1994. }
  1995. for(i=0; i<nCol; i++){
  1996. /* check for null data, if so, bind as null */
  1997. if( (nNull>0 && strcmp(azCol[i], zNull)==0)
  1998. || strlen30(azCol[i])==0
  1999. ){
  2000. sqlite3_bind_null(pStmt, i+1);
  2001. }else{
  2002. sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
  2003. }
  2004. }
  2005. sqlite3_step(pStmt);
  2006. rc = sqlite3_reset(pStmt);
  2007. free(zLine);
  2008. if( rc!=SQLITE_OK ){
  2009. Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
  2010. zCommit = "ROLLBACK";
  2011. break;
  2012. }
  2013. }
  2014. free(azCol);
  2015. fclose(in);
  2016. sqlite3_finalize(pStmt);
  2017. (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
  2018. if( zCommit[0] == 'C' ){
  2019. /* success, set result as number of lines processed */
  2020. pResult = Tcl_GetObjResult(interp);
  2021. Tcl_SetIntObj(pResult, lineno);
  2022. rc = TCL_OK;
  2023. }else{
  2024. /* failure, append lineno where failed */
  2025. sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
  2026. Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
  2027. rc = TCL_ERROR;
  2028. }
  2029. break;
  2030. }
  2031. /*
  2032. ** $db enable_load_extension BOOLEAN
  2033. **
  2034. ** Turn the extension loading feature on or off. It if off by
  2035. ** default.
  2036. */
  2037. case DB_ENABLE_LOAD_EXTENSION: {
  2038. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  2039. int onoff;
  2040. if( objc!=3 ){
  2041. Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
  2042. return TCL_ERROR;
  2043. }
  2044. if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
  2045. return TCL_ERROR;
  2046. }
  2047. sqlite3_enable_load_extension(pDb->db, onoff);
  2048. break;
  2049. #else
  2050. Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
  2051. 0);
  2052. return TCL_ERROR;
  2053. #endif
  2054. }
  2055. /*
  2056. ** $db errorcode
  2057. **
  2058. ** Return the numeric error code that was returned by the most recent
  2059. ** call to sqlite3_exec().
  2060. */
  2061. case DB_ERRORCODE: {
  2062. Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
  2063. break;
  2064. }
  2065. /*
  2066. ** $db exists $sql
  2067. ** $db onecolumn $sql
  2068. **
  2069. ** The onecolumn method is the equivalent of:
  2070. ** lindex [$db eval $sql] 0
  2071. */
  2072. case DB_EXISTS:
  2073. case DB_ONECOLUMN: {
  2074. DbEvalContext sEval;
  2075. if( objc!=3 ){
  2076. Tcl_WrongNumArgs(interp, 2, objv, "SQL");
  2077. return TCL_ERROR;
  2078. }
  2079. dbEvalInit(&sEval, pDb, objv[2], 0);
  2080. rc = dbEvalStep(&sEval);
  2081. if( choice==DB_ONECOLUMN ){
  2082. if( rc==TCL_OK ){
  2083. Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
  2084. }else if( rc==TCL_BREAK ){
  2085. Tcl_ResetResult(interp);
  2086. }
  2087. }else if( rc==TCL_BREAK || rc==TCL_OK ){
  2088. Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
  2089. }
  2090. dbEvalFinalize(&sEval);
  2091. if( rc==TCL_BREAK ){
  2092. rc = TCL_OK;
  2093. }
  2094. break;
  2095. }
  2096. /*
  2097. ** $db eval $sql ?array? ?{ ...code... }?
  2098. **
  2099. ** The SQL statement in $sql is evaluated. For each row, the values are
  2100. ** placed in elements of the array named "array" and ...code... is executed.
  2101. ** If "array" and "code" are omitted, then no callback is every invoked.
  2102. ** If "array" is an empty string, then the values are placed in variables
  2103. ** that have the same name as the fields extracted by the query.
  2104. */
  2105. case DB_EVAL: {
  2106. if( objc<3 || objc>5 ){
  2107. Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
  2108. return TCL_ERROR;
  2109. }
  2110. if( objc==3 ){
  2111. DbEvalContext sEval;
  2112. Tcl_Obj *pRet = Tcl_NewObj();
  2113. Tcl_IncrRefCount(pRet);
  2114. dbEvalInit(&sEval, pDb, objv[2], 0);
  2115. while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
  2116. int i;
  2117. int nCol;
  2118. dbEvalRowInfo(&sEval, &nCol, 0);
  2119. for(i=0; i<nCol; i++){
  2120. Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
  2121. }
  2122. }
  2123. dbEvalFinalize(&sEval);
  2124. if( rc==TCL_BREAK ){
  2125. Tcl_SetObjResult(interp, pRet);
  2126. rc = TCL_OK;
  2127. }
  2128. Tcl_DecrRefCount(pRet);
  2129. }else{
  2130. ClientData cd[2];
  2131. DbEvalContext *p;
  2132. Tcl_Obj *pArray = 0;
  2133. Tcl_Obj *pScript;
  2134. if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
  2135. pArray = objv[3];
  2136. }
  2137. pScript = objv[objc-1];
  2138. Tcl_IncrRefCount(pScript);
  2139. p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
  2140. dbEvalInit(p, pDb, objv[2], pArray);
  2141. cd[0] = (void *)p;
  2142. cd[1] = (void *)pScript;
  2143. rc = DbEvalNextCmd(cd, interp, TCL_OK);
  2144. }
  2145. break;
  2146. }
  2147. /*
  2148. ** $db function NAME [-argcount N] SCRIPT
  2149. **
  2150. ** Create a new SQL function called NAME. Whenever that function is
  2151. ** called, invoke SCRIPT to evaluate the function.
  2152. */
  2153. case DB_FUNCTION: {
  2154. SqlFunc *pFunc;
  2155. Tcl_Obj *pScript;
  2156. char *zName;
  2157. int nArg = -1;
  2158. if( objc==6 ){
  2159. const char *z = Tcl_GetString(objv[3]);
  2160. int n = strlen30(z);
  2161. if( n>2 && strncmp(z, "-argcount",n)==0 ){
  2162. if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
  2163. if( nArg<0 ){
  2164. Tcl_AppendResult(interp, "number of arguments must be non-negative",
  2165. (char*)0);
  2166. return TCL_ERROR;
  2167. }
  2168. }
  2169. pScript = objv[5];
  2170. }else if( objc!=4 ){
  2171. Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
  2172. return TCL_ERROR;
  2173. }else{
  2174. pScript = objv[3];
  2175. }
  2176. zName = Tcl_GetStringFromObj(objv[2], 0);
  2177. pFunc = findSqlFunc(pDb, zName);
  2178. if( pFunc==0 ) return TCL_ERROR;
  2179. if( pFunc->pScript ){
  2180. Tcl_DecrRefCount(pFunc->pScript);
  2181. }
  2182. pFunc->pScript = pScript;
  2183. Tcl_IncrRefCount(pScript);
  2184. pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
  2185. rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
  2186. pFunc, tclSqlFunc, 0, 0);
  2187. if( rc!=SQLITE_OK ){
  2188. rc = TCL_ERROR;
  2189. Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
  2190. }
  2191. break;
  2192. }
  2193. /*
  2194. ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
  2195. */
  2196. case DB_INCRBLOB: {
  2197. #ifdef SQLITE_OMIT_INCRBLOB
  2198. Tcl_AppendResult(interp, "incrblob not available in this build", 0);
  2199. return TCL_ERROR;
  2200. #else
  2201. int isReadonly = 0;
  2202. const char *zDb = "main";
  2203. const char *zTable;
  2204. const char *zColumn;
  2205. Tcl_WideInt iRow;
  2206. /* Check for the -readonly option */
  2207. if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
  2208. isReadonly = 1;
  2209. }
  2210. if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
  2211. Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
  2212. return TCL_ERROR;
  2213. }
  2214. if( objc==(6+isReadonly) ){
  2215. zDb = Tcl_GetString(objv[2]);
  2216. }
  2217. zTable = Tcl_GetString(objv[objc-3]);
  2218. zColumn = Tcl_GetString(objv[objc-2]);
  2219. rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
  2220. if( rc==TCL_OK ){
  2221. rc = createIncrblobChannel(
  2222. interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
  2223. );
  2224. }
  2225. #endif
  2226. break;
  2227. }
  2228. /*
  2229. ** $db interrupt
  2230. **
  2231. ** Interrupt the execution of the inner-most SQL interpreter. This
  2232. ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
  2233. */
  2234. case DB_INTERRUPT: {
  2235. sqlite3_interrupt(pDb->db);
  2236. break;
  2237. }
  2238. /*
  2239. ** $db nullvalue ?STRING?
  2240. **
  2241. ** Change text used when a NULL comes back from the database. If ?STRING?
  2242. ** is not present, then the current string used for NULL is returned.
  2243. ** If STRING is present, then STRING is returned.
  2244. **
  2245. */
  2246. case DB_NULLVALUE: {
  2247. if( objc!=2 && objc!=3 ){
  2248. Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
  2249. return TCL_ERROR;
  2250. }
  2251. if( objc==3 ){
  2252. int len;
  2253. char *zNull = Tcl_GetStringFromObj(objv[2], &len);
  2254. if( pDb->zNull ){
  2255. Tcl_Free(pDb->zNull);
  2256. }
  2257. if( zNull && len>0 ){
  2258. pDb->zNull = Tcl_Alloc( len + 1 );
  2259. memcpy(pDb->zNull, zNull, len);
  2260. pDb->zNull[len] = '\0';
  2261. }else{
  2262. pDb->zNull = 0;
  2263. }
  2264. }
  2265. Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
  2266. break;
  2267. }
  2268. /*
  2269. ** $db last_insert_rowid
  2270. **
  2271. ** Return an integer which is the ROWID for the most recent insert.
  2272. */
  2273. case DB_LAST_INSERT_ROWID: {
  2274. Tcl_Obj *pResult;
  2275. Tcl_WideInt rowid;
  2276. if( objc!=2 ){
  2277. Tcl_WrongNumArgs(interp, 2, objv, "");
  2278. return TCL_ERROR;
  2279. }
  2280. rowid = sqlite3_last_insert_rowid(pDb->db);
  2281. pResult = Tcl_GetObjResult(interp);
  2282. Tcl_SetWideIntObj(pResult, rowid);
  2283. break;
  2284. }
  2285. /*
  2286. ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
  2287. */
  2288. /* $db progress ?N CALLBACK?
  2289. **
  2290. ** Invoke the given callback every N virtual machine opcodes while executing
  2291. ** queries.
  2292. */
  2293. case DB_PROGRESS: {
  2294. if( objc==2 ){
  2295. if( pDb->zProgress ){
  2296. Tcl_AppendResult(interp, pDb->zProgress, 0);
  2297. }
  2298. }else if( objc==4 ){
  2299. char *zProgress;
  2300. int len;
  2301. int N;
  2302. if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
  2303. return TCL_ERROR;
  2304. };
  2305. if( pDb->zProgress ){
  2306. Tcl_Free(pDb->zProgress);
  2307. }
  2308. zProgress = Tcl_GetStringFromObj(objv[3], &len);
  2309. if( zProgress && len>0 ){
  2310. pDb->zProgress = Tcl_Alloc( len + 1 );
  2311. memcpy(pDb->zProgress, zProgress, len+1);
  2312. }else{
  2313. pDb->zProgress = 0;
  2314. }
  2315. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  2316. if( pDb->zProgress ){
  2317. pDb->interp = interp;
  2318. sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
  2319. }else{
  2320. sqlite3_progress_handler(pDb->db, 0, 0, 0);
  2321. }
  2322. #endif
  2323. }else{
  2324. Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
  2325. return TCL_ERROR;
  2326. }
  2327. break;
  2328. }
  2329. /* $db profile ?CALLBACK?
  2330. **
  2331. ** Make arrangements to invoke the CALLBACK routine after each SQL statement
  2332. ** that has run. The text of the SQL and the amount of elapse time are
  2333. ** appended to CALLBACK before the script is run.
  2334. */
  2335. case DB_PROFILE: {
  2336. if( objc>3 ){
  2337. Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
  2338. return TCL_ERROR;
  2339. }else if( objc==2 ){
  2340. if( pDb->zProfile ){
  2341. Tcl_AppendResult(interp, pDb->zProfile, 0);
  2342. }
  2343. }else{
  2344. char *zProfile;
  2345. int len;
  2346. if( pDb->zProfile ){
  2347. Tcl_Free(pDb->zProfile);
  2348. }
  2349. zProfile = Tcl_GetStringFromObj(objv[2], &len);
  2350. if( zProfile && len>0 ){
  2351. pDb->zProfile = Tcl_Alloc( len + 1 );
  2352. memcpy(pDb->zProfile, zProfile, len+1);
  2353. }else{
  2354. pDb->zProfile = 0;
  2355. }
  2356. #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
  2357. if( pDb->zProfile ){
  2358. pDb->interp = interp;
  2359. sqlite3_profile(pDb->db, DbProfileHandler, pDb);
  2360. }else{
  2361. sqlite3_profile(pDb->db, 0, 0);
  2362. }
  2363. #endif
  2364. }
  2365. break;
  2366. }
  2367. /*
  2368. ** $db rekey KEY
  2369. **
  2370. ** Change the encryption key on the currently open database.
  2371. */
  2372. case DB_REKEY: {
  2373. #ifdef SQLITE_HAS_CODEC
  2374. int nKey;
  2375. void *pKey;
  2376. #endif
  2377. if( objc!=3 ){
  2378. Tcl_WrongNumArgs(interp, 2, objv, "KEY");
  2379. return TCL_ERROR;
  2380. }
  2381. #ifdef SQLITE_HAS_CODEC
  2382. pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
  2383. rc = sqlite3_rekey(pDb->db, pKey, nKey);
  2384. if( rc ){
  2385. Tcl_AppendResult(interp, sqlite3_errstr(rc), 0);
  2386. rc = TCL_ERROR;
  2387. }
  2388. #endif
  2389. break;
  2390. }
  2391. /* $db restore ?DATABASE? FILENAME
  2392. **
  2393. ** Open a database file named FILENAME. Transfer the content
  2394. ** of FILENAME into the local database DATABASE (default: "main").
  2395. */
  2396. case DB_RESTORE: {
  2397. const char *zSrcFile;
  2398. const char *zDestDb;
  2399. sqlite3 *pSrc;
  2400. sqlite3_backup *pBackup;
  2401. int nTimeout = 0;
  2402. if( objc==3 ){
  2403. zDestDb = "main";
  2404. zSrcFile = Tcl_GetString(objv[2]);
  2405. }else if( objc==4 ){
  2406. zDestDb = Tcl_GetString(objv[2]);
  2407. zSrcFile = Tcl_GetString(objv[3]);
  2408. }else{
  2409. Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
  2410. return TCL_ERROR;
  2411. }
  2412. rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
  2413. if( rc!=SQLITE_OK ){
  2414. Tcl_AppendResult(interp, "cannot open source database: ",
  2415. sqlite3_errmsg(pSrc), (char*)0);
  2416. sqlite3_close(pSrc);
  2417. return TCL_ERROR;
  2418. }
  2419. pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
  2420. if( pBackup==0 ){
  2421. Tcl_AppendResult(interp, "restore failed: ",
  2422. sqlite3_errmsg(pDb->db), (char*)0);
  2423. sqlite3_close(pSrc);
  2424. return TCL_ERROR;
  2425. }
  2426. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  2427. || rc==SQLITE_BUSY ){
  2428. if( rc==SQLITE_BUSY ){
  2429. if( nTimeout++ >= 3 ) break;
  2430. sqlite3_sleep(100);
  2431. }
  2432. }
  2433. sqlite3_backup_finish(pBackup);
  2434. if( rc==SQLITE_DONE ){
  2435. rc = TCL_OK;
  2436. }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  2437. Tcl_AppendResult(interp, "restore failed: source database busy",
  2438. (char*)0);
  2439. rc = TCL_ERROR;
  2440. }else{
  2441. Tcl_AppendResult(interp, "restore failed: ",
  2442. sqlite3_errmsg(pDb->db), (char*)0);
  2443. rc = TCL_ERROR;
  2444. }
  2445. sqlite3_close(pSrc);
  2446. break;
  2447. }
  2448. /*
  2449. ** $db status (step|sort|autoindex)
  2450. **
  2451. ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
  2452. ** SQLITE_STMTSTATUS_SORT for the most recent eval.
  2453. */
  2454. case DB_STATUS: {
  2455. int v;
  2456. const char *zOp;
  2457. if( objc!=3 ){
  2458. Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
  2459. return TCL_ERROR;
  2460. }
  2461. zOp = Tcl_GetString(objv[2]);
  2462. if( strcmp(zOp, "step")==0 ){
  2463. v = pDb->nStep;
  2464. }else if( strcmp(zOp, "sort")==0 ){
  2465. v = pDb->nSort;
  2466. }else if( strcmp(zOp, "autoindex")==0 ){
  2467. v = pDb->nIndex;
  2468. }else{
  2469. Tcl_AppendResult(interp,
  2470. "bad argument: should be autoindex, step, or sort",
  2471. (char*)0);
  2472. return TCL_ERROR;
  2473. }
  2474. Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
  2475. break;
  2476. }
  2477. /*
  2478. ** $db timeout MILLESECONDS
  2479. **
  2480. ** Delay for the number of milliseconds specified when a file is locked.
  2481. */
  2482. case DB_TIMEOUT: {
  2483. int ms;
  2484. if( objc!=3 ){
  2485. Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
  2486. return TCL_ERROR;
  2487. }
  2488. if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
  2489. sqlite3_busy_timeout(pDb->db, ms);
  2490. break;
  2491. }
  2492. /*
  2493. ** $db total_changes
  2494. **
  2495. ** Return the number of rows that were modified, inserted, or deleted
  2496. ** since the database handle was created.
  2497. */
  2498. case DB_TOTAL_CHANGES: {
  2499. Tcl_Obj *pResult;
  2500. if( objc!=2 ){
  2501. Tcl_WrongNumArgs(interp, 2, objv, "");
  2502. return TCL_ERROR;
  2503. }
  2504. pResult = Tcl_GetObjResult(interp);
  2505. Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
  2506. break;
  2507. }
  2508. /* $db trace ?CALLBACK?
  2509. **
  2510. ** Make arrangements to invoke the CALLBACK routine for each SQL statement
  2511. ** that is executed. The text of the SQL is appended to CALLBACK before
  2512. ** it is executed.
  2513. */
  2514. case DB_TRACE: {
  2515. if( objc>3 ){
  2516. Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
  2517. return TCL_ERROR;
  2518. }else if( objc==2 ){
  2519. if( pDb->zTrace ){
  2520. Tcl_AppendResult(interp, pDb->zTrace, 0);
  2521. }
  2522. }else{
  2523. char *zTrace;
  2524. int len;
  2525. if( pDb->zTrace ){
  2526. Tcl_Free(pDb->zTrace);
  2527. }
  2528. zTrace = Tcl_GetStringFromObj(objv[2], &len);
  2529. if( zTrace && len>0 ){
  2530. pDb->zTrace = Tcl_Alloc( len + 1 );
  2531. memcpy(pDb->zTrace, zTrace, len+1);
  2532. }else{
  2533. pDb->zTrace = 0;
  2534. }
  2535. #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
  2536. if( pDb->zTrace ){
  2537. pDb->interp = interp;
  2538. sqlite3_trace(pDb->db, DbTraceHandler, pDb);
  2539. }else{
  2540. sqlite3_trace(pDb->db, 0, 0);
  2541. }
  2542. #endif
  2543. }
  2544. break;
  2545. }
  2546. /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
  2547. **
  2548. ** Start a new transaction (if we are not already in the midst of a
  2549. ** transaction) and execute the TCL script SCRIPT. After SCRIPT
  2550. ** completes, either commit the transaction or roll it back if SCRIPT
  2551. ** throws an exception. Or if no new transation was started, do nothing.
  2552. ** pass the exception on up the stack.
  2553. **
  2554. ** This command was inspired by Dave Thomas's talk on Ruby at the
  2555. ** 2005 O'Reilly Open Source Convention (OSCON).
  2556. */
  2557. case DB_TRANSACTION: {
  2558. Tcl_Obj *pScript;
  2559. const char *zBegin = "SAVEPOINT _tcl_transaction";
  2560. if( objc!=3 && objc!=4 ){
  2561. Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
  2562. return TCL_ERROR;
  2563. }
  2564. if( pDb->nTransaction==0 && objc==4 ){
  2565. static const char *TTYPE_strs[] = {
  2566. "deferred", "exclusive", "immediate", 0
  2567. };
  2568. enum TTYPE_enum {
  2569. TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
  2570. };
  2571. int ttype;
  2572. if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
  2573. 0, &ttype) ){
  2574. return TCL_ERROR;
  2575. }
  2576. switch( (enum TTYPE_enum)ttype ){
  2577. case TTYPE_DEFERRED: /* no-op */; break;
  2578. case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
  2579. case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
  2580. }
  2581. }
  2582. pScript = objv[objc-1];
  2583. /* Run the SQLite BEGIN command to open a transaction or savepoint. */
  2584. pDb->disableAuth++;
  2585. rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
  2586. pDb->disableAuth--;
  2587. if( rc!=SQLITE_OK ){
  2588. Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
  2589. return TCL_ERROR;
  2590. }
  2591. pDb->nTransaction++;
  2592. /* If using NRE, schedule a callback to invoke the script pScript, then
  2593. ** a second callback to commit (or rollback) the transaction or savepoint
  2594. ** opened above. If not using NRE, evaluate the script directly, then
  2595. ** call function DbTransPostCmd() to commit (or rollback) the transaction
  2596. ** or savepoint. */
  2597. if( DbUseNre() ){
  2598. Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
  2599. Tcl_NREvalObj(interp, pScript, 0);
  2600. }else{
  2601. rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
  2602. }
  2603. break;
  2604. }
  2605. /*
  2606. ** $db unlock_notify ?script?
  2607. */
  2608. case DB_UNLOCK_NOTIFY: {
  2609. #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
  2610. Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
  2611. rc = TCL_ERROR;
  2612. #else
  2613. if( objc!=2 && objc!=3 ){
  2614. Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
  2615. rc = TCL_ERROR;
  2616. }else{
  2617. void (*xNotify)(void **, int) = 0;
  2618. void *pNotifyArg = 0;
  2619. if( pDb->pUnlockNotify ){
  2620. Tcl_DecrRefCount(pDb->pUnlockNotify);
  2621. pDb->pUnlockNotify = 0;
  2622. }
  2623. if( objc==3 ){
  2624. xNotify = DbUnlockNotify;
  2625. pNotifyArg = (void *)pDb;
  2626. pDb->pUnlockNotify = objv[2];
  2627. Tcl_IncrRefCount(pDb->pUnlockNotify);
  2628. }
  2629. if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
  2630. Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
  2631. rc = TCL_ERROR;
  2632. }
  2633. }
  2634. #endif
  2635. break;
  2636. }
  2637. /*
  2638. ** $db wal_hook ?script?
  2639. ** $db update_hook ?script?
  2640. ** $db rollback_hook ?script?
  2641. */
  2642. case DB_WAL_HOOK:
  2643. case DB_UPDATE_HOOK:
  2644. case DB_ROLLBACK_HOOK: {
  2645. /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
  2646. ** whether [$db update_hook] or [$db rollback_hook] was invoked.
  2647. */
  2648. Tcl_Obj **ppHook;
  2649. if( choice==DB_UPDATE_HOOK ){
  2650. ppHook = &pDb->pUpdateHook;
  2651. }else if( choice==DB_WAL_HOOK ){
  2652. ppHook = &pDb->pWalHook;
  2653. }else{
  2654. ppHook = &pDb->pRollbackHook;
  2655. }
  2656. if( objc!=2 && objc!=3 ){
  2657. Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
  2658. return TCL_ERROR;
  2659. }
  2660. if( *ppHook ){
  2661. Tcl_SetObjResult(interp, *ppHook);
  2662. if( objc==3 ){
  2663. Tcl_DecrRefCount(*ppHook);
  2664. *ppHook = 0;
  2665. }
  2666. }
  2667. if( objc==3 ){
  2668. assert( !(*ppHook) );
  2669. if( Tcl_GetCharLength(objv[2])>0 ){
  2670. *ppHook = objv[2];
  2671. Tcl_IncrRefCount(*ppHook);
  2672. }
  2673. }
  2674. sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
  2675. sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
  2676. sqlite3_wal_hook(pDb->db,(pDb->pWalHook?DbWalHandler:0),pDb);
  2677. break;
  2678. }
  2679. /* $db version
  2680. **
  2681. ** Return the version string for this database.
  2682. */
  2683. case DB_VERSION: {
  2684. Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
  2685. break;
  2686. }
  2687. } /* End of the SWITCH statement */
  2688. return rc;
  2689. }
  2690. #if SQLITE_TCL_NRE
  2691. /*
  2692. ** Adaptor that provides an objCmd interface to the NRE-enabled
  2693. ** interface implementation.
  2694. */
  2695. static int DbObjCmdAdaptor(
  2696. void *cd,
  2697. Tcl_Interp *interp,
  2698. int objc,
  2699. Tcl_Obj *const*objv
  2700. ){
  2701. return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
  2702. }
  2703. #endif /* SQLITE_TCL_NRE */
  2704. /*
  2705. ** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
  2706. ** ?-create BOOLEAN? ?-nomutex BOOLEAN?
  2707. **
  2708. ** This is the main Tcl command. When the "sqlite" Tcl command is
  2709. ** invoked, this routine runs to process that command.
  2710. **
  2711. ** The first argument, DBNAME, is an arbitrary name for a new
  2712. ** database connection. This command creates a new command named
  2713. ** DBNAME that is used to control that connection. The database
  2714. ** connection is deleted when the DBNAME command is deleted.
  2715. **
  2716. ** The second argument is the name of the database file.
  2717. **
  2718. */
  2719. static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
  2720. SqliteDb *p;
  2721. const char *zArg;
  2722. char *zErrMsg;
  2723. int i;
  2724. const char *zFile;
  2725. const char *zVfs = 0;
  2726. int flags;
  2727. Tcl_DString translatedFilename;
  2728. #ifdef SQLITE_HAS_CODEC
  2729. void *pKey = 0;
  2730. int nKey = 0;
  2731. #endif
  2732. int rc;
  2733. /* In normal use, each TCL interpreter runs in a single thread. So
  2734. ** by default, we can turn of mutexing on SQLite database connections.
  2735. ** However, for testing purposes it is useful to have mutexes turned
  2736. ** on. So, by default, mutexes default off. But if compiled with
  2737. ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
  2738. */
  2739. #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
  2740. flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
  2741. #else
  2742. flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
  2743. #endif
  2744. if( objc==2 ){
  2745. zArg = Tcl_GetStringFromObj(objv[1], 0);
  2746. if( strcmp(zArg,"-version")==0 ){
  2747. Tcl_AppendResult(interp,sqlite3_version,0);
  2748. return TCL_OK;
  2749. }
  2750. if( strcmp(zArg,"-has-codec")==0 ){
  2751. #ifdef SQLITE_HAS_CODEC
  2752. Tcl_AppendResult(interp,"1",0);
  2753. #else
  2754. Tcl_AppendResult(interp,"0",0);
  2755. #endif
  2756. return TCL_OK;
  2757. }
  2758. }
  2759. for(i=3; i+1<objc; i+=2){
  2760. zArg = Tcl_GetString(objv[i]);
  2761. if( strcmp(zArg,"-key")==0 ){
  2762. #ifdef SQLITE_HAS_CODEC
  2763. pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
  2764. #endif
  2765. }else if( strcmp(zArg, "-vfs")==0 ){
  2766. zVfs = Tcl_GetString(objv[i+1]);
  2767. }else if( strcmp(zArg, "-readonly")==0 ){
  2768. int b;
  2769. if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
  2770. if( b ){
  2771. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  2772. flags |= SQLITE_OPEN_READONLY;
  2773. }else{
  2774. flags &= ~SQLITE_OPEN_READONLY;
  2775. flags |= SQLITE_OPEN_READWRITE;
  2776. }
  2777. }else if( strcmp(zArg, "-create")==0 ){
  2778. int b;
  2779. if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
  2780. if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
  2781. flags |= SQLITE_OPEN_CREATE;
  2782. }else{
  2783. flags &= ~SQLITE_OPEN_CREATE;
  2784. }
  2785. }else if( strcmp(zArg, "-nomutex")==0 ){
  2786. int b;
  2787. if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
  2788. if( b ){
  2789. flags |= SQLITE_OPEN_NOMUTEX;
  2790. flags &= ~SQLITE_OPEN_FULLMUTEX;
  2791. }else{
  2792. flags &= ~SQLITE_OPEN_NOMUTEX;
  2793. }
  2794. }else if( strcmp(zArg, "-fullmutex")==0 ){
  2795. int b;
  2796. if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
  2797. if( b ){
  2798. flags |= SQLITE_OPEN_FULLMUTEX;
  2799. flags &= ~SQLITE_OPEN_NOMUTEX;
  2800. }else{
  2801. flags &= ~SQLITE_OPEN_FULLMUTEX;
  2802. }
  2803. }else if( strcmp(zArg, "-uri")==0 ){
  2804. int b;
  2805. if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
  2806. if( b ){
  2807. flags |= SQLITE_OPEN_URI;
  2808. }else{
  2809. flags &= ~SQLITE_OPEN_URI;
  2810. }
  2811. }else{
  2812. Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
  2813. return TCL_ERROR;
  2814. }
  2815. }
  2816. if( objc<3 || (objc&1)!=1 ){
  2817. Tcl_WrongNumArgs(interp, 1, objv,
  2818. "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
  2819. " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
  2820. #ifdef SQLITE_HAS_CODEC
  2821. " ?-key CODECKEY?"
  2822. #endif
  2823. );
  2824. return TCL_ERROR;
  2825. }
  2826. zErrMsg = 0;
  2827. p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
  2828. if( p==0 ){
  2829. Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
  2830. return TCL_ERROR;
  2831. }
  2832. memset(p, 0, sizeof(*p));
  2833. zFile = Tcl_GetStringFromObj(objv[2], 0);
  2834. zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
  2835. rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
  2836. Tcl_DStringFree(&translatedFilename);
  2837. if( p->db ){
  2838. if( SQLITE_OK!=sqlite3_errcode(p->db) ){
  2839. zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
  2840. sqlite3_close(p->db);
  2841. p->db = 0;
  2842. }
  2843. }else{
  2844. zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
  2845. }
  2846. #ifdef SQLITE_HAS_CODEC
  2847. if( p->db ){
  2848. sqlite3_key(p->db, pKey, nKey);
  2849. }
  2850. #endif
  2851. if( p->db==0 ){
  2852. Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
  2853. Tcl_Free((char*)p);
  2854. sqlite3_free(zErrMsg);
  2855. return TCL_ERROR;
  2856. }
  2857. p->maxStmt = NUM_PREPARED_STMTS;
  2858. p->interp = interp;
  2859. zArg = Tcl_GetStringFromObj(objv[1], 0);
  2860. if( DbUseNre() ){
  2861. Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
  2862. (char*)p, DbDeleteCmd);
  2863. }else{
  2864. Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
  2865. }
  2866. return TCL_OK;
  2867. }
  2868. /*
  2869. ** Provide a dummy Tcl_InitStubs if we are using this as a static
  2870. ** library.
  2871. */
  2872. #ifndef USE_TCL_STUBS
  2873. # undef Tcl_InitStubs
  2874. # define Tcl_InitStubs(a,b,c) TCL_VERSION
  2875. #endif
  2876. /*
  2877. ** Make sure we have a PACKAGE_VERSION macro defined. This will be
  2878. ** defined automatically by the TEA makefile. But other makefiles
  2879. ** do not define it.
  2880. */
  2881. #ifndef PACKAGE_VERSION
  2882. # define PACKAGE_VERSION SQLITE_VERSION
  2883. #endif
  2884. /*
  2885. ** Initialize this module.
  2886. **
  2887. ** This Tcl module contains only a single new Tcl command named "sqlite".
  2888. ** (Hence there is no namespace. There is no point in using a namespace
  2889. ** if the extension only supplies one new name!) The "sqlite" command is
  2890. ** used to open a new SQLite database. See the DbMain() routine above
  2891. ** for additional information.
  2892. **
  2893. ** The EXTERN macros are required by TCL in order to work on windows.
  2894. */
  2895. EXTERN int Sqlite3_Init(Tcl_Interp *interp){
  2896. int rc = Tcl_InitStubs(interp, "8.4", 0)==0 ? TCL_ERROR : TCL_OK;
  2897. if( rc==TCL_OK ){
  2898. Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
  2899. #ifndef SQLITE_3_SUFFIX_ONLY
  2900. /* The "sqlite" alias is undocumented. It is here only to support
  2901. ** legacy scripts. All new scripts should use only the "sqlite3"
  2902. ** command. */
  2903. Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
  2904. #endif
  2905. rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
  2906. }
  2907. return rc;
  2908. }
  2909. EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
  2910. EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
  2911. EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
  2912. /* Because it accesses the file-system and uses persistent state, SQLite
  2913. ** is not considered appropriate for safe interpreters. Hence, we deliberately
  2914. ** omit the _SafeInit() interfaces.
  2915. */
  2916. #ifndef SQLITE_3_SUFFIX_ONLY
  2917. int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
  2918. int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
  2919. int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
  2920. int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
  2921. #endif
  2922. #ifdef TCLSH
  2923. /*****************************************************************************
  2924. ** All of the code that follows is used to build standalone TCL interpreters
  2925. ** that are statically linked with SQLite. Enable these by compiling
  2926. ** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
  2927. ** tclsh but with SQLite built in. An n of 2 generates the SQLite space
  2928. ** analysis program.
  2929. */
  2930. #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
  2931. /*
  2932. * This code implements the MD5 message-digest algorithm.
  2933. * The algorithm is due to Ron Rivest. This code was
  2934. * written by Colin Plumb in 1993, no copyright is claimed.
  2935. * This code is in the public domain; do with it what you wish.
  2936. *
  2937. * Equivalent code is available from RSA Data Security, Inc.
  2938. * This code has been tested against that, and is equivalent,
  2939. * except that you don't need to include two pages of legalese
  2940. * with every copy.
  2941. *
  2942. * To compute the message digest of a chunk of bytes, declare an
  2943. * MD5Context structure, pass it to MD5Init, call MD5Update as
  2944. * needed on buffers full of bytes, and then call MD5Final, which
  2945. * will fill a supplied 16-byte array with the digest.
  2946. */
  2947. /*
  2948. * If compiled on a machine that doesn't have a 32-bit integer,
  2949. * you just set "uint32" to the appropriate datatype for an
  2950. * unsigned 32-bit integer. For example:
  2951. *
  2952. * cc -Duint32='unsigned long' md5.c
  2953. *
  2954. */
  2955. #ifndef uint32
  2956. # define uint32 unsigned int
  2957. #endif
  2958. struct MD5Context {
  2959. int isInit;
  2960. uint32 buf[4];
  2961. uint32 bits[2];
  2962. unsigned char in[64];
  2963. };
  2964. typedef struct MD5Context MD5Context;
  2965. /*
  2966. * Note: this code is harmless on little-endian machines.
  2967. */
  2968. static void byteReverse (unsigned char *buf, unsigned longs){
  2969. uint32 t;
  2970. do {
  2971. t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
  2972. ((unsigned)buf[1]<<8 | buf[0]);
  2973. *(uint32 *)buf = t;
  2974. buf += 4;
  2975. } while (--longs);
  2976. }
  2977. /* The four core functions - F1 is optimized somewhat */
  2978. /* #define F1(x, y, z) (x & y | ~x & z) */
  2979. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  2980. #define F2(x, y, z) F1(z, x, y)
  2981. #define F3(x, y, z) (x ^ y ^ z)
  2982. #define F4(x, y, z) (y ^ (x | ~z))
  2983. /* This is the central step in the MD5 algorithm. */
  2984. #define MD5STEP(f, w, x, y, z, data, s) \
  2985. ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
  2986. /*
  2987. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  2988. * reflect the addition of 16 longwords of new data. MD5Update blocks
  2989. * the data and converts bytes into longwords for this routine.
  2990. */
  2991. static void MD5Transform(uint32 buf[4], const uint32 in[16]){
  2992. register uint32 a, b, c, d;
  2993. a = buf[0];
  2994. b = buf[1];
  2995. c = buf[2];
  2996. d = buf[3];
  2997. MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
  2998. MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
  2999. MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
  3000. MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
  3001. MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
  3002. MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
  3003. MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
  3004. MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
  3005. MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
  3006. MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
  3007. MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
  3008. MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
  3009. MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
  3010. MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
  3011. MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
  3012. MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
  3013. MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
  3014. MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
  3015. MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
  3016. MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
  3017. MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
  3018. MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
  3019. MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
  3020. MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
  3021. MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
  3022. MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
  3023. MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
  3024. MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
  3025. MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
  3026. MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
  3027. MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
  3028. MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
  3029. MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
  3030. MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
  3031. MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
  3032. MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
  3033. MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
  3034. MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
  3035. MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
  3036. MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
  3037. MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
  3038. MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
  3039. MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
  3040. MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
  3041. MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
  3042. MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
  3043. MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
  3044. MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
  3045. MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
  3046. MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
  3047. MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
  3048. MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
  3049. MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
  3050. MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
  3051. MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
  3052. MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
  3053. MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
  3054. MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
  3055. MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
  3056. MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
  3057. MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
  3058. MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
  3059. MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
  3060. MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
  3061. buf[0] += a;
  3062. buf[1] += b;
  3063. buf[2] += c;
  3064. buf[3] += d;
  3065. }
  3066. /*
  3067. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  3068. * initialization constants.
  3069. */
  3070. static void MD5Init(MD5Context *ctx){
  3071. ctx->isInit = 1;
  3072. ctx->buf[0] = 0x67452301;
  3073. ctx->buf[1] = 0xefcdab89;
  3074. ctx->buf[2] = 0x98badcfe;
  3075. ctx->buf[3] = 0x10325476;
  3076. ctx->bits[0] = 0;
  3077. ctx->bits[1] = 0;
  3078. }
  3079. /*
  3080. * Update context to reflect the concatenation of another buffer full
  3081. * of bytes.
  3082. */
  3083. static
  3084. void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
  3085. uint32 t;
  3086. /* Update bitcount */
  3087. t = ctx->bits[0];
  3088. if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
  3089. ctx->bits[1]++; /* Carry from low to high */
  3090. ctx->bits[1] += len >> 29;
  3091. t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
  3092. /* Handle any leading odd-sized chunks */
  3093. if ( t ) {
  3094. unsigned char *p = (unsigned char *)ctx->in + t;
  3095. t = 64-t;
  3096. if (len < t) {
  3097. memcpy(p, buf, len);
  3098. return;
  3099. }
  3100. memcpy(p, buf, t);
  3101. byteReverse(ctx->in, 16);
  3102. MD5Transform(ctx->buf, (uint32 *)ctx->in);
  3103. buf += t;
  3104. len -= t;
  3105. }
  3106. /* Process data in 64-byte chunks */
  3107. while (len >= 64) {
  3108. memcpy(ctx->in, buf, 64);
  3109. byteReverse(ctx->in, 16);
  3110. MD5Transform(ctx->buf, (uint32 *)ctx->in);
  3111. buf += 64;
  3112. len -= 64;
  3113. }
  3114. /* Handle any remaining bytes of data. */
  3115. memcpy(ctx->in, buf, len);
  3116. }
  3117. /*
  3118. * Final wrapup - pad to 64-byte boundary with the bit pattern
  3119. * 1 0* (64-bit count of bits processed, MSB-first)
  3120. */
  3121. static void MD5Final(unsigned char digest[16], MD5Context *ctx){
  3122. unsigned count;
  3123. unsigned char *p;
  3124. /* Compute number of bytes mod 64 */
  3125. count = (ctx->bits[0] >> 3) & 0x3F;
  3126. /* Set the first char of padding to 0x80. This is safe since there is
  3127. always at least one byte free */
  3128. p = ctx->in + count;
  3129. *p++ = 0x80;
  3130. /* Bytes of padding needed to make 64 bytes */
  3131. count = 64 - 1 - count;
  3132. /* Pad out to 56 mod 64 */
  3133. if (count < 8) {
  3134. /* Two lots of padding: Pad the first block to 64 bytes */
  3135. memset(p, 0, count);
  3136. byteReverse(ctx->in, 16);
  3137. MD5Transform(ctx->buf, (uint32 *)ctx->in);
  3138. /* Now fill the next block with 56 bytes */
  3139. memset(ctx->in, 0, 56);
  3140. } else {
  3141. /* Pad block to 56 bytes */
  3142. memset(p, 0, count-8);
  3143. }
  3144. byteReverse(ctx->in, 14);
  3145. /* Append length in bits and transform */
  3146. ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
  3147. ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];
  3148. MD5Transform(ctx->buf, (uint32 *)ctx->in);
  3149. byteReverse((unsigned char *)ctx->buf, 4);
  3150. memcpy(digest, ctx->buf, 16);
  3151. }
  3152. /*
  3153. ** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
  3154. */
  3155. static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
  3156. static char const zEncode[] = "0123456789abcdef";
  3157. int i, j;
  3158. for(j=i=0; i<16; i++){
  3159. int a = digest[i];
  3160. zBuf[j++] = zEncode[(a>>4)&0xf];
  3161. zBuf[j++] = zEncode[a & 0xf];
  3162. }
  3163. zBuf[j] = 0;
  3164. }
  3165. /*
  3166. ** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
  3167. ** each representing 16 bits of the digest and separated from each
  3168. ** other by a "-" character.
  3169. */
  3170. static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
  3171. int i, j;
  3172. unsigned int x;
  3173. for(i=j=0; i<16; i+=2){
  3174. x = digest[i]*256 + digest[i+1];
  3175. if( i>0 ) zDigest[j++] = '-';
  3176. sprintf(&zDigest[j], "%05u", x);
  3177. j += 5;
  3178. }
  3179. zDigest[j] = 0;
  3180. }
  3181. /*
  3182. ** A TCL command for md5. The argument is the text to be hashed. The
  3183. ** Result is the hash in base64.
  3184. */
  3185. static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
  3186. MD5Context ctx;
  3187. unsigned char digest[16];
  3188. char zBuf[50];
  3189. void (*converter)(unsigned char*, char*);
  3190. if( argc!=2 ){
  3191. Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
  3192. " TEXT\"", 0);
  3193. return TCL_ERROR;
  3194. }
  3195. MD5Init(&ctx);
  3196. MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
  3197. MD5Final(digest, &ctx);
  3198. converter = (void(*)(unsigned char*,char*))cd;
  3199. converter(digest, zBuf);
  3200. Tcl_AppendResult(interp, zBuf, (char*)0);
  3201. return TCL_OK;
  3202. }
  3203. /*
  3204. ** A TCL command to take the md5 hash of a file. The argument is the
  3205. ** name of the file.
  3206. */
  3207. static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
  3208. FILE *in;
  3209. MD5Context ctx;
  3210. void (*converter)(unsigned char*, char*);
  3211. unsigned char digest[16];
  3212. char zBuf[10240];
  3213. if( argc!=2 ){
  3214. Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
  3215. " FILENAME\"", 0);
  3216. return TCL_ERROR;
  3217. }
  3218. in = fopen(argv[1],"rb");
  3219. if( in==0 ){
  3220. Tcl_AppendResult(interp,"unable to open file \"", argv[1],
  3221. "\" for reading", 0);
  3222. return TCL_ERROR;
  3223. }
  3224. MD5Init(&ctx);
  3225. for(;;){
  3226. int n;
  3227. n = (int)fread(zBuf, 1, sizeof(zBuf), in);
  3228. if( n<=0 ) break;
  3229. MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
  3230. }
  3231. fclose(in);
  3232. MD5Final(digest, &ctx);
  3233. converter = (void(*)(unsigned char*,char*))cd;
  3234. converter(digest, zBuf);
  3235. Tcl_AppendResult(interp, zBuf, (char*)0);
  3236. return TCL_OK;
  3237. }
  3238. /*
  3239. ** Register the four new TCL commands for generating MD5 checksums
  3240. ** with the TCL interpreter.
  3241. */
  3242. int Md5_Init(Tcl_Interp *interp){
  3243. Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
  3244. MD5DigestToBase16, 0);
  3245. Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
  3246. MD5DigestToBase10x8, 0);
  3247. Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
  3248. MD5DigestToBase16, 0);
  3249. Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
  3250. MD5DigestToBase10x8, 0);
  3251. return TCL_OK;
  3252. }
  3253. #endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
  3254. #if defined(SQLITE_TEST)
  3255. /*
  3256. ** During testing, the special md5sum() aggregate function is available.
  3257. ** inside SQLite. The following routines implement that function.
  3258. */
  3259. static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
  3260. MD5Context *p;
  3261. int i;
  3262. if( argc<1 ) return;
  3263. p = sqlite3_aggregate_context(context, sizeof(*p));
  3264. if( p==0 ) return;
  3265. if( !p->isInit ){
  3266. MD5Init(p);
  3267. }
  3268. for(i=0; i<argc; i++){
  3269. const char *zData = (char*)sqlite3_value_text(argv[i]);
  3270. if( zData ){
  3271. MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
  3272. }
  3273. }
  3274. }
  3275. static void md5finalize(sqlite3_context *context){
  3276. MD5Context *p;
  3277. unsigned char digest[16];
  3278. char zBuf[33];
  3279. p = sqlite3_aggregate_context(context, sizeof(*p));
  3280. MD5Final(digest,p);
  3281. MD5DigestToBase16(digest, zBuf);
  3282. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  3283. }
  3284. int Md5_Register(sqlite3 *db){
  3285. int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
  3286. md5step, md5finalize);
  3287. sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
  3288. return rc;
  3289. }
  3290. #endif /* defined(SQLITE_TEST) */
  3291. /*
  3292. ** If the macro TCLSH is one, then put in code this for the
  3293. ** "main" routine that will initialize Tcl and take input from
  3294. ** standard input, or if a file is named on the command line
  3295. ** the TCL interpreter reads and evaluates that file.
  3296. */
  3297. #if TCLSH==1
  3298. static const char *tclsh_main_loop(void){
  3299. static const char zMainloop[] =
  3300. "set line {}\n"
  3301. "while {![eof stdin]} {\n"
  3302. "if {$line!=\"\"} {\n"
  3303. "puts -nonewline \"> \"\n"
  3304. "} else {\n"
  3305. "puts -nonewline \"% \"\n"
  3306. "}\n"
  3307. "flush stdout\n"
  3308. "append line [gets stdin]\n"
  3309. "if {[info complete $line]} {\n"
  3310. "if {[catch {uplevel #0 $line} result]} {\n"
  3311. "puts stderr \"Error: $result\"\n"
  3312. "} elseif {$result!=\"\"} {\n"
  3313. "puts $result\n"
  3314. "}\n"
  3315. "set line {}\n"
  3316. "} else {\n"
  3317. "append line \\n\n"
  3318. "}\n"
  3319. "}\n"
  3320. ;
  3321. return zMainloop;
  3322. }
  3323. #endif
  3324. #if TCLSH==2
  3325. static const char *tclsh_main_loop(void);
  3326. #endif
  3327. #ifdef SQLITE_TEST
  3328. static void init_all(Tcl_Interp *);
  3329. static int init_all_cmd(
  3330. ClientData cd,
  3331. Tcl_Interp *interp,
  3332. int objc,
  3333. Tcl_Obj *CONST objv[]
  3334. ){
  3335. Tcl_Interp *slave;
  3336. if( objc!=2 ){
  3337. Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
  3338. return TCL_ERROR;
  3339. }
  3340. slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
  3341. if( !slave ){
  3342. return TCL_ERROR;
  3343. }
  3344. init_all(slave);
  3345. return TCL_OK;
  3346. }
  3347. /*
  3348. ** Tclcmd: db_use_legacy_prepare DB BOOLEAN
  3349. **
  3350. ** The first argument to this command must be a database command created by
  3351. ** [sqlite3]. If the second argument is true, then the handle is configured
  3352. ** to use the sqlite3_prepare_v2() function to prepare statements. If it
  3353. ** is false, sqlite3_prepare().
  3354. */
  3355. static int db_use_legacy_prepare_cmd(
  3356. ClientData cd,
  3357. Tcl_Interp *interp,
  3358. int objc,
  3359. Tcl_Obj *CONST objv[]
  3360. ){
  3361. Tcl_CmdInfo cmdInfo;
  3362. SqliteDb *pDb;
  3363. int bPrepare;
  3364. if( objc!=3 ){
  3365. Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
  3366. return TCL_ERROR;
  3367. }
  3368. if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
  3369. Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
  3370. return TCL_ERROR;
  3371. }
  3372. pDb = (SqliteDb*)cmdInfo.objClientData;
  3373. if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
  3374. return TCL_ERROR;
  3375. }
  3376. pDb->bLegacyPrepare = bPrepare;
  3377. Tcl_ResetResult(interp);
  3378. return TCL_OK;
  3379. }
  3380. #endif
  3381. /*
  3382. ** Configure the interpreter passed as the first argument to have access
  3383. ** to the commands and linked variables that make up:
  3384. **
  3385. ** * the [sqlite3] extension itself,
  3386. **
  3387. ** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
  3388. **
  3389. ** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
  3390. ** test suite.
  3391. */
  3392. static void init_all(Tcl_Interp *interp){
  3393. Sqlite3_Init(interp);
  3394. #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
  3395. Md5_Init(interp);
  3396. #endif
  3397. /* Install the [register_dbstat_vtab] command to access the implementation
  3398. ** of virtual table dbstat (source file test_stat.c). This command is
  3399. ** required for testfixture and sqlite3_analyzer, but not by the production
  3400. ** Tcl extension. */
  3401. #if defined(SQLITE_TEST) || TCLSH==2
  3402. {
  3403. extern int SqlitetestStat_Init(Tcl_Interp*);
  3404. SqlitetestStat_Init(interp);
  3405. }
  3406. #endif
  3407. #ifdef SQLITE_TEST
  3408. {
  3409. extern int Sqliteconfig_Init(Tcl_Interp*);
  3410. extern int Sqlitetest1_Init(Tcl_Interp*);
  3411. extern int Sqlitetest2_Init(Tcl_Interp*);
  3412. extern int Sqlitetest3_Init(Tcl_Interp*);
  3413. extern int Sqlitetest4_Init(Tcl_Interp*);
  3414. extern int Sqlitetest5_Init(Tcl_Interp*);
  3415. extern int Sqlitetest6_Init(Tcl_Interp*);
  3416. extern int Sqlitetest7_Init(Tcl_Interp*);
  3417. extern int Sqlitetest8_Init(Tcl_Interp*);
  3418. extern int Sqlitetest9_Init(Tcl_Interp*);
  3419. extern int Sqlitetestasync_Init(Tcl_Interp*);
  3420. extern int Sqlitetest_autoext_Init(Tcl_Interp*);
  3421. extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
  3422. extern int Sqlitetest_func_Init(Tcl_Interp*);
  3423. extern int Sqlitetest_hexio_Init(Tcl_Interp*);
  3424. extern int Sqlitetest_init_Init(Tcl_Interp*);
  3425. extern int Sqlitetest_malloc_Init(Tcl_Interp*);
  3426. extern int Sqlitetest_mutex_Init(Tcl_Interp*);
  3427. extern int Sqlitetestschema_Init(Tcl_Interp*);
  3428. extern int Sqlitetestsse_Init(Tcl_Interp*);
  3429. extern int Sqlitetesttclvar_Init(Tcl_Interp*);
  3430. extern int Sqlitetestfs_Init(Tcl_Interp*);
  3431. extern int SqlitetestThread_Init(Tcl_Interp*);
  3432. extern int SqlitetestOnefile_Init();
  3433. extern int SqlitetestOsinst_Init(Tcl_Interp*);
  3434. extern int Sqlitetestbackup_Init(Tcl_Interp*);
  3435. extern int Sqlitetestintarray_Init(Tcl_Interp*);
  3436. extern int Sqlitetestvfs_Init(Tcl_Interp *);
  3437. extern int Sqlitetestrtree_Init(Tcl_Interp*);
  3438. extern int Sqlitequota_Init(Tcl_Interp*);
  3439. extern int Sqlitemultiplex_Init(Tcl_Interp*);
  3440. extern int SqliteSuperlock_Init(Tcl_Interp*);
  3441. extern int SqlitetestSyscall_Init(Tcl_Interp*);
  3442. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  3443. extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
  3444. #endif
  3445. #ifdef SQLITE_ENABLE_ZIPVFS
  3446. extern int Zipvfs_Init(Tcl_Interp*);
  3447. Zipvfs_Init(interp);
  3448. #endif
  3449. Sqliteconfig_Init(interp);
  3450. Sqlitetest1_Init(interp);
  3451. Sqlitetest2_Init(interp);
  3452. Sqlitetest3_Init(interp);
  3453. Sqlitetest4_Init(interp);
  3454. Sqlitetest5_Init(interp);
  3455. Sqlitetest6_Init(interp);
  3456. Sqlitetest7_Init(interp);
  3457. Sqlitetest8_Init(interp);
  3458. Sqlitetest9_Init(interp);
  3459. Sqlitetestasync_Init(interp);
  3460. Sqlitetest_autoext_Init(interp);
  3461. Sqlitetest_demovfs_Init(interp);
  3462. Sqlitetest_func_Init(interp);
  3463. Sqlitetest_hexio_Init(interp);
  3464. Sqlitetest_init_Init(interp);
  3465. Sqlitetest_malloc_Init(interp);
  3466. Sqlitetest_mutex_Init(interp);
  3467. Sqlitetestschema_Init(interp);
  3468. Sqlitetesttclvar_Init(interp);
  3469. Sqlitetestfs_Init(interp);
  3470. SqlitetestThread_Init(interp);
  3471. SqlitetestOnefile_Init(interp);
  3472. SqlitetestOsinst_Init(interp);
  3473. Sqlitetestbackup_Init(interp);
  3474. Sqlitetestintarray_Init(interp);
  3475. Sqlitetestvfs_Init(interp);
  3476. Sqlitetestrtree_Init(interp);
  3477. Sqlitequota_Init(interp);
  3478. Sqlitemultiplex_Init(interp);
  3479. SqliteSuperlock_Init(interp);
  3480. SqlitetestSyscall_Init(interp);
  3481. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  3482. Sqlitetestfts3_Init(interp);
  3483. #endif
  3484. Tcl_CreateObjCommand(
  3485. interp, "load_testfixture_extensions", init_all_cmd, 0, 0
  3486. );
  3487. Tcl_CreateObjCommand(
  3488. interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
  3489. );
  3490. #ifdef SQLITE_SSE
  3491. Sqlitetestsse_Init(interp);
  3492. #endif
  3493. }
  3494. #endif
  3495. }
  3496. #define TCLSH_MAIN main /* Needed to fake out mktclapp */
  3497. int TCLSH_MAIN(int argc, char **argv){
  3498. Tcl_Interp *interp;
  3499. #if !defined(_WIN32_WCE)
  3500. if( getenv("BREAK") ){
  3501. fprintf(stderr,
  3502. "attach debugger to process %d and press any key to continue.\n",
  3503. GETPID());
  3504. fgetc(stdin);
  3505. }
  3506. #endif
  3507. /* Call sqlite3_shutdown() once before doing anything else. This is to
  3508. ** test that sqlite3_shutdown() can be safely called by a process before
  3509. ** sqlite3_initialize() is. */
  3510. sqlite3_shutdown();
  3511. Tcl_FindExecutable(argv[0]);
  3512. interp = Tcl_CreateInterp();
  3513. #if TCLSH==2
  3514. sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
  3515. #endif
  3516. init_all(interp);
  3517. if( argc>=2 ){
  3518. int i;
  3519. char zArgc[32];
  3520. sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
  3521. Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
  3522. Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
  3523. Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
  3524. for(i=3-TCLSH; i<argc; i++){
  3525. Tcl_SetVar(interp, "argv", argv[i],
  3526. TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
  3527. }
  3528. if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
  3529. const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
  3530. if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
  3531. fprintf(stderr,"%s: %s\n", *argv, zInfo);
  3532. return 1;
  3533. }
  3534. }
  3535. if( TCLSH==2 || argc<=1 ){
  3536. Tcl_GlobalEval(interp, tclsh_main_loop());
  3537. }
  3538. return 0;
  3539. }
  3540. #endif /* TCLSH */