tclsqlite.c 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592
  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. ** $Id: tclsqlite.c,v 1.207 2007/11/14 06:48:48 danielk1977 Exp $
  16. */
  17. #include "tcl.h"
  18. #include <errno.h>
  19. /*
  20. ** Some additional include files are needed if this file is not
  21. ** appended to the amalgamation.
  22. */
  23. #ifndef SQLITE_AMALGAMATION
  24. # include "sqliteInt.h"
  25. # include <stdlib.h>
  26. # include <string.h>
  27. # include <assert.h>
  28. # include <ctype.h>
  29. #endif
  30. /*
  31. * Windows needs to know which symbols to export. Unix does not.
  32. * BUILD_sqlite should be undefined for Unix.
  33. */
  34. #ifdef BUILD_sqlite
  35. #undef TCL_STORAGE_CLASS
  36. #define TCL_STORAGE_CLASS DLLEXPORT
  37. #endif /* BUILD_sqlite */
  38. #define NUM_PREPARED_STMTS 10
  39. #define MAX_PREPARED_STMTS 100
  40. /*
  41. ** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
  42. ** have to do a translation when going between the two. Set the
  43. ** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
  44. ** this translation.
  45. */
  46. #if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
  47. # define UTF_TRANSLATION_NEEDED 1
  48. #endif
  49. /*
  50. ** New SQL functions can be created as TCL scripts. Each such function
  51. ** is described by an instance of the following structure.
  52. */
  53. typedef struct SqlFunc SqlFunc;
  54. struct SqlFunc {
  55. Tcl_Interp *interp; /* The TCL interpret to execute the function */
  56. Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
  57. int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
  58. char *zName; /* Name of this function */
  59. SqlFunc *pNext; /* Next function on the list of them all */
  60. };
  61. /*
  62. ** New collation sequences function can be created as TCL scripts. Each such
  63. ** function is described by an instance of the following structure.
  64. */
  65. typedef struct SqlCollate SqlCollate;
  66. struct SqlCollate {
  67. Tcl_Interp *interp; /* The TCL interpret to execute the function */
  68. char *zScript; /* The script to be run */
  69. SqlCollate *pNext; /* Next function on the list of them all */
  70. };
  71. /*
  72. ** Prepared statements are cached for faster execution. Each prepared
  73. ** statement is described by an instance of the following structure.
  74. */
  75. typedef struct SqlPreparedStmt SqlPreparedStmt;
  76. struct SqlPreparedStmt {
  77. SqlPreparedStmt *pNext; /* Next in linked list */
  78. SqlPreparedStmt *pPrev; /* Previous on the list */
  79. sqlite3_stmt *pStmt; /* The prepared statement */
  80. int nSql; /* chars in zSql[] */
  81. const char *zSql; /* Text of the SQL statement */
  82. };
  83. typedef struct IncrblobChannel IncrblobChannel;
  84. /*
  85. ** There is one instance of this structure for each SQLite database
  86. ** that has been opened by the SQLite TCL interface.
  87. */
  88. typedef struct SqliteDb SqliteDb;
  89. struct SqliteDb {
  90. sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
  91. Tcl_Interp *interp; /* The interpreter used for this database */
  92. char *zBusy; /* The busy callback routine */
  93. char *zCommit; /* The commit hook callback routine */
  94. char *zTrace; /* The trace callback routine */
  95. char *zProfile; /* The profile callback routine */
  96. char *zProgress; /* The progress callback routine */
  97. char *zAuth; /* The authorization callback routine */
  98. char *zNull; /* Text to substitute for an SQL NULL value */
  99. SqlFunc *pFunc; /* List of SQL functions */
  100. Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
  101. Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
  102. SqlCollate *pCollate; /* List of SQL collation functions */
  103. int rc; /* Return code of most recent sqlite3_exec() */
  104. Tcl_Obj *pCollateNeeded; /* Collation needed script */
  105. SqlPreparedStmt *stmtList; /* List of prepared statements*/
  106. SqlPreparedStmt *stmtLast; /* Last statement in the list */
  107. int maxStmt; /* The next maximum number of stmtList */
  108. int nStmt; /* Number of statements in stmtList */
  109. IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
  110. };
  111. struct IncrblobChannel {
  112. sqlite3_blob *pBlob; /* sqlite3 blob handle */
  113. SqliteDb *pDb; /* Associated database connection */
  114. int iSeek; /* Current seek offset */
  115. Tcl_Channel channel; /* Channel identifier */
  116. IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
  117. IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
  118. };
  119. #ifndef SQLITE_OMIT_INCRBLOB
  120. /*
  121. ** Close all incrblob channels opened using database connection pDb.
  122. ** This is called when shutting down the database connection.
  123. */
  124. static void closeIncrblobChannels(SqliteDb *pDb){
  125. IncrblobChannel *p;
  126. IncrblobChannel *pNext;
  127. for(p=pDb->pIncrblob; p; p=pNext){
  128. pNext = p->pNext;
  129. /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
  130. ** which deletes the IncrblobChannel structure at *p. So do not
  131. ** call Tcl_Free() here.
  132. */
  133. Tcl_UnregisterChannel(pDb->interp, p->channel);
  134. }
  135. }
  136. /*
  137. ** Close an incremental blob channel.
  138. */
  139. static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
  140. IncrblobChannel *p = (IncrblobChannel *)instanceData;
  141. int rc = sqlite3_blob_close(p->pBlob);
  142. sqlite3 *db = p->pDb->db;
  143. /* Remove the channel from the SqliteDb.pIncrblob list. */
  144. if( p->pNext ){
  145. p->pNext->pPrev = p->pPrev;
  146. }
  147. if( p->pPrev ){
  148. p->pPrev->pNext = p->pNext;
  149. }
  150. if( p->pDb->pIncrblob==p ){
  151. p->pDb->pIncrblob = p->pNext;
  152. }
  153. /* Free the IncrblobChannel structure */
  154. Tcl_Free((char *)p);
  155. if( rc!=SQLITE_OK ){
  156. Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
  157. return TCL_ERROR;
  158. }
  159. return TCL_OK;
  160. }
  161. /*
  162. ** Read data from an incremental blob channel.
  163. */
  164. static int incrblobInput(
  165. ClientData instanceData,
  166. char *buf,
  167. int bufSize,
  168. int *errorCodePtr
  169. ){
  170. IncrblobChannel *p = (IncrblobChannel *)instanceData;
  171. int nRead = bufSize; /* Number of bytes to read */
  172. int nBlob; /* Total size of the blob */
  173. int rc; /* sqlite error code */
  174. nBlob = sqlite3_blob_bytes(p->pBlob);
  175. if( (p->iSeek+nRead)>nBlob ){
  176. nRead = nBlob-p->iSeek;
  177. }
  178. if( nRead<=0 ){
  179. return 0;
  180. }
  181. rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
  182. if( rc!=SQLITE_OK ){
  183. *errorCodePtr = rc;
  184. return -1;
  185. }
  186. p->iSeek += nRead;
  187. return nRead;
  188. }
  189. /*
  190. ** Write data to an incremental blob channel.
  191. */
  192. static int incrblobOutput(
  193. ClientData instanceData,
  194. CONST char *buf,
  195. int toWrite,
  196. int *errorCodePtr
  197. ){
  198. IncrblobChannel *p = (IncrblobChannel *)instanceData;
  199. int nWrite = toWrite; /* Number of bytes to write */
  200. int nBlob; /* Total size of the blob */
  201. int rc; /* sqlite error code */
  202. nBlob = sqlite3_blob_bytes(p->pBlob);
  203. if( (p->iSeek+nWrite)>nBlob ){
  204. *errorCodePtr = EINVAL;
  205. return -1;
  206. }
  207. if( nWrite<=0 ){
  208. return 0;
  209. }
  210. rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
  211. if( rc!=SQLITE_OK ){
  212. *errorCodePtr = EIO;
  213. return -1;
  214. }
  215. p->iSeek += nWrite;
  216. return nWrite;
  217. }
  218. /*
  219. ** Seek an incremental blob channel.
  220. */
  221. static int incrblobSeek(
  222. ClientData instanceData,
  223. long offset,
  224. int seekMode,
  225. int *errorCodePtr
  226. ){
  227. IncrblobChannel *p = (IncrblobChannel *)instanceData;
  228. switch( seekMode ){
  229. case SEEK_SET:
  230. p->iSeek = offset;
  231. break;
  232. case SEEK_CUR:
  233. p->iSeek += offset;
  234. break;
  235. case SEEK_END:
  236. p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
  237. break;
  238. default: assert(!"Bad seekMode");
  239. }
  240. return p->iSeek;
  241. }
  242. static void incrblobWatch(ClientData instanceData, int mode){
  243. /* NO-OP */
  244. }
  245. static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
  246. return TCL_ERROR;
  247. }
  248. static Tcl_ChannelType IncrblobChannelType = {
  249. "incrblob", /* typeName */
  250. TCL_CHANNEL_VERSION_2, /* version */
  251. incrblobClose, /* closeProc */
  252. incrblobInput, /* inputProc */
  253. incrblobOutput, /* outputProc */
  254. incrblobSeek, /* seekProc */
  255. 0, /* setOptionProc */
  256. 0, /* getOptionProc */
  257. incrblobWatch, /* watchProc (this is a no-op) */
  258. incrblobHandle, /* getHandleProc (always returns error) */
  259. 0, /* close2Proc */
  260. 0, /* blockModeProc */
  261. 0, /* flushProc */
  262. 0, /* handlerProc */
  263. 0, /* wideSeekProc */
  264. };
  265. /*
  266. ** Create a new incrblob channel.
  267. */
  268. static int createIncrblobChannel(
  269. Tcl_Interp *interp,
  270. SqliteDb *pDb,
  271. const char *zDb,
  272. const char *zTable,
  273. const char *zColumn,
  274. sqlite_int64 iRow,
  275. int isReadonly
  276. ){
  277. IncrblobChannel *p;
  278. sqlite3 *db = pDb->db;
  279. sqlite3_blob *pBlob;
  280. int rc;
  281. int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
  282. /* This variable is used to name the channels: "incrblob_[incr count]" */
  283. static int count = 0;
  284. char zChannel[64];
  285. rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
  286. if( rc!=SQLITE_OK ){
  287. Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
  288. return TCL_ERROR;
  289. }
  290. p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
  291. p->iSeek = 0;
  292. p->pBlob = pBlob;
  293. sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
  294. p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
  295. Tcl_RegisterChannel(interp, p->channel);
  296. /* Link the new channel into the SqliteDb.pIncrblob list. */
  297. p->pNext = pDb->pIncrblob;
  298. p->pPrev = 0;
  299. if( p->pNext ){
  300. p->pNext->pPrev = p;
  301. }
  302. pDb->pIncrblob = p;
  303. p->pDb = pDb;
  304. Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
  305. return TCL_OK;
  306. }
  307. #else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
  308. #define closeIncrblobChannels(pDb)
  309. #endif
  310. /*
  311. ** Look at the script prefix in pCmd. We will be executing this script
  312. ** after first appending one or more arguments. This routine analyzes
  313. ** the script to see if it is safe to use Tcl_EvalObjv() on the script
  314. ** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
  315. ** faster.
  316. **
  317. ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
  318. ** command name followed by zero or more arguments with no [...] or $
  319. ** or {...} or ; to be seen anywhere. Most callback scripts consist
  320. ** of just a single procedure name and they meet this requirement.
  321. */
  322. static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
  323. /* We could try to do something with Tcl_Parse(). But we will instead
  324. ** just do a search for forbidden characters. If any of the forbidden
  325. ** characters appear in pCmd, we will report the string as unsafe.
  326. */
  327. const char *z;
  328. int n;
  329. z = Tcl_GetStringFromObj(pCmd, &n);
  330. while( n-- > 0 ){
  331. int c = *(z++);
  332. if( c=='$' || c=='[' || c==';' ) return 0;
  333. }
  334. return 1;
  335. }
  336. /*
  337. ** Find an SqlFunc structure with the given name. Or create a new
  338. ** one if an existing one cannot be found. Return a pointer to the
  339. ** structure.
  340. */
  341. static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
  342. SqlFunc *p, *pNew;
  343. int i;
  344. pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
  345. pNew->zName = (char*)&pNew[1];
  346. for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
  347. pNew->zName[i] = 0;
  348. for(p=pDb->pFunc; p; p=p->pNext){
  349. if( strcmp(p->zName, pNew->zName)==0 ){
  350. Tcl_Free((char*)pNew);
  351. return p;
  352. }
  353. }
  354. pNew->interp = pDb->interp;
  355. pNew->pScript = 0;
  356. pNew->pNext = pDb->pFunc;
  357. pDb->pFunc = pNew;
  358. return pNew;
  359. }
  360. /*
  361. ** Finalize and free a list of prepared statements
  362. */
  363. static void flushStmtCache( SqliteDb *pDb ){
  364. SqlPreparedStmt *pPreStmt;
  365. while( pDb->stmtList ){
  366. sqlite3_finalize( pDb->stmtList->pStmt );
  367. pPreStmt = pDb->stmtList;
  368. pDb->stmtList = pDb->stmtList->pNext;
  369. Tcl_Free( (char*)pPreStmt );
  370. }
  371. pDb->nStmt = 0;
  372. pDb->stmtLast = 0;
  373. }
  374. /*
  375. ** TCL calls this procedure when an sqlite3 database command is
  376. ** deleted.
  377. */
  378. static void DbDeleteCmd(void *db){
  379. SqliteDb *pDb = (SqliteDb*)db;
  380. flushStmtCache(pDb);
  381. closeIncrblobChannels(pDb);
  382. sqlite3_close(pDb->db);
  383. while( pDb->pFunc ){
  384. SqlFunc *pFunc = pDb->pFunc;
  385. pDb->pFunc = pFunc->pNext;
  386. Tcl_DecrRefCount(pFunc->pScript);
  387. Tcl_Free((char*)pFunc);
  388. }
  389. while( pDb->pCollate ){
  390. SqlCollate *pCollate = pDb->pCollate;
  391. pDb->pCollate = pCollate->pNext;
  392. Tcl_Free((char*)pCollate);
  393. }
  394. if( pDb->zBusy ){
  395. Tcl_Free(pDb->zBusy);
  396. }
  397. if( pDb->zTrace ){
  398. Tcl_Free(pDb->zTrace);
  399. }
  400. if( pDb->zProfile ){
  401. Tcl_Free(pDb->zProfile);
  402. }
  403. if( pDb->zAuth ){
  404. Tcl_Free(pDb->zAuth);
  405. }
  406. if( pDb->zNull ){
  407. Tcl_Free(pDb->zNull);
  408. }
  409. if( pDb->pUpdateHook ){
  410. Tcl_DecrRefCount(pDb->pUpdateHook);
  411. }
  412. if( pDb->pRollbackHook ){
  413. Tcl_DecrRefCount(pDb->pRollbackHook);
  414. }
  415. if( pDb->pCollateNeeded ){
  416. Tcl_DecrRefCount(pDb->pCollateNeeded);
  417. }
  418. Tcl_Free((char*)pDb);
  419. }
  420. /*
  421. ** This routine is called when a database file is locked while trying
  422. ** to execute SQL.
  423. */
  424. static int DbBusyHandler(void *cd, int nTries){
  425. SqliteDb *pDb = (SqliteDb*)cd;
  426. int rc;
  427. char zVal[30];
  428. sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
  429. rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
  430. if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
  431. return 0;
  432. }
  433. return 1;
  434. }
  435. /*
  436. ** This routine is invoked as the 'progress callback' for the database.
  437. */
  438. static int DbProgressHandler(void *cd){
  439. SqliteDb *pDb = (SqliteDb*)cd;
  440. int rc;
  441. assert( pDb->zProgress );
  442. rc = Tcl_Eval(pDb->interp, pDb->zProgress);
  443. if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
  444. return 1;
  445. }
  446. return 0;
  447. }
  448. #ifndef SQLITE_OMIT_TRACE
  449. /*
  450. ** This routine is called by the SQLite trace handler whenever a new
  451. ** block of SQL is executed. The TCL script in pDb->zTrace is executed.
  452. */
  453. static void DbTraceHandler(void *cd, const char *zSql){
  454. SqliteDb *pDb = (SqliteDb*)cd;
  455. Tcl_DString str;
  456. Tcl_DStringInit(&str);
  457. Tcl_DStringAppend(&str, pDb->zTrace, -1);
  458. Tcl_DStringAppendElement(&str, zSql);
  459. Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
  460. Tcl_DStringFree(&str);
  461. Tcl_ResetResult(pDb->interp);
  462. }
  463. #endif
  464. #ifndef SQLITE_OMIT_TRACE
  465. /*
  466. ** This routine is called by the SQLite profile handler after a statement
  467. ** SQL has executed. The TCL script in pDb->zProfile is evaluated.
  468. */
  469. static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
  470. SqliteDb *pDb = (SqliteDb*)cd;
  471. Tcl_DString str;
  472. char zTm[100];
  473. sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
  474. Tcl_DStringInit(&str);
  475. Tcl_DStringAppend(&str, pDb->zProfile, -1);
  476. Tcl_DStringAppendElement(&str, zSql);
  477. Tcl_DStringAppendElement(&str, zTm);
  478. Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
  479. Tcl_DStringFree(&str);
  480. Tcl_ResetResult(pDb->interp);
  481. }
  482. #endif
  483. /*
  484. ** This routine is called when a transaction is committed. The
  485. ** TCL script in pDb->zCommit is executed. If it returns non-zero or
  486. ** if it throws an exception, the transaction is rolled back instead
  487. ** of being committed.
  488. */
  489. static int DbCommitHandler(void *cd){
  490. SqliteDb *pDb = (SqliteDb*)cd;
  491. int rc;
  492. rc = Tcl_Eval(pDb->interp, pDb->zCommit);
  493. if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
  494. return 1;
  495. }
  496. return 0;
  497. }
  498. static void DbRollbackHandler(void *clientData){
  499. SqliteDb *pDb = (SqliteDb*)clientData;
  500. assert(pDb->pRollbackHook);
  501. if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
  502. Tcl_BackgroundError(pDb->interp);
  503. }
  504. }
  505. static void DbUpdateHandler(
  506. void *p,
  507. int op,
  508. const char *zDb,
  509. const char *zTbl,
  510. sqlite_int64 rowid
  511. ){
  512. SqliteDb *pDb = (SqliteDb *)p;
  513. Tcl_Obj *pCmd;
  514. assert( pDb->pUpdateHook );
  515. assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
  516. pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
  517. Tcl_IncrRefCount(pCmd);
  518. Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
  519. ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
  520. Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
  521. Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
  522. Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
  523. Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
  524. }
  525. static void tclCollateNeeded(
  526. void *pCtx,
  527. sqlite3 *db,
  528. int enc,
  529. const char *zName
  530. ){
  531. SqliteDb *pDb = (SqliteDb *)pCtx;
  532. Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
  533. Tcl_IncrRefCount(pScript);
  534. Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
  535. Tcl_EvalObjEx(pDb->interp, pScript, 0);
  536. Tcl_DecrRefCount(pScript);
  537. }
  538. /*
  539. ** This routine is called to evaluate an SQL collation function implemented
  540. ** using TCL script.
  541. */
  542. static int tclSqlCollate(
  543. void *pCtx,
  544. int nA,
  545. const void *zA,
  546. int nB,
  547. const void *zB
  548. ){
  549. SqlCollate *p = (SqlCollate *)pCtx;
  550. Tcl_Obj *pCmd;
  551. pCmd = Tcl_NewStringObj(p->zScript, -1);
  552. Tcl_IncrRefCount(pCmd);
  553. Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
  554. Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
  555. Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
  556. Tcl_DecrRefCount(pCmd);
  557. return (atoi(Tcl_GetStringResult(p->interp)));
  558. }
  559. /*
  560. ** This routine is called to evaluate an SQL function implemented
  561. ** using TCL script.
  562. */
  563. static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
  564. SqlFunc *p = sqlite3_user_data(context);
  565. Tcl_Obj *pCmd;
  566. int i;
  567. int rc;
  568. if( argc==0 ){
  569. /* If there are no arguments to the function, call Tcl_EvalObjEx on the
  570. ** script object directly. This allows the TCL compiler to generate
  571. ** bytecode for the command on the first invocation and thus make
  572. ** subsequent invocations much faster. */
  573. pCmd = p->pScript;
  574. Tcl_IncrRefCount(pCmd);
  575. rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
  576. Tcl_DecrRefCount(pCmd);
  577. }else{
  578. /* If there are arguments to the function, make a shallow copy of the
  579. ** script object, lappend the arguments, then evaluate the copy.
  580. **
  581. ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
  582. ** The new Tcl_Obj contains pointers to the original list elements.
  583. ** That way, when Tcl_EvalObjv() is run and shimmers the first element
  584. ** of the list to tclCmdNameType, that alternate representation will
  585. ** be preserved and reused on the next invocation.
  586. */
  587. Tcl_Obj **aArg;
  588. int nArg;
  589. if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
  590. sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
  591. return;
  592. }
  593. pCmd = Tcl_NewListObj(nArg, aArg);
  594. Tcl_IncrRefCount(pCmd);
  595. for(i=0; i<argc; i++){
  596. sqlite3_value *pIn = argv[i];
  597. Tcl_Obj *pVal;
  598. /* Set pVal to contain the i'th column of this row. */
  599. switch( sqlite3_value_type(pIn) ){
  600. case SQLITE_BLOB: {
  601. int bytes = sqlite3_value_bytes(pIn);
  602. pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
  603. break;
  604. }
  605. case SQLITE_INTEGER: {
  606. sqlite_int64 v = sqlite3_value_int64(pIn);
  607. if( v>=-2147483647 && v<=2147483647 ){
  608. pVal = Tcl_NewIntObj(v);
  609. }else{
  610. pVal = Tcl_NewWideIntObj(v);
  611. }
  612. break;
  613. }
  614. case SQLITE_FLOAT: {
  615. double r = sqlite3_value_double(pIn);
  616. pVal = Tcl_NewDoubleObj(r);
  617. break;
  618. }
  619. case SQLITE_NULL: {
  620. pVal = Tcl_NewStringObj("", 0);
  621. break;
  622. }
  623. default: {
  624. int bytes = sqlite3_value_bytes(pIn);
  625. pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
  626. break;
  627. }
  628. }
  629. rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
  630. if( rc ){
  631. Tcl_DecrRefCount(pCmd);
  632. sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
  633. return;
  634. }
  635. }
  636. if( !p->useEvalObjv ){
  637. /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
  638. ** is a list without a string representation. To prevent this from
  639. ** happening, make sure pCmd has a valid string representation */
  640. Tcl_GetString(pCmd);
  641. }
  642. rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
  643. Tcl_DecrRefCount(pCmd);
  644. }
  645. if( rc && rc!=TCL_RETURN ){
  646. sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
  647. }else{
  648. Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
  649. int n;
  650. u8 *data;
  651. char *zType = pVar->typePtr ? pVar->typePtr->name : "";
  652. char c = zType[0];
  653. if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
  654. /* Only return a BLOB type if the Tcl variable is a bytearray and
  655. ** has no string representation. */
  656. data = Tcl_GetByteArrayFromObj(pVar, &n);
  657. sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
  658. }else if( c=='b' && strcmp(zType,"boolean")==0 ){
  659. Tcl_GetIntFromObj(0, pVar, &n);
  660. sqlite3_result_int(context, n);
  661. }else if( c=='d' && strcmp(zType,"double")==0 ){
  662. double r;
  663. Tcl_GetDoubleFromObj(0, pVar, &r);
  664. sqlite3_result_double(context, r);
  665. }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
  666. (c=='i' && strcmp(zType,"int")==0) ){
  667. Tcl_WideInt v;
  668. Tcl_GetWideIntFromObj(0, pVar, &v);
  669. sqlite3_result_int64(context, v);
  670. }else{
  671. data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
  672. sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
  673. }
  674. }
  675. }
  676. #ifndef SQLITE_OMIT_AUTHORIZATION
  677. /*
  678. ** This is the authentication function. It appends the authentication
  679. ** type code and the two arguments to zCmd[] then invokes the result
  680. ** on the interpreter. The reply is examined to determine if the
  681. ** authentication fails or succeeds.
  682. */
  683. static int auth_callback(
  684. void *pArg,
  685. int code,
  686. const char *zArg1,
  687. const char *zArg2,
  688. const char *zArg3,
  689. const char *zArg4
  690. ){
  691. char *zCode;
  692. Tcl_DString str;
  693. int rc;
  694. const char *zReply;
  695. SqliteDb *pDb = (SqliteDb*)pArg;
  696. switch( code ){
  697. case SQLITE_COPY : zCode="SQLITE_COPY"; break;
  698. case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
  699. case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
  700. case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
  701. case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
  702. case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
  703. case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
  704. case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
  705. case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
  706. case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
  707. case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
  708. case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
  709. case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
  710. case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
  711. case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
  712. case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
  713. case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
  714. case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
  715. case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
  716. case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
  717. case SQLITE_READ : zCode="SQLITE_READ"; break;
  718. case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
  719. case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
  720. case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
  721. case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
  722. case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
  723. case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
  724. case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
  725. case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
  726. case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
  727. case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
  728. case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
  729. default : zCode="????"; break;
  730. }
  731. Tcl_DStringInit(&str);
  732. Tcl_DStringAppend(&str, pDb->zAuth, -1);
  733. Tcl_DStringAppendElement(&str, zCode);
  734. Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
  735. Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
  736. Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
  737. Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
  738. rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
  739. Tcl_DStringFree(&str);
  740. zReply = Tcl_GetStringResult(pDb->interp);
  741. if( strcmp(zReply,"SQLITE_OK")==0 ){
  742. rc = SQLITE_OK;
  743. }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
  744. rc = SQLITE_DENY;
  745. }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
  746. rc = SQLITE_IGNORE;
  747. }else{
  748. rc = 999;
  749. }
  750. return rc;
  751. }
  752. #endif /* SQLITE_OMIT_AUTHORIZATION */
  753. /*
  754. ** zText is a pointer to text obtained via an sqlite3_result_text()
  755. ** or similar interface. This routine returns a Tcl string object,
  756. ** reference count set to 0, containing the text. If a translation
  757. ** between iso8859 and UTF-8 is required, it is preformed.
  758. */
  759. static Tcl_Obj *dbTextToObj(char const *zText){
  760. Tcl_Obj *pVal;
  761. #ifdef UTF_TRANSLATION_NEEDED
  762. Tcl_DString dCol;
  763. Tcl_DStringInit(&dCol);
  764. Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
  765. pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
  766. Tcl_DStringFree(&dCol);
  767. #else
  768. pVal = Tcl_NewStringObj(zText, -1);
  769. #endif
  770. return pVal;
  771. }
  772. /*
  773. ** This routine reads a line of text from FILE in, stores
  774. ** the text in memory obtained from malloc() and returns a pointer
  775. ** to the text. NULL is returned at end of file, or if malloc()
  776. ** fails.
  777. **
  778. ** The interface is like "readline" but no command-line editing
  779. ** is done.
  780. **
  781. ** copied from shell.c from '.import' command
  782. */
  783. static char *local_getline(char *zPrompt, FILE *in){
  784. char *zLine;
  785. int nLine;
  786. int n;
  787. int eol;
  788. nLine = 100;
  789. zLine = malloc( nLine );
  790. if( zLine==0 ) return 0;
  791. n = 0;
  792. eol = 0;
  793. while( !eol ){
  794. if( n+100>nLine ){
  795. nLine = nLine*2 + 100;
  796. zLine = realloc(zLine, nLine);
  797. if( zLine==0 ) return 0;
  798. }
  799. if( fgets(&zLine[n], nLine - n, in)==0 ){
  800. if( n==0 ){
  801. free(zLine);
  802. return 0;
  803. }
  804. zLine[n] = 0;
  805. eol = 1;
  806. break;
  807. }
  808. while( zLine[n] ){ n++; }
  809. if( n>0 && zLine[n-1]=='\n' ){
  810. n--;
  811. zLine[n] = 0;
  812. eol = 1;
  813. }
  814. }
  815. zLine = realloc( zLine, n+1 );
  816. return zLine;
  817. }
  818. /*
  819. ** Figure out the column names for the data returned by the statement
  820. ** passed as the second argument.
  821. **
  822. ** If parameter papColName is not NULL, then *papColName is set to point
  823. ** at an array allocated using Tcl_Alloc(). It is the callers responsibility
  824. ** to free this array using Tcl_Free(), and to decrement the reference
  825. ** count of each Tcl_Obj* member of the array.
  826. **
  827. ** The return value of this function is the number of columns of data
  828. ** returned by pStmt (and hence the size of the *papColName array).
  829. **
  830. ** If pArray is not NULL, then it contains the name of a Tcl array
  831. ** variable. The "*" member of this array is set to a list containing
  832. ** the names of the columns returned by the statement, in order from
  833. ** left to right. e.g. if the names of the returned columns are a, b and
  834. ** c, it does the equivalent of the tcl command:
  835. **
  836. ** set ${pArray}(*) {a b c}
  837. */
  838. static int
  839. computeColumnNames(
  840. Tcl_Interp *interp,
  841. sqlite3_stmt *pStmt, /* SQL statement */
  842. Tcl_Obj ***papColName, /* OUT: Array of column names */
  843. Tcl_Obj *pArray /* Name of array variable (may be null) */
  844. ){
  845. int nCol;
  846. /* Compute column names */
  847. nCol = sqlite3_column_count(pStmt);
  848. if( papColName ){
  849. int i;
  850. Tcl_Obj **apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
  851. for(i=0; i<nCol; i++){
  852. apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
  853. Tcl_IncrRefCount(apColName[i]);
  854. }
  855. /* If results are being stored in an array variable, then create
  856. ** the array(*) entry for that array
  857. */
  858. if( pArray ){
  859. Tcl_Obj *pColList = Tcl_NewObj();
  860. Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
  861. Tcl_IncrRefCount(pColList);
  862. for(i=0; i<nCol; i++){
  863. Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
  864. }
  865. Tcl_IncrRefCount(pStar);
  866. Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
  867. Tcl_DecrRefCount(pColList);
  868. Tcl_DecrRefCount(pStar);
  869. }
  870. *papColName = apColName;
  871. }
  872. return nCol;
  873. }
  874. /*
  875. ** The "sqlite" command below creates a new Tcl command for each
  876. ** connection it opens to an SQLite database. This routine is invoked
  877. ** whenever one of those connection-specific commands is executed
  878. ** in Tcl. For example, if you run Tcl code like this:
  879. **
  880. ** sqlite3 db1 "my_database"
  881. ** db1 close
  882. **
  883. ** The first command opens a connection to the "my_database" database
  884. ** and calls that connection "db1". The second command causes this
  885. ** subroutine to be invoked.
  886. */
  887. static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
  888. SqliteDb *pDb = (SqliteDb*)cd;
  889. int choice;
  890. int rc = TCL_OK;
  891. static const char *DB_strs[] = {
  892. "authorizer", "busy", "cache",
  893. "changes", "close", "collate",
  894. "collation_needed", "commit_hook", "complete",
  895. "copy", "enable_load_extension","errorcode",
  896. "eval", "exists", "function",
  897. "incrblob", "interrupt", "last_insert_rowid",
  898. "nullvalue", "onecolumn", "profile",
  899. "progress", "rekey", "rollback_hook",
  900. "timeout", "total_changes", "trace",
  901. "transaction", "update_hook", "version",
  902. 0
  903. };
  904. enum DB_enum {
  905. DB_AUTHORIZER, DB_BUSY, DB_CACHE,
  906. DB_CHANGES, DB_CLOSE, DB_COLLATE,
  907. DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
  908. DB_COPY, DB_ENABLE_LOAD_EXTENSION,DB_ERRORCODE,
  909. DB_EVAL, DB_EXISTS, DB_FUNCTION,
  910. DB_INCRBLOB, DB_INTERRUPT, DB_LAST_INSERT_ROWID,
  911. DB_NULLVALUE, DB_ONECOLUMN, DB_PROFILE,
  912. DB_PROGRESS, DB_REKEY, DB_ROLLBACK_HOOK,
  913. DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
  914. DB_TRANSACTION, DB_UPDATE_HOOK, DB_VERSION
  915. };
  916. /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
  917. if( objc<2 ){
  918. Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
  919. return TCL_ERROR;
  920. }
  921. if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
  922. return TCL_ERROR;
  923. }
  924. switch( (enum DB_enum)choice ){
  925. /* $db authorizer ?CALLBACK?
  926. **
  927. ** Invoke the given callback to authorize each SQL operation as it is
  928. ** compiled. 5 arguments are appended to the callback before it is
  929. ** invoked:
  930. **
  931. ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
  932. ** (2) First descriptive name (depends on authorization type)
  933. ** (3) Second descriptive name
  934. ** (4) Name of the database (ex: "main", "temp")
  935. ** (5) Name of trigger that is doing the access
  936. **
  937. ** The callback should return on of the following strings: SQLITE_OK,
  938. ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
  939. **
  940. ** If this method is invoked with no arguments, the current authorization
  941. ** callback string is returned.
  942. */
  943. case DB_AUTHORIZER: {
  944. #ifdef SQLITE_OMIT_AUTHORIZATION
  945. Tcl_AppendResult(interp, "authorization not available in this build", 0);
  946. return TCL_ERROR;
  947. #else
  948. if( objc>3 ){
  949. Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
  950. return TCL_ERROR;
  951. }else if( objc==2 ){
  952. if( pDb->zAuth ){
  953. Tcl_AppendResult(interp, pDb->zAuth, 0);
  954. }
  955. }else{
  956. char *zAuth;
  957. int len;
  958. if( pDb->zAuth ){
  959. Tcl_Free(pDb->zAuth);
  960. }
  961. zAuth = Tcl_GetStringFromObj(objv[2], &len);
  962. if( zAuth && len>0 ){
  963. pDb->zAuth = Tcl_Alloc( len + 1 );
  964. memcpy(pDb->zAuth, zAuth, len+1);
  965. }else{
  966. pDb->zAuth = 0;
  967. }
  968. if( pDb->zAuth ){
  969. pDb->interp = interp;
  970. sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
  971. }else{
  972. sqlite3_set_authorizer(pDb->db, 0, 0);
  973. }
  974. }
  975. #endif
  976. break;
  977. }
  978. /* $db busy ?CALLBACK?
  979. **
  980. ** Invoke the given callback if an SQL statement attempts to open
  981. ** a locked database file.
  982. */
  983. case DB_BUSY: {
  984. if( objc>3 ){
  985. Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
  986. return TCL_ERROR;
  987. }else if( objc==2 ){
  988. if( pDb->zBusy ){
  989. Tcl_AppendResult(interp, pDb->zBusy, 0);
  990. }
  991. }else{
  992. char *zBusy;
  993. int len;
  994. if( pDb->zBusy ){
  995. Tcl_Free(pDb->zBusy);
  996. }
  997. zBusy = Tcl_GetStringFromObj(objv[2], &len);
  998. if( zBusy && len>0 ){
  999. pDb->zBusy = Tcl_Alloc( len + 1 );
  1000. memcpy(pDb->zBusy, zBusy, len+1);
  1001. }else{
  1002. pDb->zBusy = 0;
  1003. }
  1004. if( pDb->zBusy ){
  1005. pDb->interp = interp;
  1006. sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
  1007. }else{
  1008. sqlite3_busy_handler(pDb->db, 0, 0);
  1009. }
  1010. }
  1011. break;
  1012. }
  1013. /* $db cache flush
  1014. ** $db cache size n
  1015. **
  1016. ** Flush the prepared statement cache, or set the maximum number of
  1017. ** cached statements.
  1018. */
  1019. case DB_CACHE: {
  1020. char *subCmd;
  1021. int n;
  1022. if( objc<=2 ){
  1023. Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
  1024. return TCL_ERROR;
  1025. }
  1026. subCmd = Tcl_GetStringFromObj( objv[2], 0 );
  1027. if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
  1028. if( objc!=3 ){
  1029. Tcl_WrongNumArgs(interp, 2, objv, "flush");
  1030. return TCL_ERROR;
  1031. }else{
  1032. flushStmtCache( pDb );
  1033. }
  1034. }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
  1035. if( objc!=4 ){
  1036. Tcl_WrongNumArgs(interp, 2, objv, "size n");
  1037. return TCL_ERROR;
  1038. }else{
  1039. if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
  1040. Tcl_AppendResult( interp, "cannot convert \"",
  1041. Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
  1042. return TCL_ERROR;
  1043. }else{
  1044. if( n<0 ){
  1045. flushStmtCache( pDb );
  1046. n = 0;
  1047. }else if( n>MAX_PREPARED_STMTS ){
  1048. n = MAX_PREPARED_STMTS;
  1049. }
  1050. pDb->maxStmt = n;
  1051. }
  1052. }
  1053. }else{
  1054. Tcl_AppendResult( interp, "bad option \"",
  1055. Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
  1056. return TCL_ERROR;
  1057. }
  1058. break;
  1059. }
  1060. /* $db changes
  1061. **
  1062. ** Return the number of rows that were modified, inserted, or deleted by
  1063. ** the most recent INSERT, UPDATE or DELETE statement, not including
  1064. ** any changes made by trigger programs.
  1065. */
  1066. case DB_CHANGES: {
  1067. Tcl_Obj *pResult;
  1068. if( objc!=2 ){
  1069. Tcl_WrongNumArgs(interp, 2, objv, "");
  1070. return TCL_ERROR;
  1071. }
  1072. pResult = Tcl_GetObjResult(interp);
  1073. Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
  1074. break;
  1075. }
  1076. /* $db close
  1077. **
  1078. ** Shutdown the database
  1079. */
  1080. case DB_CLOSE: {
  1081. Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
  1082. break;
  1083. }
  1084. /*
  1085. ** $db collate NAME SCRIPT
  1086. **
  1087. ** Create a new SQL collation function called NAME. Whenever
  1088. ** that function is called, invoke SCRIPT to evaluate the function.
  1089. */
  1090. case DB_COLLATE: {
  1091. SqlCollate *pCollate;
  1092. char *zName;
  1093. char *zScript;
  1094. int nScript;
  1095. if( objc!=4 ){
  1096. Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
  1097. return TCL_ERROR;
  1098. }
  1099. zName = Tcl_GetStringFromObj(objv[2], 0);
  1100. zScript = Tcl_GetStringFromObj(objv[3], &nScript);
  1101. pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
  1102. if( pCollate==0 ) return TCL_ERROR;
  1103. pCollate->interp = interp;
  1104. pCollate->pNext = pDb->pCollate;
  1105. pCollate->zScript = (char*)&pCollate[1];
  1106. pDb->pCollate = pCollate;
  1107. memcpy(pCollate->zScript, zScript, nScript+1);
  1108. if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
  1109. pCollate, tclSqlCollate) ){
  1110. Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
  1111. return TCL_ERROR;
  1112. }
  1113. break;
  1114. }
  1115. /*
  1116. ** $db collation_needed SCRIPT
  1117. **
  1118. ** Create a new SQL collation function called NAME. Whenever
  1119. ** that function is called, invoke SCRIPT to evaluate the function.
  1120. */
  1121. case DB_COLLATION_NEEDED: {
  1122. if( objc!=3 ){
  1123. Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
  1124. return TCL_ERROR;
  1125. }
  1126. if( pDb->pCollateNeeded ){
  1127. Tcl_DecrRefCount(pDb->pCollateNeeded);
  1128. }
  1129. pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
  1130. Tcl_IncrRefCount(pDb->pCollateNeeded);
  1131. sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
  1132. break;
  1133. }
  1134. /* $db commit_hook ?CALLBACK?
  1135. **
  1136. ** Invoke the given callback just before committing every SQL transaction.
  1137. ** If the callback throws an exception or returns non-zero, then the
  1138. ** transaction is aborted. If CALLBACK is an empty string, the callback
  1139. ** is disabled.
  1140. */
  1141. case DB_COMMIT_HOOK: {
  1142. if( objc>3 ){
  1143. Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
  1144. return TCL_ERROR;
  1145. }else if( objc==2 ){
  1146. if( pDb->zCommit ){
  1147. Tcl_AppendResult(interp, pDb->zCommit, 0);
  1148. }
  1149. }else{
  1150. char *zCommit;
  1151. int len;
  1152. if( pDb->zCommit ){
  1153. Tcl_Free(pDb->zCommit);
  1154. }
  1155. zCommit = Tcl_GetStringFromObj(objv[2], &len);
  1156. if( zCommit && len>0 ){
  1157. pDb->zCommit = Tcl_Alloc( len + 1 );
  1158. memcpy(pDb->zCommit, zCommit, len+1);
  1159. }else{
  1160. pDb->zCommit = 0;
  1161. }
  1162. if( pDb->zCommit ){
  1163. pDb->interp = interp;
  1164. sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
  1165. }else{
  1166. sqlite3_commit_hook(pDb->db, 0, 0);
  1167. }
  1168. }
  1169. break;
  1170. }
  1171. /* $db complete SQL
  1172. **
  1173. ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
  1174. ** additional lines of input are needed. This is similar to the
  1175. ** built-in "info complete" command of Tcl.
  1176. */
  1177. case DB_COMPLETE: {
  1178. #ifndef SQLITE_OMIT_COMPLETE
  1179. Tcl_Obj *pResult;
  1180. int isComplete;
  1181. if( objc!=3 ){
  1182. Tcl_WrongNumArgs(interp, 2, objv, "SQL");
  1183. return TCL_ERROR;
  1184. }
  1185. isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
  1186. pResult = Tcl_GetObjResult(interp);
  1187. Tcl_SetBooleanObj(pResult, isComplete);
  1188. #endif
  1189. break;
  1190. }
  1191. /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
  1192. **
  1193. ** Copy data into table from filename, optionally using SEPARATOR
  1194. ** as column separators. If a column contains a null string, or the
  1195. ** value of NULLINDICATOR, a NULL is inserted for the column.
  1196. ** conflict-algorithm is one of the sqlite conflict algorithms:
  1197. ** rollback, abort, fail, ignore, replace
  1198. ** On success, return the number of lines processed, not necessarily same
  1199. ** as 'db changes' due to conflict-algorithm selected.
  1200. **
  1201. ** This code is basically an implementation/enhancement of
  1202. ** the sqlite3 shell.c ".import" command.
  1203. **
  1204. ** This command usage is equivalent to the sqlite2.x COPY statement,
  1205. ** which imports file data into a table using the PostgreSQL COPY file format:
  1206. ** $db copy $conflit_algo $table_name $filename \t \\N
  1207. */
  1208. case DB_COPY: {
  1209. char *zTable; /* Insert data into this table */
  1210. char *zFile; /* The file from which to extract data */
  1211. char *zConflict; /* The conflict algorithm to use */
  1212. sqlite3_stmt *pStmt; /* A statement */
  1213. int rc; /* Result code */
  1214. int nCol; /* Number of columns in the table */
  1215. int nByte; /* Number of bytes in an SQL string */
  1216. int i, j; /* Loop counters */
  1217. int nSep; /* Number of bytes in zSep[] */
  1218. int nNull; /* Number of bytes in zNull[] */
  1219. char *zSql; /* An SQL statement */
  1220. char *zLine; /* A single line of input from the file */
  1221. char **azCol; /* zLine[] broken up into columns */
  1222. char *zCommit; /* How to commit changes */
  1223. FILE *in; /* The input file */
  1224. int lineno = 0; /* Line number of input file */
  1225. char zLineNum[80]; /* Line number print buffer */
  1226. Tcl_Obj *pResult; /* interp result */
  1227. char *zSep;
  1228. char *zNull;
  1229. if( objc<5 || objc>7 ){
  1230. Tcl_WrongNumArgs(interp, 2, objv,
  1231. "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
  1232. return TCL_ERROR;
  1233. }
  1234. if( objc>=6 ){
  1235. zSep = Tcl_GetStringFromObj(objv[5], 0);
  1236. }else{
  1237. zSep = "\t";
  1238. }
  1239. if( objc>=7 ){
  1240. zNull = Tcl_GetStringFromObj(objv[6], 0);
  1241. }else{
  1242. zNull = "";
  1243. }
  1244. zConflict = Tcl_GetStringFromObj(objv[2], 0);
  1245. zTable = Tcl_GetStringFromObj(objv[3], 0);
  1246. zFile = Tcl_GetStringFromObj(objv[4], 0);
  1247. nSep = strlen(zSep);
  1248. nNull = strlen(zNull);
  1249. if( nSep==0 ){
  1250. Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
  1251. return TCL_ERROR;
  1252. }
  1253. if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
  1254. sqlite3StrICmp(zConflict, "abort" ) != 0 &&
  1255. sqlite3StrICmp(zConflict, "fail" ) != 0 &&
  1256. sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
  1257. sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
  1258. Tcl_AppendResult(interp, "Error: \"", zConflict,
  1259. "\", conflict-algorithm must be one of: rollback, "
  1260. "abort, fail, ignore, or replace", 0);
  1261. return TCL_ERROR;
  1262. }
  1263. zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
  1264. if( zSql==0 ){
  1265. Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
  1266. return TCL_ERROR;
  1267. }
  1268. nByte = strlen(zSql);
  1269. rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
  1270. sqlite3_free(zSql);
  1271. if( rc ){
  1272. Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
  1273. nCol = 0;
  1274. }else{
  1275. nCol = sqlite3_column_count(pStmt);
  1276. }
  1277. sqlite3_finalize(pStmt);
  1278. if( nCol==0 ) {
  1279. return TCL_ERROR;
  1280. }
  1281. zSql = malloc( nByte + 50 + nCol*2 );
  1282. if( zSql==0 ) {
  1283. Tcl_AppendResult(interp, "Error: can't malloc()", 0);
  1284. return TCL_ERROR;
  1285. }
  1286. sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
  1287. zConflict, zTable);
  1288. j = strlen(zSql);
  1289. for(i=1; i<nCol; i++){
  1290. zSql[j++] = ',';
  1291. zSql[j++] = '?';
  1292. }
  1293. zSql[j++] = ')';
  1294. zSql[j] = 0;
  1295. rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
  1296. free(zSql);
  1297. if( rc ){
  1298. Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
  1299. sqlite3_finalize(pStmt);
  1300. return TCL_ERROR;
  1301. }
  1302. in = fopen(zFile, "rb");
  1303. if( in==0 ){
  1304. Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
  1305. sqlite3_finalize(pStmt);
  1306. return TCL_ERROR;
  1307. }
  1308. azCol = malloc( sizeof(azCol[0])*(nCol+1) );
  1309. if( azCol==0 ) {
  1310. Tcl_AppendResult(interp, "Error: can't malloc()", 0);
  1311. fclose(in);
  1312. return TCL_ERROR;
  1313. }
  1314. (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
  1315. zCommit = "COMMIT";
  1316. while( (zLine = local_getline(0, in))!=0 ){
  1317. char *z;
  1318. i = 0;
  1319. lineno++;
  1320. azCol[0] = zLine;
  1321. for(i=0, z=zLine; *z; z++){
  1322. if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
  1323. *z = 0;
  1324. i++;
  1325. if( i<nCol ){
  1326. azCol[i] = &z[nSep];
  1327. z += nSep-1;
  1328. }
  1329. }
  1330. }
  1331. if( i+1!=nCol ){
  1332. char *zErr;
  1333. int nErr = strlen(zFile) + 200;
  1334. zErr = malloc(nErr);
  1335. if( zErr ){
  1336. sqlite3_snprintf(nErr, zErr,
  1337. "Error: %s line %d: expected %d columns of data but found %d",
  1338. zFile, lineno, nCol, i+1);
  1339. Tcl_AppendResult(interp, zErr, 0);
  1340. free(zErr);
  1341. }
  1342. zCommit = "ROLLBACK";
  1343. break;
  1344. }
  1345. for(i=0; i<nCol; i++){
  1346. /* check for null data, if so, bind as null */
  1347. if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
  1348. sqlite3_bind_null(pStmt, i+1);
  1349. }else{
  1350. sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
  1351. }
  1352. }
  1353. sqlite3_step(pStmt);
  1354. rc = sqlite3_reset(pStmt);
  1355. free(zLine);
  1356. if( rc!=SQLITE_OK ){
  1357. Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
  1358. zCommit = "ROLLBACK";
  1359. break;
  1360. }
  1361. }
  1362. free(azCol);
  1363. fclose(in);
  1364. sqlite3_finalize(pStmt);
  1365. (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
  1366. if( zCommit[0] == 'C' ){
  1367. /* success, set result as number of lines processed */
  1368. pResult = Tcl_GetObjResult(interp);
  1369. Tcl_SetIntObj(pResult, lineno);
  1370. rc = TCL_OK;
  1371. }else{
  1372. /* failure, append lineno where failed */
  1373. sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
  1374. Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
  1375. rc = TCL_ERROR;
  1376. }
  1377. break;
  1378. }
  1379. /*
  1380. ** $db enable_load_extension BOOLEAN
  1381. **
  1382. ** Turn the extension loading feature on or off. It if off by
  1383. ** default.
  1384. */
  1385. case DB_ENABLE_LOAD_EXTENSION: {
  1386. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1387. int onoff;
  1388. if( objc!=3 ){
  1389. Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
  1390. return TCL_ERROR;
  1391. }
  1392. if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
  1393. return TCL_ERROR;
  1394. }
  1395. sqlite3_enable_load_extension(pDb->db, onoff);
  1396. break;
  1397. #else
  1398. Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
  1399. 0);
  1400. return TCL_ERROR;
  1401. #endif
  1402. }
  1403. /*
  1404. ** $db errorcode
  1405. **
  1406. ** Return the numeric error code that was returned by the most recent
  1407. ** call to sqlite3_exec().
  1408. */
  1409. case DB_ERRORCODE: {
  1410. Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
  1411. break;
  1412. }
  1413. /*
  1414. ** $db eval $sql ?array? ?{ ...code... }?
  1415. ** $db onecolumn $sql
  1416. **
  1417. ** The SQL statement in $sql is evaluated. For each row, the values are
  1418. ** placed in elements of the array named "array" and ...code... is executed.
  1419. ** If "array" and "code" are omitted, then no callback is every invoked.
  1420. ** If "array" is an empty string, then the values are placed in variables
  1421. ** that have the same name as the fields extracted by the query.
  1422. **
  1423. ** The onecolumn method is the equivalent of:
  1424. ** lindex [$db eval $sql] 0
  1425. */
  1426. case DB_ONECOLUMN:
  1427. case DB_EVAL:
  1428. case DB_EXISTS: {
  1429. char const *zSql; /* Next SQL statement to execute */
  1430. char const *zLeft; /* What is left after first stmt in zSql */
  1431. sqlite3_stmt *pStmt; /* Compiled SQL statment */
  1432. Tcl_Obj *pArray; /* Name of array into which results are written */
  1433. Tcl_Obj *pScript; /* Script to run for each result set */
  1434. Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
  1435. int nParm; /* Number of entries used in apParm[] */
  1436. Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
  1437. Tcl_Obj *pRet; /* Value to be returned */
  1438. SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
  1439. int rc2;
  1440. if( choice==DB_EVAL ){
  1441. if( objc<3 || objc>5 ){
  1442. Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
  1443. return TCL_ERROR;
  1444. }
  1445. pRet = Tcl_NewObj();
  1446. Tcl_IncrRefCount(pRet);
  1447. }else{
  1448. if( objc!=3 ){
  1449. Tcl_WrongNumArgs(interp, 2, objv, "SQL");
  1450. return TCL_ERROR;
  1451. }
  1452. if( choice==DB_EXISTS ){
  1453. pRet = Tcl_NewBooleanObj(0);
  1454. Tcl_IncrRefCount(pRet);
  1455. }else{
  1456. pRet = 0;
  1457. }
  1458. }
  1459. if( objc==3 ){
  1460. pArray = pScript = 0;
  1461. }else if( objc==4 ){
  1462. pArray = 0;
  1463. pScript = objv[3];
  1464. }else{
  1465. pArray = objv[3];
  1466. if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
  1467. pScript = objv[4];
  1468. }
  1469. Tcl_IncrRefCount(objv[2]);
  1470. zSql = Tcl_GetStringFromObj(objv[2], 0);
  1471. while( rc==TCL_OK && zSql[0] ){
  1472. int i; /* Loop counter */
  1473. int nVar; /* Number of bind parameters in the pStmt */
  1474. int nCol = -1; /* Number of columns in the result set */
  1475. Tcl_Obj **apColName = 0; /* Array of column names */
  1476. int len; /* String length of zSql */
  1477. /* Try to find a SQL statement that has already been compiled and
  1478. ** which matches the next sequence of SQL.
  1479. */
  1480. pStmt = 0;
  1481. len = strlen(zSql);
  1482. for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
  1483. int n = pPreStmt->nSql;
  1484. if( len>=n
  1485. && memcmp(pPreStmt->zSql, zSql, n)==0
  1486. && (zSql[n]==0 || zSql[n-1]==';')
  1487. ){
  1488. pStmt = pPreStmt->pStmt;
  1489. zLeft = &zSql[pPreStmt->nSql];
  1490. /* When a prepared statement is found, unlink it from the
  1491. ** cache list. It will later be added back to the beginning
  1492. ** of the cache list in order to implement LRU replacement.
  1493. */
  1494. if( pPreStmt->pPrev ){
  1495. pPreStmt->pPrev->pNext = pPreStmt->pNext;
  1496. }else{
  1497. pDb->stmtList = pPreStmt->pNext;
  1498. }
  1499. if( pPreStmt->pNext ){
  1500. pPreStmt->pNext->pPrev = pPreStmt->pPrev;
  1501. }else{
  1502. pDb->stmtLast = pPreStmt->pPrev;
  1503. }
  1504. pDb->nStmt--;
  1505. break;
  1506. }
  1507. }
  1508. /* If no prepared statement was found. Compile the SQL text
  1509. */
  1510. if( pStmt==0 ){
  1511. if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, &zLeft) ){
  1512. Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
  1513. rc = TCL_ERROR;
  1514. break;
  1515. }
  1516. if( pStmt==0 ){
  1517. if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
  1518. /* A compile-time error in the statement
  1519. */
  1520. Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
  1521. rc = TCL_ERROR;
  1522. break;
  1523. }else{
  1524. /* The statement was a no-op. Continue to the next statement
  1525. ** in the SQL string.
  1526. */
  1527. zSql = zLeft;
  1528. continue;
  1529. }
  1530. }
  1531. assert( pPreStmt==0 );
  1532. }
  1533. /* Bind values to parameters that begin with $ or :
  1534. */
  1535. nVar = sqlite3_bind_parameter_count(pStmt);
  1536. nParm = 0;
  1537. if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
  1538. apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
  1539. }else{
  1540. apParm = aParm;
  1541. }
  1542. for(i=1; i<=nVar; i++){
  1543. const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
  1544. if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
  1545. Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
  1546. if( pVar ){
  1547. int n;
  1548. u8 *data;
  1549. char *zType = pVar->typePtr ? pVar->typePtr->name : "";
  1550. char c = zType[0];
  1551. if( zVar[0]=='@' ||
  1552. (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
  1553. /* Load a BLOB type if the Tcl variable is a bytearray and
  1554. ** it has no string representation or the host
  1555. ** parameter name begins with "@". */
  1556. data = Tcl_GetByteArrayFromObj(pVar, &n);
  1557. sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
  1558. Tcl_IncrRefCount(pVar);
  1559. apParm[nParm++] = pVar;
  1560. }else if( c=='b' && strcmp(zType,"boolean")==0 ){
  1561. Tcl_GetIntFromObj(interp, pVar, &n);
  1562. sqlite3_bind_int(pStmt, i, n);
  1563. }else if( c=='d' && strcmp(zType,"double")==0 ){
  1564. double r;
  1565. Tcl_GetDoubleFromObj(interp, pVar, &r);
  1566. sqlite3_bind_double(pStmt, i, r);
  1567. }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
  1568. (c=='i' && strcmp(zType,"int")==0) ){
  1569. Tcl_WideInt v;
  1570. Tcl_GetWideIntFromObj(interp, pVar, &v);
  1571. sqlite3_bind_int64(pStmt, i, v);
  1572. }else{
  1573. data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
  1574. sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
  1575. Tcl_IncrRefCount(pVar);
  1576. apParm[nParm++] = pVar;
  1577. }
  1578. }else{
  1579. sqlite3_bind_null( pStmt, i );
  1580. }
  1581. }
  1582. }
  1583. /* Execute the SQL
  1584. */
  1585. while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
  1586. /* Compute column names. This must be done after the first successful
  1587. ** call to sqlite3_step(), in case the query is recompiled and the
  1588. ** number or names of the returned columns changes.
  1589. */
  1590. assert(!pArray||pScript);
  1591. if (nCol < 0) {
  1592. Tcl_Obj ***ap = (pScript?&apColName:0);
  1593. nCol = computeColumnNames(interp, pStmt, ap, pArray);
  1594. }
  1595. for(i=0; i<nCol; i++){
  1596. Tcl_Obj *pVal;
  1597. /* Set pVal to contain the i'th column of this row. */
  1598. switch( sqlite3_column_type(pStmt, i) ){
  1599. case SQLITE_BLOB: {
  1600. int bytes = sqlite3_column_bytes(pStmt, i);
  1601. pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
  1602. break;
  1603. }
  1604. case SQLITE_INTEGER: {
  1605. sqlite_int64 v = sqlite3_column_int64(pStmt, i);
  1606. if( v>=-2147483647 && v<=2147483647 ){
  1607. pVal = Tcl_NewIntObj(v);
  1608. }else{
  1609. pVal = Tcl_NewWideIntObj(v);
  1610. }
  1611. break;
  1612. }
  1613. case SQLITE_FLOAT: {
  1614. double r = sqlite3_column_double(pStmt, i);
  1615. pVal = Tcl_NewDoubleObj(r);
  1616. break;
  1617. }
  1618. case SQLITE_NULL: {
  1619. pVal = dbTextToObj(pDb->zNull);
  1620. break;
  1621. }
  1622. default: {
  1623. pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
  1624. break;
  1625. }
  1626. }
  1627. if( pScript ){
  1628. if( pArray==0 ){
  1629. Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
  1630. }else{
  1631. Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
  1632. }
  1633. }else if( choice==DB_ONECOLUMN ){
  1634. assert( pRet==0 );
  1635. if( pRet==0 ){
  1636. pRet = pVal;
  1637. Tcl_IncrRefCount(pRet);
  1638. }
  1639. rc = TCL_BREAK;
  1640. i = nCol;
  1641. }else if( choice==DB_EXISTS ){
  1642. Tcl_DecrRefCount(pRet);
  1643. pRet = Tcl_NewBooleanObj(1);
  1644. Tcl_IncrRefCount(pRet);
  1645. rc = TCL_BREAK;
  1646. i = nCol;
  1647. }else{
  1648. Tcl_ListObjAppendElement(interp, pRet, pVal);
  1649. }
  1650. }
  1651. if( pScript ){
  1652. rc = Tcl_EvalObjEx(interp, pScript, 0);
  1653. if( rc==TCL_CONTINUE ){
  1654. rc = TCL_OK;
  1655. }
  1656. }
  1657. }
  1658. if( rc==TCL_BREAK ){
  1659. rc = TCL_OK;
  1660. }
  1661. /* Free the column name objects */
  1662. if( pScript ){
  1663. /* If the query returned no rows, but an array variable was
  1664. ** specified, call computeColumnNames() now to populate the
  1665. ** arrayname(*) variable.
  1666. */
  1667. if (pArray && nCol < 0) {
  1668. Tcl_Obj ***ap = (pScript?&apColName:0);
  1669. nCol = computeColumnNames(interp, pStmt, ap, pArray);
  1670. }
  1671. for(i=0; i<nCol; i++){
  1672. Tcl_DecrRefCount(apColName[i]);
  1673. }
  1674. Tcl_Free((char*)apColName);
  1675. }
  1676. /* Free the bound string and blob parameters */
  1677. for(i=0; i<nParm; i++){
  1678. Tcl_DecrRefCount(apParm[i]);
  1679. }
  1680. if( apParm!=aParm ){
  1681. Tcl_Free((char*)apParm);
  1682. }
  1683. /* Reset the statement. If the result code is SQLITE_SCHEMA, then
  1684. ** flush the statement cache and try the statement again.
  1685. */
  1686. rc2 = sqlite3_reset(pStmt);
  1687. if( SQLITE_OK!=rc2 ){
  1688. /* If a run-time error occurs, report the error and stop reading
  1689. ** the SQL
  1690. */
  1691. Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
  1692. sqlite3_finalize(pStmt);
  1693. rc = TCL_ERROR;
  1694. if( pPreStmt ) Tcl_Free((char*)pPreStmt);
  1695. break;
  1696. }else if( pDb->maxStmt<=0 ){
  1697. /* If the cache is turned off, deallocated the statement */
  1698. if( pPreStmt ) Tcl_Free((char*)pPreStmt);
  1699. sqlite3_finalize(pStmt);
  1700. }else{
  1701. /* Everything worked and the cache is operational.
  1702. ** Create a new SqlPreparedStmt structure if we need one.
  1703. ** (If we already have one we can just reuse it.)
  1704. */
  1705. if( pPreStmt==0 ){
  1706. len = zLeft - zSql;
  1707. pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) );
  1708. if( pPreStmt==0 ) return TCL_ERROR;
  1709. pPreStmt->pStmt = pStmt;
  1710. pPreStmt->nSql = len;
  1711. pPreStmt->zSql = sqlite3_sql(pStmt);
  1712. assert( strlen(pPreStmt->zSql)==len );
  1713. assert( 0==memcmp(pPreStmt->zSql, zSql, len) );
  1714. }
  1715. /* Add the prepared statement to the beginning of the cache list
  1716. */
  1717. pPreStmt->pNext = pDb->stmtList;
  1718. pPreStmt->pPrev = 0;
  1719. if( pDb->stmtList ){
  1720. pDb->stmtList->pPrev = pPreStmt;
  1721. }
  1722. pDb->stmtList = pPreStmt;
  1723. if( pDb->stmtLast==0 ){
  1724. assert( pDb->nStmt==0 );
  1725. pDb->stmtLast = pPreStmt;
  1726. }else{
  1727. assert( pDb->nStmt>0 );
  1728. }
  1729. pDb->nStmt++;
  1730. /* If we have too many statement in cache, remove the surplus from the
  1731. ** end of the cache list.
  1732. */
  1733. while( pDb->nStmt>pDb->maxStmt ){
  1734. sqlite3_finalize(pDb->stmtLast->pStmt);
  1735. pDb->stmtLast = pDb->stmtLast->pPrev;
  1736. Tcl_Free((char*)pDb->stmtLast->pNext);
  1737. pDb->stmtLast->pNext = 0;
  1738. pDb->nStmt--;
  1739. }
  1740. }
  1741. /* Proceed to the next statement */
  1742. zSql = zLeft;
  1743. }
  1744. Tcl_DecrRefCount(objv[2]);
  1745. if( pRet ){
  1746. if( rc==TCL_OK ){
  1747. Tcl_SetObjResult(interp, pRet);
  1748. }
  1749. Tcl_DecrRefCount(pRet);
  1750. }else if( rc==TCL_OK ){
  1751. Tcl_ResetResult(interp);
  1752. }
  1753. break;
  1754. }
  1755. /*
  1756. ** $db function NAME SCRIPT
  1757. **
  1758. ** Create a new SQL function called NAME. Whenever that function is
  1759. ** called, invoke SCRIPT to evaluate the function.
  1760. */
  1761. case DB_FUNCTION: {
  1762. SqlFunc *pFunc;
  1763. Tcl_Obj *pScript;
  1764. char *zName;
  1765. if( objc!=4 ){
  1766. Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
  1767. return TCL_ERROR;
  1768. }
  1769. zName = Tcl_GetStringFromObj(objv[2], 0);
  1770. pScript = objv[3];
  1771. pFunc = findSqlFunc(pDb, zName);
  1772. if( pFunc==0 ) return TCL_ERROR;
  1773. if( pFunc->pScript ){
  1774. Tcl_DecrRefCount(pFunc->pScript);
  1775. }
  1776. pFunc->pScript = pScript;
  1777. Tcl_IncrRefCount(pScript);
  1778. pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
  1779. rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
  1780. pFunc, tclSqlFunc, 0, 0);
  1781. if( rc!=SQLITE_OK ){
  1782. rc = TCL_ERROR;
  1783. Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
  1784. }
  1785. break;
  1786. }
  1787. /*
  1788. ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
  1789. */
  1790. case DB_INCRBLOB: {
  1791. #ifdef SQLITE_OMIT_INCRBLOB
  1792. Tcl_AppendResult(interp, "incrblob not available in this build", 0);
  1793. return TCL_ERROR;
  1794. #else
  1795. int isReadonly = 0;
  1796. const char *zDb = "main";
  1797. const char *zTable;
  1798. const char *zColumn;
  1799. sqlite_int64 iRow;
  1800. /* Check for the -readonly option */
  1801. if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
  1802. isReadonly = 1;
  1803. }
  1804. if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
  1805. Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
  1806. return TCL_ERROR;
  1807. }
  1808. if( objc==(6+isReadonly) ){
  1809. zDb = Tcl_GetString(objv[2]);
  1810. }
  1811. zTable = Tcl_GetString(objv[objc-3]);
  1812. zColumn = Tcl_GetString(objv[objc-2]);
  1813. rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
  1814. if( rc==TCL_OK ){
  1815. rc = createIncrblobChannel(
  1816. interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
  1817. );
  1818. }
  1819. #endif
  1820. break;
  1821. }
  1822. /*
  1823. ** $db interrupt
  1824. **
  1825. ** Interrupt the execution of the inner-most SQL interpreter. This
  1826. ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
  1827. */
  1828. case DB_INTERRUPT: {
  1829. sqlite3_interrupt(pDb->db);
  1830. break;
  1831. }
  1832. /*
  1833. ** $db nullvalue ?STRING?
  1834. **
  1835. ** Change text used when a NULL comes back from the database. If ?STRING?
  1836. ** is not present, then the current string used for NULL is returned.
  1837. ** If STRING is present, then STRING is returned.
  1838. **
  1839. */
  1840. case DB_NULLVALUE: {
  1841. if( objc!=2 && objc!=3 ){
  1842. Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
  1843. return TCL_ERROR;
  1844. }
  1845. if( objc==3 ){
  1846. int len;
  1847. char *zNull = Tcl_GetStringFromObj(objv[2], &len);
  1848. if( pDb->zNull ){
  1849. Tcl_Free(pDb->zNull);
  1850. }
  1851. if( zNull && len>0 ){
  1852. pDb->zNull = Tcl_Alloc( len + 1 );
  1853. strncpy(pDb->zNull, zNull, len);
  1854. pDb->zNull[len] = '\0';
  1855. }else{
  1856. pDb->zNull = 0;
  1857. }
  1858. }
  1859. Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
  1860. break;
  1861. }
  1862. /*
  1863. ** $db last_insert_rowid
  1864. **
  1865. ** Return an integer which is the ROWID for the most recent insert.
  1866. */
  1867. case DB_LAST_INSERT_ROWID: {
  1868. Tcl_Obj *pResult;
  1869. Tcl_WideInt rowid;
  1870. if( objc!=2 ){
  1871. Tcl_WrongNumArgs(interp, 2, objv, "");
  1872. return TCL_ERROR;
  1873. }
  1874. rowid = sqlite3_last_insert_rowid(pDb->db);
  1875. pResult = Tcl_GetObjResult(interp);
  1876. Tcl_SetWideIntObj(pResult, rowid);
  1877. break;
  1878. }
  1879. /*
  1880. ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
  1881. */
  1882. /* $db progress ?N CALLBACK?
  1883. **
  1884. ** Invoke the given callback every N virtual machine opcodes while executing
  1885. ** queries.
  1886. */
  1887. case DB_PROGRESS: {
  1888. if( objc==2 ){
  1889. if( pDb->zProgress ){
  1890. Tcl_AppendResult(interp, pDb->zProgress, 0);
  1891. }
  1892. }else if( objc==4 ){
  1893. char *zProgress;
  1894. int len;
  1895. int N;
  1896. if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
  1897. return TCL_ERROR;
  1898. };
  1899. if( pDb->zProgress ){
  1900. Tcl_Free(pDb->zProgress);
  1901. }
  1902. zProgress = Tcl_GetStringFromObj(objv[3], &len);
  1903. if( zProgress && len>0 ){
  1904. pDb->zProgress = Tcl_Alloc( len + 1 );
  1905. memcpy(pDb->zProgress, zProgress, len+1);
  1906. }else{
  1907. pDb->zProgress = 0;
  1908. }
  1909. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  1910. if( pDb->zProgress ){
  1911. pDb->interp = interp;
  1912. sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
  1913. }else{
  1914. sqlite3_progress_handler(pDb->db, 0, 0, 0);
  1915. }
  1916. #endif
  1917. }else{
  1918. Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
  1919. return TCL_ERROR;
  1920. }
  1921. break;
  1922. }
  1923. /* $db profile ?CALLBACK?
  1924. **
  1925. ** Make arrangements to invoke the CALLBACK routine after each SQL statement
  1926. ** that has run. The text of the SQL and the amount of elapse time are
  1927. ** appended to CALLBACK before the script is run.
  1928. */
  1929. case DB_PROFILE: {
  1930. if( objc>3 ){
  1931. Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
  1932. return TCL_ERROR;
  1933. }else if( objc==2 ){
  1934. if( pDb->zProfile ){
  1935. Tcl_AppendResult(interp, pDb->zProfile, 0);
  1936. }
  1937. }else{
  1938. char *zProfile;
  1939. int len;
  1940. if( pDb->zProfile ){
  1941. Tcl_Free(pDb->zProfile);
  1942. }
  1943. zProfile = Tcl_GetStringFromObj(objv[2], &len);
  1944. if( zProfile && len>0 ){
  1945. pDb->zProfile = Tcl_Alloc( len + 1 );
  1946. memcpy(pDb->zProfile, zProfile, len+1);
  1947. }else{
  1948. pDb->zProfile = 0;
  1949. }
  1950. #ifndef SQLITE_OMIT_TRACE
  1951. if( pDb->zProfile ){
  1952. pDb->interp = interp;
  1953. sqlite3_profile(pDb->db, DbProfileHandler, pDb);
  1954. }else{
  1955. sqlite3_profile(pDb->db, 0, 0);
  1956. }
  1957. #endif
  1958. }
  1959. break;
  1960. }
  1961. /*
  1962. ** $db rekey KEY
  1963. **
  1964. ** Change the encryption key on the currently open database.
  1965. */
  1966. case DB_REKEY: {
  1967. int nKey;
  1968. void *pKey;
  1969. if( objc!=3 ){
  1970. Tcl_WrongNumArgs(interp, 2, objv, "KEY");
  1971. return TCL_ERROR;
  1972. }
  1973. pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
  1974. #ifdef SQLITE_HAS_CODEC
  1975. rc = sqlite3_rekey(pDb->db, pKey, nKey);
  1976. if( rc ){
  1977. Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
  1978. rc = TCL_ERROR;
  1979. }
  1980. #endif
  1981. break;
  1982. }
  1983. /*
  1984. ** $db timeout MILLESECONDS
  1985. **
  1986. ** Delay for the number of milliseconds specified when a file is locked.
  1987. */
  1988. case DB_TIMEOUT: {
  1989. int ms;
  1990. if( objc!=3 ){
  1991. Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
  1992. return TCL_ERROR;
  1993. }
  1994. if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
  1995. sqlite3_busy_timeout(pDb->db, ms);
  1996. break;
  1997. }
  1998. /*
  1999. ** $db total_changes
  2000. **
  2001. ** Return the number of rows that were modified, inserted, or deleted
  2002. ** since the database handle was created.
  2003. */
  2004. case DB_TOTAL_CHANGES: {
  2005. Tcl_Obj *pResult;
  2006. if( objc!=2 ){
  2007. Tcl_WrongNumArgs(interp, 2, objv, "");
  2008. return TCL_ERROR;
  2009. }
  2010. pResult = Tcl_GetObjResult(interp);
  2011. Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
  2012. break;
  2013. }
  2014. /* $db trace ?CALLBACK?
  2015. **
  2016. ** Make arrangements to invoke the CALLBACK routine for each SQL statement
  2017. ** that is executed. The text of the SQL is appended to CALLBACK before
  2018. ** it is executed.
  2019. */
  2020. case DB_TRACE: {
  2021. if( objc>3 ){
  2022. Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
  2023. return TCL_ERROR;
  2024. }else if( objc==2 ){
  2025. if( pDb->zTrace ){
  2026. Tcl_AppendResult(interp, pDb->zTrace, 0);
  2027. }
  2028. }else{
  2029. char *zTrace;
  2030. int len;
  2031. if( pDb->zTrace ){
  2032. Tcl_Free(pDb->zTrace);
  2033. }
  2034. zTrace = Tcl_GetStringFromObj(objv[2], &len);
  2035. if( zTrace && len>0 ){
  2036. pDb->zTrace = Tcl_Alloc( len + 1 );
  2037. memcpy(pDb->zTrace, zTrace, len+1);
  2038. }else{
  2039. pDb->zTrace = 0;
  2040. }
  2041. #ifndef SQLITE_OMIT_TRACE
  2042. if( pDb->zTrace ){
  2043. pDb->interp = interp;
  2044. sqlite3_trace(pDb->db, DbTraceHandler, pDb);
  2045. }else{
  2046. sqlite3_trace(pDb->db, 0, 0);
  2047. }
  2048. #endif
  2049. }
  2050. break;
  2051. }
  2052. /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
  2053. **
  2054. ** Start a new transaction (if we are not already in the midst of a
  2055. ** transaction) and execute the TCL script SCRIPT. After SCRIPT
  2056. ** completes, either commit the transaction or roll it back if SCRIPT
  2057. ** throws an exception. Or if no new transation was started, do nothing.
  2058. ** pass the exception on up the stack.
  2059. **
  2060. ** This command was inspired by Dave Thomas's talk on Ruby at the
  2061. ** 2005 O'Reilly Open Source Convention (OSCON).
  2062. */
  2063. case DB_TRANSACTION: {
  2064. int inTrans;
  2065. Tcl_Obj *pScript;
  2066. const char *zBegin = "BEGIN";
  2067. if( objc!=3 && objc!=4 ){
  2068. Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
  2069. return TCL_ERROR;
  2070. }
  2071. if( objc==3 ){
  2072. pScript = objv[2];
  2073. } else {
  2074. static const char *TTYPE_strs[] = {
  2075. "deferred", "exclusive", "immediate", 0
  2076. };
  2077. enum TTYPE_enum {
  2078. TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
  2079. };
  2080. int ttype;
  2081. if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
  2082. 0, &ttype) ){
  2083. return TCL_ERROR;
  2084. }
  2085. switch( (enum TTYPE_enum)ttype ){
  2086. case TTYPE_DEFERRED: /* no-op */; break;
  2087. case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
  2088. case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
  2089. }
  2090. pScript = objv[3];
  2091. }
  2092. inTrans = !sqlite3_get_autocommit(pDb->db);
  2093. if( !inTrans ){
  2094. (void)sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
  2095. }
  2096. rc = Tcl_EvalObjEx(interp, pScript, 0);
  2097. if( !inTrans ){
  2098. const char *zEnd;
  2099. if( rc==TCL_ERROR ){
  2100. zEnd = "ROLLBACK";
  2101. } else {
  2102. zEnd = "COMMIT";
  2103. }
  2104. if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
  2105. sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
  2106. }
  2107. }
  2108. break;
  2109. }
  2110. /*
  2111. ** $db update_hook ?script?
  2112. ** $db rollback_hook ?script?
  2113. */
  2114. case DB_UPDATE_HOOK:
  2115. case DB_ROLLBACK_HOOK: {
  2116. /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
  2117. ** whether [$db update_hook] or [$db rollback_hook] was invoked.
  2118. */
  2119. Tcl_Obj **ppHook;
  2120. if( choice==DB_UPDATE_HOOK ){
  2121. ppHook = &pDb->pUpdateHook;
  2122. }else{
  2123. ppHook = &pDb->pRollbackHook;
  2124. }
  2125. if( objc!=2 && objc!=3 ){
  2126. Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
  2127. return TCL_ERROR;
  2128. }
  2129. if( *ppHook ){
  2130. Tcl_SetObjResult(interp, *ppHook);
  2131. if( objc==3 ){
  2132. Tcl_DecrRefCount(*ppHook);
  2133. *ppHook = 0;
  2134. }
  2135. }
  2136. if( objc==3 ){
  2137. assert( !(*ppHook) );
  2138. if( Tcl_GetCharLength(objv[2])>0 ){
  2139. *ppHook = objv[2];
  2140. Tcl_IncrRefCount(*ppHook);
  2141. }
  2142. }
  2143. sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
  2144. sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
  2145. break;
  2146. }
  2147. /* $db version
  2148. **
  2149. ** Return the version string for this database.
  2150. */
  2151. case DB_VERSION: {
  2152. Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
  2153. break;
  2154. }
  2155. } /* End of the SWITCH statement */
  2156. return rc;
  2157. }
  2158. /*
  2159. ** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
  2160. ** ?-create BOOLEAN?
  2161. **
  2162. ** This is the main Tcl command. When the "sqlite" Tcl command is
  2163. ** invoked, this routine runs to process that command.
  2164. **
  2165. ** The first argument, DBNAME, is an arbitrary name for a new
  2166. ** database connection. This command creates a new command named
  2167. ** DBNAME that is used to control that connection. The database
  2168. ** connection is deleted when the DBNAME command is deleted.
  2169. **
  2170. ** The second argument is the name of the database file.
  2171. **
  2172. */
  2173. static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
  2174. SqliteDb *p;
  2175. void *pKey = 0;
  2176. int nKey = 0;
  2177. const char *zArg;
  2178. char *zErrMsg;
  2179. int i;
  2180. const char *zFile;
  2181. const char *zVfs = 0;
  2182. int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
  2183. Tcl_DString translatedFilename;
  2184. if( objc==2 ){
  2185. zArg = Tcl_GetStringFromObj(objv[1], 0);
  2186. if( strcmp(zArg,"-version")==0 ){
  2187. Tcl_AppendResult(interp,sqlite3_version,0);
  2188. return TCL_OK;
  2189. }
  2190. if( strcmp(zArg,"-has-codec")==0 ){
  2191. #ifdef SQLITE_HAS_CODEC
  2192. Tcl_AppendResult(interp,"1",0);
  2193. #else
  2194. Tcl_AppendResult(interp,"0",0);
  2195. #endif
  2196. return TCL_OK;
  2197. }
  2198. }
  2199. for(i=3; i+1<objc; i+=2){
  2200. zArg = Tcl_GetString(objv[i]);
  2201. if( strcmp(zArg,"-key")==0 ){
  2202. pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
  2203. }else if( strcmp(zArg, "-vfs")==0 ){
  2204. i++;
  2205. zVfs = Tcl_GetString(objv[i]);
  2206. }else if( strcmp(zArg, "-readonly")==0 ){
  2207. int b;
  2208. if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
  2209. if( b ){
  2210. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  2211. flags |= SQLITE_OPEN_READONLY;
  2212. }else{
  2213. flags &= ~SQLITE_OPEN_READONLY;
  2214. flags |= SQLITE_OPEN_READWRITE;
  2215. }
  2216. }else if( strcmp(zArg, "-create")==0 ){
  2217. int b;
  2218. if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
  2219. if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
  2220. flags |= SQLITE_OPEN_CREATE;
  2221. }else{
  2222. flags &= ~SQLITE_OPEN_CREATE;
  2223. }
  2224. }else{
  2225. Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
  2226. return TCL_ERROR;
  2227. }
  2228. }
  2229. if( objc<3 || (objc&1)!=1 ){
  2230. Tcl_WrongNumArgs(interp, 1, objv,
  2231. "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
  2232. #ifdef SQLITE_HAS_CODEC
  2233. " ?-key CODECKEY?"
  2234. #endif
  2235. );
  2236. return TCL_ERROR;
  2237. }
  2238. zErrMsg = 0;
  2239. p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
  2240. if( p==0 ){
  2241. Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
  2242. return TCL_ERROR;
  2243. }
  2244. memset(p, 0, sizeof(*p));
  2245. zFile = Tcl_GetStringFromObj(objv[2], 0);
  2246. zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
  2247. sqlite3_open_v2(zFile, &p->db, flags, zVfs);
  2248. Tcl_DStringFree(&translatedFilename);
  2249. if( SQLITE_OK!=sqlite3_errcode(p->db) ){
  2250. zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
  2251. sqlite3_close(p->db);
  2252. p->db = 0;
  2253. }
  2254. #ifdef SQLITE_TEST
  2255. if( p->db ){
  2256. extern int Md5_Register(sqlite3*);
  2257. if( Md5_Register(p->db)==SQLITE_NOMEM ){
  2258. zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
  2259. sqlite3_close(p->db);
  2260. p->db = 0;
  2261. }
  2262. }
  2263. #endif
  2264. #ifdef SQLITE_HAS_CODEC
  2265. if( p->db ){
  2266. sqlite3_key(p->db, pKey, nKey);
  2267. }
  2268. #endif
  2269. if( p->db==0 ){
  2270. Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
  2271. Tcl_Free((char*)p);
  2272. sqlite3_free(zErrMsg);
  2273. return TCL_ERROR;
  2274. }
  2275. p->maxStmt = NUM_PREPARED_STMTS;
  2276. p->interp = interp;
  2277. zArg = Tcl_GetStringFromObj(objv[1], 0);
  2278. Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
  2279. return TCL_OK;
  2280. }
  2281. /*
  2282. ** Provide a dummy Tcl_InitStubs if we are using this as a static
  2283. ** library.
  2284. */
  2285. #ifndef USE_TCL_STUBS
  2286. # undef Tcl_InitStubs
  2287. # define Tcl_InitStubs(a,b,c)
  2288. #endif
  2289. /*
  2290. ** Make sure we have a PACKAGE_VERSION macro defined. This will be
  2291. ** defined automatically by the TEA makefile. But other makefiles
  2292. ** do not define it.
  2293. */
  2294. #ifndef PACKAGE_VERSION
  2295. # define PACKAGE_VERSION SQLITE_VERSION
  2296. #endif
  2297. /*
  2298. ** Initialize this module.
  2299. **
  2300. ** This Tcl module contains only a single new Tcl command named "sqlite".
  2301. ** (Hence there is no namespace. There is no point in using a namespace
  2302. ** if the extension only supplies one new name!) The "sqlite" command is
  2303. ** used to open a new SQLite database. See the DbMain() routine above
  2304. ** for additional information.
  2305. */
  2306. EXTERN int Sqlite3_Init(Tcl_Interp *interp){
  2307. Tcl_InitStubs(interp, "8.4", 0);
  2308. Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
  2309. Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
  2310. Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
  2311. Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
  2312. return TCL_OK;
  2313. }
  2314. EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
  2315. EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
  2316. EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
  2317. #ifndef SQLITE_3_SUFFIX_ONLY
  2318. EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
  2319. EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
  2320. EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
  2321. EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
  2322. #endif
  2323. #ifdef TCLSH
  2324. /*****************************************************************************
  2325. ** The code that follows is used to build standalone TCL interpreters
  2326. ** that are statically linked with SQLite.
  2327. */
  2328. /*
  2329. ** If the macro TCLSH is one, then put in code this for the
  2330. ** "main" routine that will initialize Tcl and take input from
  2331. ** standard input, or if a file is named on the command line
  2332. ** the TCL interpreter reads and evaluates that file.
  2333. */
  2334. #if TCLSH==1
  2335. static char zMainloop[] =
  2336. "set line {}\n"
  2337. "while {![eof stdin]} {\n"
  2338. "if {$line!=\"\"} {\n"
  2339. "puts -nonewline \"> \"\n"
  2340. "} else {\n"
  2341. "puts -nonewline \"% \"\n"
  2342. "}\n"
  2343. "flush stdout\n"
  2344. "append line [gets stdin]\n"
  2345. "if {[info complete $line]} {\n"
  2346. "if {[catch {uplevel #0 $line} result]} {\n"
  2347. "puts stderr \"Error: $result\"\n"
  2348. "} elseif {$result!=\"\"} {\n"
  2349. "puts $result\n"
  2350. "}\n"
  2351. "set line {}\n"
  2352. "} else {\n"
  2353. "append line \\n\n"
  2354. "}\n"
  2355. "}\n"
  2356. ;
  2357. #endif
  2358. /*
  2359. ** If the macro TCLSH is two, then get the main loop code out of
  2360. ** the separate file "spaceanal_tcl.h".
  2361. */
  2362. #if TCLSH==2
  2363. static char zMainloop[] =
  2364. #include "spaceanal_tcl.h"
  2365. ;
  2366. #endif
  2367. #define TCLSH_MAIN main /* Needed to fake out mktclapp */
  2368. int TCLSH_MAIN(int argc, char **argv){
  2369. Tcl_Interp *interp;
  2370. Tcl_FindExecutable(argv[0]);
  2371. interp = Tcl_CreateInterp();
  2372. Sqlite3_Init(interp);
  2373. #ifdef SQLITE_TEST
  2374. {
  2375. extern int Md5_Init(Tcl_Interp*);
  2376. extern int Sqliteconfig_Init(Tcl_Interp*);
  2377. extern int Sqlitetest1_Init(Tcl_Interp*);
  2378. extern int Sqlitetest2_Init(Tcl_Interp*);
  2379. extern int Sqlitetest3_Init(Tcl_Interp*);
  2380. extern int Sqlitetest4_Init(Tcl_Interp*);
  2381. extern int Sqlitetest5_Init(Tcl_Interp*);
  2382. extern int Sqlitetest6_Init(Tcl_Interp*);
  2383. extern int Sqlitetest7_Init(Tcl_Interp*);
  2384. extern int Sqlitetest8_Init(Tcl_Interp*);
  2385. extern int Sqlitetest9_Init(Tcl_Interp*);
  2386. extern int Sqlitetestasync_Init(Tcl_Interp*);
  2387. extern int Sqlitetest_autoext_Init(Tcl_Interp*);
  2388. extern int Sqlitetest_hexio_Init(Tcl_Interp*);
  2389. extern int Sqlitetest_malloc_Init(Tcl_Interp*);
  2390. extern int Sqlitetestschema_Init(Tcl_Interp*);
  2391. extern int Sqlitetestsse_Init(Tcl_Interp*);
  2392. extern int Sqlitetesttclvar_Init(Tcl_Interp*);
  2393. extern int SqlitetestThread_Init(Tcl_Interp*);
  2394. extern int SqlitetestOnefile_Init();
  2395. Md5_Init(interp);
  2396. Sqliteconfig_Init(interp);
  2397. Sqlitetest1_Init(interp);
  2398. Sqlitetest2_Init(interp);
  2399. Sqlitetest3_Init(interp);
  2400. Sqlitetest4_Init(interp);
  2401. Sqlitetest5_Init(interp);
  2402. Sqlitetest6_Init(interp);
  2403. Sqlitetest7_Init(interp);
  2404. Sqlitetest8_Init(interp);
  2405. Sqlitetest9_Init(interp);
  2406. Sqlitetestasync_Init(interp);
  2407. Sqlitetest_autoext_Init(interp);
  2408. Sqlitetest_hexio_Init(interp);
  2409. Sqlitetest_malloc_Init(interp);
  2410. Sqlitetestschema_Init(interp);
  2411. Sqlitetesttclvar_Init(interp);
  2412. SqlitetestThread_Init(interp);
  2413. SqlitetestOnefile_Init(interp);
  2414. #ifdef SQLITE_SSE
  2415. Sqlitetestsse_Init(interp);
  2416. #endif
  2417. }
  2418. #endif
  2419. if( argc>=2 || TCLSH==2 ){
  2420. int i;
  2421. char zArgc[32];
  2422. sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
  2423. Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
  2424. Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
  2425. Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
  2426. for(i=3-TCLSH; i<argc; i++){
  2427. Tcl_SetVar(interp, "argv", argv[i],
  2428. TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
  2429. }
  2430. if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
  2431. const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
  2432. if( zInfo==0 ) zInfo = interp->result;
  2433. fprintf(stderr,"%s: %s\n", *argv, zInfo);
  2434. return 1;
  2435. }
  2436. }
  2437. if( argc<=1 || TCLSH==2 ){
  2438. Tcl_GlobalEval(interp, zMainloop);
  2439. }
  2440. return 0;
  2441. }
  2442. #endif /* TCLSH */