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