PageRenderTime 55ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/python-build/sqlite3/shell.c

https://code.google.com/p/android-scripting/
C | 3569 lines | 2889 code | 227 blank | 453 comment | 587 complexity | 58856190d8e975d76e3605bc1504c6f9 MD5 | raw file
Possible License(s): GPL-3.0, 0BSD, GPL-2.0, Apache-2.0, LGPL-3.0, AGPL-1.0, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. ** 2001 September 15
  3. **
  4. ** The author disclaims copyright to this source code. In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. ** May you do good and not evil.
  8. ** May you find forgiveness for yourself and forgive others.
  9. ** May you share freely, never taking more than you give.
  10. **
  11. *************************************************************************
  12. ** This file contains code to implement the "sqlite" command line
  13. ** utility for accessing SQLite databases.
  14. */
  15. #if defined(_WIN32) || defined(WIN32)
  16. /* This needs to come before any includes for MSVC compiler */
  17. #define _CRT_SECURE_NO_WARNINGS
  18. #endif
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <stdio.h>
  22. #include <assert.h>
  23. #include "sqlite3.h"
  24. #include <ctype.h>
  25. #include <stdarg.h>
  26. #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__)
  27. # include <signal.h>
  28. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  29. # include <pwd.h>
  30. # endif
  31. # include <unistd.h>
  32. # include <sys/types.h>
  33. #endif
  34. #ifdef __OS2__
  35. # include <unistd.h>
  36. #endif
  37. #if defined(HAVE_READLINE) && HAVE_READLINE==1
  38. # include <readline/readline.h>
  39. # include <readline/history.h>
  40. #else
  41. # define readline(p) local_getline(p,stdin)
  42. # define add_history(X)
  43. # define read_history(X)
  44. # define write_history(X)
  45. # define stifle_history(X)
  46. #endif
  47. #if defined(_WIN32) || defined(WIN32)
  48. # include <io.h>
  49. #define isatty(h) _isatty(h)
  50. #define access(f,m) _access((f),(m))
  51. #else
  52. /* Make sure isatty() has a prototype.
  53. */
  54. extern int isatty();
  55. #endif
  56. #if defined(_WIN32_WCE)
  57. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
  58. * thus we always assume that we have a console. That can be
  59. * overridden with the -batch command line option.
  60. */
  61. #define isatty(x) 1
  62. #endif
  63. #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(__RTP__) && !defined(_WRS_KERNEL)
  64. #include <sys/time.h>
  65. #include <sys/resource.h>
  66. /* Saved resource information for the beginning of an operation */
  67. static struct rusage sBegin;
  68. /* True if the timer is enabled */
  69. static int enableTimer = 0;
  70. /*
  71. ** Begin timing an operation
  72. */
  73. static void beginTimer(void){
  74. if( enableTimer ){
  75. getrusage(RUSAGE_SELF, &sBegin);
  76. }
  77. }
  78. /* Return the difference of two time_structs in seconds */
  79. static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  80. return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
  81. (double)(pEnd->tv_sec - pStart->tv_sec);
  82. }
  83. /*
  84. ** Print the timing results.
  85. */
  86. static void endTimer(void){
  87. if( enableTimer ){
  88. struct rusage sEnd;
  89. getrusage(RUSAGE_SELF, &sEnd);
  90. printf("CPU Time: user %f sys %f\n",
  91. timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
  92. timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  93. }
  94. }
  95. #define BEGIN_TIMER beginTimer()
  96. #define END_TIMER endTimer()
  97. #define HAS_TIMER 1
  98. #elif (defined(_WIN32) || defined(WIN32))
  99. #include <windows.h>
  100. /* Saved resource information for the beginning of an operation */
  101. static HANDLE hProcess;
  102. static FILETIME ftKernelBegin;
  103. static FILETIME ftUserBegin;
  104. typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME);
  105. static GETPROCTIMES getProcessTimesAddr = NULL;
  106. /* True if the timer is enabled */
  107. static int enableTimer = 0;
  108. /*
  109. ** Check to see if we have timer support. Return 1 if necessary
  110. ** support found (or found previously).
  111. */
  112. static int hasTimer(void){
  113. if( getProcessTimesAddr ){
  114. return 1;
  115. } else {
  116. /* GetProcessTimes() isn't supported in WIN95 and some other Windows versions.
  117. ** See if the version we are running on has it, and if it does, save off
  118. ** a pointer to it and the current process handle.
  119. */
  120. hProcess = GetCurrentProcess();
  121. if( hProcess ){
  122. HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
  123. if( NULL != hinstLib ){
  124. getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
  125. if( NULL != getProcessTimesAddr ){
  126. return 1;
  127. }
  128. FreeLibrary(hinstLib);
  129. }
  130. }
  131. }
  132. return 0;
  133. }
  134. /*
  135. ** Begin timing an operation
  136. */
  137. static void beginTimer(void){
  138. if( enableTimer && getProcessTimesAddr ){
  139. FILETIME ftCreation, ftExit;
  140. getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin);
  141. }
  142. }
  143. /* Return the difference of two FILETIME structs in seconds */
  144. static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
  145. sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
  146. sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
  147. return (double) ((i64End - i64Start) / 10000000.0);
  148. }
  149. /*
  150. ** Print the timing results.
  151. */
  152. static void endTimer(void){
  153. if( enableTimer && getProcessTimesAddr){
  154. FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
  155. getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd);
  156. printf("CPU Time: user %f sys %f\n",
  157. timeDiff(&ftUserBegin, &ftUserEnd),
  158. timeDiff(&ftKernelBegin, &ftKernelEnd));
  159. }
  160. }
  161. #define BEGIN_TIMER beginTimer()
  162. #define END_TIMER endTimer()
  163. #define HAS_TIMER hasTimer()
  164. #else
  165. #define BEGIN_TIMER
  166. #define END_TIMER
  167. #define HAS_TIMER 0
  168. #endif
  169. /*
  170. ** Used to prevent warnings about unused parameters
  171. */
  172. #define UNUSED_PARAMETER(x) (void)(x)
  173. /**************************************************************************
  174. ***************************************************************************
  175. ** Begin genfkey logic.
  176. */
  177. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined SQLITE_OMIT_SUBQUERY
  178. #define GENFKEY_ERROR 1
  179. #define GENFKEY_DROPTRIGGER 2
  180. #define GENFKEY_CREATETRIGGER 3
  181. static int genfkey_create_triggers(sqlite3 *, const char *, void *,
  182. int (*)(void *, int, const char *)
  183. );
  184. struct GenfkeyCb {
  185. void *pCtx;
  186. int eType;
  187. int (*xData)(void *, int, const char *);
  188. };
  189. typedef struct GenfkeyCb GenfkeyCb;
  190. /* The code in this file defines a sqlite3 virtual-table module that
  191. ** provides a read-only view of the current database schema. There is one
  192. ** row in the schema table for each column in the database schema.
  193. */
  194. #define SCHEMA \
  195. "CREATE TABLE x(" \
  196. "database," /* Name of database (i.e. main, temp etc.) */ \
  197. "tablename," /* Name of table */ \
  198. "cid," /* Column number (from left-to-right, 0 upward) */ \
  199. "name," /* Column name */ \
  200. "type," /* Specified type (i.e. VARCHAR(32)) */ \
  201. "not_null," /* Boolean. True if NOT NULL was specified */ \
  202. "dflt_value," /* Default value for this column */ \
  203. "pk" /* True if this column is part of the primary key */ \
  204. ")"
  205. #define SCHEMA2 \
  206. "CREATE TABLE x(" \
  207. "database," /* Name of database (i.e. main, temp etc.) */ \
  208. "from_tbl," /* Name of table */ \
  209. "fkid," \
  210. "seq," \
  211. "to_tbl," \
  212. "from_col," \
  213. "to_col," \
  214. "on_update," \
  215. "on_delete," \
  216. "match" \
  217. ")"
  218. #define SCHEMA3 \
  219. "CREATE TABLE x(" \
  220. "database," /* Name of database (i.e. main, temp etc.) */ \
  221. "tablename," /* Name of table */ \
  222. "seq," \
  223. "name," \
  224. "isunique" \
  225. ")"
  226. #define SCHEMA4 \
  227. "CREATE TABLE x(" \
  228. "database," /* Name of database (i.e. main, temp etc.) */ \
  229. "indexname," /* Name of table */ \
  230. "seqno," \
  231. "cid," \
  232. "name" \
  233. ")"
  234. #define SCHEMA5 \
  235. "CREATE TABLE x(" \
  236. "database," /* Name of database (i.e. main, temp etc.) */ \
  237. "triggername," /* Name of trigger */ \
  238. "dummy" /* Unused */ \
  239. ")"
  240. typedef struct SchemaTable SchemaTable;
  241. static struct SchemaTable {
  242. const char *zName;
  243. const char *zObject;
  244. const char *zPragma;
  245. const char *zSchema;
  246. } aSchemaTable[] = {
  247. { "table_info", "table", "PRAGMA %Q.table_info(%Q)", SCHEMA },
  248. { "foreign_key_list", "table", "PRAGMA %Q.foreign_key_list(%Q)", SCHEMA2 },
  249. { "index_list", "table", "PRAGMA %Q.index_list(%Q)", SCHEMA3 },
  250. { "index_info", "index", "PRAGMA %Q.index_info(%Q)", SCHEMA4 },
  251. { "trigger_list", "trigger", "SELECT 1", SCHEMA5 },
  252. { 0, 0, 0, 0 }
  253. };
  254. typedef struct schema_vtab schema_vtab;
  255. typedef struct schema_cursor schema_cursor;
  256. /* A schema table object */
  257. struct schema_vtab {
  258. sqlite3_vtab base;
  259. sqlite3 *db;
  260. SchemaTable *pType;
  261. };
  262. /* A schema table cursor object */
  263. struct schema_cursor {
  264. sqlite3_vtab_cursor base;
  265. sqlite3_stmt *pDbList;
  266. sqlite3_stmt *pTableList;
  267. sqlite3_stmt *pColumnList;
  268. int rowid;
  269. };
  270. /*
  271. ** Table destructor for the schema module.
  272. */
  273. static int schemaDestroy(sqlite3_vtab *pVtab){
  274. sqlite3_free(pVtab);
  275. return 0;
  276. }
  277. /*
  278. ** Table constructor for the schema module.
  279. */
  280. static int schemaCreate(
  281. sqlite3 *db,
  282. void *pAux,
  283. int argc, const char *const*argv,
  284. sqlite3_vtab **ppVtab,
  285. char **pzErr
  286. ){
  287. int rc = SQLITE_NOMEM;
  288. schema_vtab *pVtab;
  289. SchemaTable *pType = &aSchemaTable[0];
  290. UNUSED_PARAMETER(pzErr);
  291. if( argc>3 ){
  292. int i;
  293. pType = 0;
  294. for(i=0; aSchemaTable[i].zName; i++){
  295. if( 0==strcmp(argv[3], aSchemaTable[i].zName) ){
  296. pType = &aSchemaTable[i];
  297. }
  298. }
  299. if( !pType ){
  300. return SQLITE_ERROR;
  301. }
  302. }
  303. pVtab = sqlite3_malloc(sizeof(schema_vtab));
  304. if( pVtab ){
  305. memset(pVtab, 0, sizeof(schema_vtab));
  306. pVtab->db = (sqlite3 *)pAux;
  307. pVtab->pType = pType;
  308. rc = sqlite3_declare_vtab(db, pType->zSchema);
  309. }
  310. *ppVtab = (sqlite3_vtab *)pVtab;
  311. return rc;
  312. }
  313. /*
  314. ** Open a new cursor on the schema table.
  315. */
  316. static int schemaOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  317. int rc = SQLITE_NOMEM;
  318. schema_cursor *pCur;
  319. UNUSED_PARAMETER(pVTab);
  320. pCur = sqlite3_malloc(sizeof(schema_cursor));
  321. if( pCur ){
  322. memset(pCur, 0, sizeof(schema_cursor));
  323. *ppCursor = (sqlite3_vtab_cursor *)pCur;
  324. rc = SQLITE_OK;
  325. }
  326. return rc;
  327. }
  328. /*
  329. ** Close a schema table cursor.
  330. */
  331. static int schemaClose(sqlite3_vtab_cursor *cur){
  332. schema_cursor *pCur = (schema_cursor *)cur;
  333. sqlite3_finalize(pCur->pDbList);
  334. sqlite3_finalize(pCur->pTableList);
  335. sqlite3_finalize(pCur->pColumnList);
  336. sqlite3_free(pCur);
  337. return SQLITE_OK;
  338. }
  339. static void columnToResult(sqlite3_context *ctx, sqlite3_stmt *pStmt, int iCol){
  340. switch( sqlite3_column_type(pStmt, iCol) ){
  341. case SQLITE_NULL:
  342. sqlite3_result_null(ctx);
  343. break;
  344. case SQLITE_INTEGER:
  345. sqlite3_result_int64(ctx, sqlite3_column_int64(pStmt, iCol));
  346. break;
  347. case SQLITE_FLOAT:
  348. sqlite3_result_double(ctx, sqlite3_column_double(pStmt, iCol));
  349. break;
  350. case SQLITE_TEXT: {
  351. const char *z = (const char *)sqlite3_column_text(pStmt, iCol);
  352. sqlite3_result_text(ctx, z, -1, SQLITE_TRANSIENT);
  353. break;
  354. }
  355. }
  356. }
  357. /*
  358. ** Retrieve a column of data.
  359. */
  360. static int schemaColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  361. schema_cursor *pCur = (schema_cursor *)cur;
  362. switch( i ){
  363. case 0:
  364. columnToResult(ctx, pCur->pDbList, 1);
  365. break;
  366. case 1:
  367. columnToResult(ctx, pCur->pTableList, 0);
  368. break;
  369. default:
  370. columnToResult(ctx, pCur->pColumnList, i-2);
  371. break;
  372. }
  373. return SQLITE_OK;
  374. }
  375. /*
  376. ** Retrieve the current rowid.
  377. */
  378. static int schemaRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  379. schema_cursor *pCur = (schema_cursor *)cur;
  380. *pRowid = pCur->rowid;
  381. return SQLITE_OK;
  382. }
  383. static int finalize(sqlite3_stmt **ppStmt){
  384. int rc = sqlite3_finalize(*ppStmt);
  385. *ppStmt = 0;
  386. return rc;
  387. }
  388. static int schemaEof(sqlite3_vtab_cursor *cur){
  389. schema_cursor *pCur = (schema_cursor *)cur;
  390. return (pCur->pDbList ? 0 : 1);
  391. }
  392. /*
  393. ** Advance the cursor to the next row.
  394. */
  395. static int schemaNext(sqlite3_vtab_cursor *cur){
  396. int rc = SQLITE_OK;
  397. schema_cursor *pCur = (schema_cursor *)cur;
  398. schema_vtab *pVtab = (schema_vtab *)(cur->pVtab);
  399. char *zSql = 0;
  400. while( !pCur->pColumnList || SQLITE_ROW!=sqlite3_step(pCur->pColumnList) ){
  401. if( SQLITE_OK!=(rc = finalize(&pCur->pColumnList)) ) goto next_exit;
  402. while( !pCur->pTableList || SQLITE_ROW!=sqlite3_step(pCur->pTableList) ){
  403. if( SQLITE_OK!=(rc = finalize(&pCur->pTableList)) ) goto next_exit;
  404. assert(pCur->pDbList);
  405. while( SQLITE_ROW!=sqlite3_step(pCur->pDbList) ){
  406. rc = finalize(&pCur->pDbList);
  407. goto next_exit;
  408. }
  409. /* Set zSql to the SQL to pull the list of tables from the
  410. ** sqlite_master (or sqlite_temp_master) table of the database
  411. ** identfied by the row pointed to by the SQL statement pCur->pDbList
  412. ** (iterating through a "PRAGMA database_list;" statement).
  413. */
  414. if( sqlite3_column_int(pCur->pDbList, 0)==1 ){
  415. zSql = sqlite3_mprintf(
  416. "SELECT name FROM sqlite_temp_master WHERE type=%Q",
  417. pVtab->pType->zObject
  418. );
  419. }else{
  420. sqlite3_stmt *pDbList = pCur->pDbList;
  421. zSql = sqlite3_mprintf(
  422. "SELECT name FROM %Q.sqlite_master WHERE type=%Q",
  423. sqlite3_column_text(pDbList, 1), pVtab->pType->zObject
  424. );
  425. }
  426. if( !zSql ){
  427. rc = SQLITE_NOMEM;
  428. goto next_exit;
  429. }
  430. rc = sqlite3_prepare(pVtab->db, zSql, -1, &pCur->pTableList, 0);
  431. sqlite3_free(zSql);
  432. if( rc!=SQLITE_OK ) goto next_exit;
  433. }
  434. /* Set zSql to the SQL to the table_info pragma for the table currently
  435. ** identified by the rows pointed to by statements pCur->pDbList and
  436. ** pCur->pTableList.
  437. */
  438. zSql = sqlite3_mprintf(pVtab->pType->zPragma,
  439. sqlite3_column_text(pCur->pDbList, 1),
  440. sqlite3_column_text(pCur->pTableList, 0)
  441. );
  442. if( !zSql ){
  443. rc = SQLITE_NOMEM;
  444. goto next_exit;
  445. }
  446. rc = sqlite3_prepare(pVtab->db, zSql, -1, &pCur->pColumnList, 0);
  447. sqlite3_free(zSql);
  448. if( rc!=SQLITE_OK ) goto next_exit;
  449. }
  450. pCur->rowid++;
  451. next_exit:
  452. /* TODO: Handle rc */
  453. return rc;
  454. }
  455. /*
  456. ** Reset a schema table cursor.
  457. */
  458. static int schemaFilter(
  459. sqlite3_vtab_cursor *pVtabCursor,
  460. int idxNum, const char *idxStr,
  461. int argc, sqlite3_value **argv
  462. ){
  463. int rc;
  464. schema_vtab *pVtab = (schema_vtab *)(pVtabCursor->pVtab);
  465. schema_cursor *pCur = (schema_cursor *)pVtabCursor;
  466. UNUSED_PARAMETER(idxNum);
  467. UNUSED_PARAMETER(idxStr);
  468. UNUSED_PARAMETER(argc);
  469. UNUSED_PARAMETER(argv);
  470. pCur->rowid = 0;
  471. finalize(&pCur->pTableList);
  472. finalize(&pCur->pColumnList);
  473. finalize(&pCur->pDbList);
  474. rc = sqlite3_prepare(pVtab->db,"SELECT 0, 'main'", -1, &pCur->pDbList, 0);
  475. return (rc==SQLITE_OK ? schemaNext(pVtabCursor) : rc);
  476. }
  477. /*
  478. ** Analyse the WHERE condition.
  479. */
  480. static int schemaBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  481. UNUSED_PARAMETER(tab);
  482. UNUSED_PARAMETER(pIdxInfo);
  483. return SQLITE_OK;
  484. }
  485. /*
  486. ** A virtual table module that merely echos method calls into TCL
  487. ** variables.
  488. */
  489. static sqlite3_module schemaModule = {
  490. 0, /* iVersion */
  491. schemaCreate,
  492. schemaCreate,
  493. schemaBestIndex,
  494. schemaDestroy,
  495. schemaDestroy,
  496. schemaOpen, /* xOpen - open a cursor */
  497. schemaClose, /* xClose - close a cursor */
  498. schemaFilter, /* xFilter - configure scan constraints */
  499. schemaNext, /* xNext - advance a cursor */
  500. schemaEof, /* xEof */
  501. schemaColumn, /* xColumn - read data */
  502. schemaRowid, /* xRowid - read data */
  503. 0, /* xUpdate */
  504. 0, /* xBegin */
  505. 0, /* xSync */
  506. 0, /* xCommit */
  507. 0, /* xRollback */
  508. 0, /* xFindMethod */
  509. 0, /* xRename */
  510. };
  511. /*
  512. ** Extension load function.
  513. */
  514. static int installSchemaModule(sqlite3 *db, sqlite3 *sdb){
  515. sqlite3_create_module(db, "schema", &schemaModule, (void *)sdb);
  516. return 0;
  517. }
  518. /*
  519. ** sj(zValue, zJoin)
  520. **
  521. ** The following block contains the implementation of an aggregate
  522. ** function that returns a string. Each time the function is stepped,
  523. ** it appends data to an internal buffer. When the aggregate is finalized,
  524. ** the contents of the buffer are returned.
  525. **
  526. ** The first time the aggregate is stepped the buffer is set to a copy
  527. ** of the first argument. The second time and subsequent times it is
  528. ** stepped a copy of the second argument is appended to the buffer, then
  529. ** a copy of the first.
  530. **
  531. ** Example:
  532. **
  533. ** INSERT INTO t1(a) VALUES('1');
  534. ** INSERT INTO t1(a) VALUES('2');
  535. ** INSERT INTO t1(a) VALUES('3');
  536. ** SELECT sj(a, ', ') FROM t1;
  537. **
  538. ** => "1, 2, 3"
  539. **
  540. */
  541. struct StrBuffer {
  542. char *zBuf;
  543. };
  544. typedef struct StrBuffer StrBuffer;
  545. static void joinFinalize(sqlite3_context *context){
  546. StrBuffer *p;
  547. p = (StrBuffer *)sqlite3_aggregate_context(context, sizeof(StrBuffer));
  548. sqlite3_result_text(context, p->zBuf, -1, SQLITE_TRANSIENT);
  549. sqlite3_free(p->zBuf);
  550. }
  551. static void joinStep(
  552. sqlite3_context *context,
  553. int argc,
  554. sqlite3_value **argv
  555. ){
  556. StrBuffer *p;
  557. UNUSED_PARAMETER(argc);
  558. p = (StrBuffer *)sqlite3_aggregate_context(context, sizeof(StrBuffer));
  559. if( p->zBuf==0 ){
  560. p->zBuf = sqlite3_mprintf("%s", sqlite3_value_text(argv[0]));
  561. }else{
  562. char *zTmp = p->zBuf;
  563. p->zBuf = sqlite3_mprintf("%s%s%s",
  564. zTmp, sqlite3_value_text(argv[1]), sqlite3_value_text(argv[0])
  565. );
  566. sqlite3_free(zTmp);
  567. }
  568. }
  569. /*
  570. ** dq(zString)
  571. **
  572. ** This scalar function accepts a single argument and interprets it as
  573. ** a text value. The return value is the argument enclosed in double
  574. ** quotes. If any double quote characters are present in the argument,
  575. ** these are escaped.
  576. **
  577. ** dq('the raven "Nevermore."') == '"the raven ""Nevermore."""'
  578. */
  579. static void doublequote(
  580. sqlite3_context *context,
  581. int argc,
  582. sqlite3_value **argv
  583. ){
  584. int ii;
  585. char *zOut;
  586. char *zCsr;
  587. const char *zIn = (const char *)sqlite3_value_text(argv[0]);
  588. int nIn = sqlite3_value_bytes(argv[0]);
  589. UNUSED_PARAMETER(argc);
  590. zOut = sqlite3_malloc(nIn*2+3);
  591. zCsr = zOut;
  592. *zCsr++ = '"';
  593. for(ii=0; ii<nIn; ii++){
  594. *zCsr++ = zIn[ii];
  595. if( zIn[ii]=='"' ){
  596. *zCsr++ = '"';
  597. }
  598. }
  599. *zCsr++ = '"';
  600. *zCsr++ = '\0';
  601. sqlite3_result_text(context, zOut, -1, SQLITE_TRANSIENT);
  602. sqlite3_free(zOut);
  603. }
  604. /*
  605. ** multireplace(zString, zSearch1, zReplace1, ...)
  606. */
  607. static void multireplace(
  608. sqlite3_context *context,
  609. int argc,
  610. sqlite3_value **argv
  611. ){
  612. int i = 0;
  613. char *zOut = 0;
  614. int nOut = 0;
  615. int nMalloc = 0;
  616. const char *zIn = (const char *)sqlite3_value_text(argv[0]);
  617. int nIn = sqlite3_value_bytes(argv[0]);
  618. while( i<nIn ){
  619. const char *zCopy = &zIn[i];
  620. int nCopy = 1;
  621. int nReplace = 1;
  622. int j;
  623. for(j=1; j<(argc-1); j+=2){
  624. const char *z = (const char *)sqlite3_value_text(argv[j]);
  625. int n = sqlite3_value_bytes(argv[j]);
  626. if( n<=(nIn-i) && 0==strncmp(z, zCopy, n) ){
  627. zCopy = (const char *)sqlite3_value_text(argv[j+1]);
  628. nCopy = sqlite3_value_bytes(argv[j+1]);
  629. nReplace = n;
  630. break;
  631. }
  632. }
  633. if( (nOut+nCopy)>nMalloc ){
  634. char *zNew;
  635. nMalloc = 16 + (nOut+nCopy)*2;
  636. zNew = (char*)sqlite3_realloc(zOut, nMalloc);
  637. if( zNew==0 ){
  638. sqlite3_result_error_nomem(context);
  639. return;
  640. }else{
  641. zOut = zNew;
  642. }
  643. }
  644. assert( nMalloc>=(nOut+nCopy) );
  645. memcpy(&zOut[nOut], zCopy, nCopy);
  646. i += nReplace;
  647. nOut += nCopy;
  648. }
  649. sqlite3_result_text(context, zOut, nOut, SQLITE_TRANSIENT);
  650. sqlite3_free(zOut);
  651. }
  652. /*
  653. ** A callback for sqlite3_exec() invokes the callback specified by the
  654. ** GenfkeyCb structure pointed to by the void* passed as the first argument.
  655. */
  656. static int invokeCallback(void *p, int nArg, char **azArg, char **azCol){
  657. GenfkeyCb *pCb = (GenfkeyCb *)p;
  658. UNUSED_PARAMETER(nArg);
  659. UNUSED_PARAMETER(azCol);
  660. return pCb->xData(pCb->pCtx, pCb->eType, azArg[0]);
  661. }
  662. static int detectSchemaProblem(
  663. sqlite3 *db, /* Database connection */
  664. const char *zMessage, /* English language error message */
  665. const char *zSql, /* SQL statement to run */
  666. GenfkeyCb *pCb
  667. ){
  668. sqlite3_stmt *pStmt;
  669. int rc;
  670. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  671. if( rc!=SQLITE_OK ){
  672. return rc;
  673. }
  674. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  675. char *zDel;
  676. int iFk = sqlite3_column_int(pStmt, 0);
  677. const char *zTab = (const char *)sqlite3_column_text(pStmt, 1);
  678. zDel = sqlite3_mprintf("Error in table %s: %s", zTab, zMessage);
  679. rc = pCb->xData(pCb->pCtx, pCb->eType, zDel);
  680. sqlite3_free(zDel);
  681. if( rc!=SQLITE_OK ) return rc;
  682. zDel = sqlite3_mprintf(
  683. "DELETE FROM temp.fkey WHERE from_tbl = %Q AND fkid = %d"
  684. , zTab, iFk
  685. );
  686. sqlite3_exec(db, zDel, 0, 0, 0);
  687. sqlite3_free(zDel);
  688. }
  689. sqlite3_finalize(pStmt);
  690. return SQLITE_OK;
  691. }
  692. /*
  693. ** Create and populate temporary table "fkey".
  694. */
  695. static int populateTempTable(sqlite3 *db, GenfkeyCb *pCallback){
  696. int rc;
  697. rc = sqlite3_exec(db,
  698. "CREATE VIRTUAL TABLE temp.v_fkey USING schema(foreign_key_list);"
  699. "CREATE VIRTUAL TABLE temp.v_col USING schema(table_info);"
  700. "CREATE VIRTUAL TABLE temp.v_idxlist USING schema(index_list);"
  701. "CREATE VIRTUAL TABLE temp.v_idxinfo USING schema(index_info);"
  702. "CREATE VIRTUAL TABLE temp.v_triggers USING schema(trigger_list);"
  703. "CREATE TABLE temp.fkey AS "
  704. "SELECT from_tbl, to_tbl, fkid, from_col, to_col, on_update, on_delete "
  705. "FROM temp.v_fkey WHERE database = 'main';"
  706. , 0, 0, 0
  707. );
  708. if( rc!=SQLITE_OK ) return rc;
  709. rc = detectSchemaProblem(db, "foreign key columns do not exist",
  710. "SELECT fkid, from_tbl "
  711. "FROM temp.fkey "
  712. "WHERE to_col IS NOT NULL AND NOT EXISTS (SELECT 1 "
  713. "FROM temp.v_col WHERE tablename=to_tbl AND name==to_col"
  714. ")", pCallback
  715. );
  716. if( rc!=SQLITE_OK ) return rc;
  717. /* At this point the temp.fkey table is mostly populated. If any foreign
  718. ** keys were specified so that they implicitly refer to they primary
  719. ** key of the parent table, the "to_col" values of the temp.fkey rows
  720. ** are still set to NULL.
  721. **
  722. ** This is easily fixed for single column primary keys, but not for
  723. ** composites. With a composite primary key, there is no way to reliably
  724. ** query sqlite for the order in which the columns that make up the
  725. ** composite key were declared i.e. there is no way to tell if the
  726. ** schema actually contains "PRIMARY KEY(a, b)" or "PRIMARY KEY(b, a)".
  727. ** Therefore, this case is not handled. The following function call
  728. ** detects instances of this case.
  729. */
  730. rc = detectSchemaProblem(db, "implicit mapping to composite primary key",
  731. "SELECT fkid, from_tbl "
  732. "FROM temp.fkey "
  733. "WHERE to_col IS NULL "
  734. "GROUP BY fkid, from_tbl HAVING count(*) > 1", pCallback
  735. );
  736. if( rc!=SQLITE_OK ) return rc;
  737. /* Detect attempts to implicitly map to the primary key of a table
  738. ** that has no primary key column.
  739. */
  740. rc = detectSchemaProblem(db, "implicit mapping to non-existant primary key",
  741. "SELECT fkid, from_tbl "
  742. "FROM temp.fkey "
  743. "WHERE to_col IS NULL AND NOT EXISTS "
  744. "(SELECT 1 FROM temp.v_col WHERE pk AND tablename = temp.fkey.to_tbl)"
  745. , pCallback
  746. );
  747. if( rc!=SQLITE_OK ) return rc;
  748. /* Fix all the implicit primary key mappings in the temp.fkey table. */
  749. rc = sqlite3_exec(db,
  750. "UPDATE temp.fkey SET to_col = "
  751. "(SELECT name FROM temp.v_col WHERE pk AND tablename=temp.fkey.to_tbl)"
  752. " WHERE to_col IS NULL;"
  753. , 0, 0, 0
  754. );
  755. if( rc!=SQLITE_OK ) return rc;
  756. /* Now check that all all parent keys are either primary keys or
  757. ** subject to a unique constraint.
  758. */
  759. rc = sqlite3_exec(db,
  760. "CREATE TABLE temp.idx2 AS SELECT "
  761. "il.tablename AS tablename,"
  762. "ii.indexname AS indexname,"
  763. "ii.name AS col "
  764. "FROM temp.v_idxlist AS il, temp.v_idxinfo AS ii "
  765. "WHERE il.isunique AND il.database='main' AND ii.indexname = il.name;"
  766. "INSERT INTO temp.idx2 "
  767. "SELECT tablename, 'pk', name FROM temp.v_col WHERE pk;"
  768. "CREATE TABLE temp.idx AS SELECT "
  769. "tablename, indexname, sj(dq(col),',') AS cols "
  770. "FROM (SELECT * FROM temp.idx2 ORDER BY col) "
  771. "GROUP BY tablename, indexname;"
  772. "CREATE TABLE temp.fkey2 AS SELECT "
  773. "fkid, from_tbl, to_tbl, sj(dq(to_col),',') AS cols "
  774. "FROM (SELECT * FROM temp.fkey ORDER BY to_col) "
  775. "GROUP BY fkid, from_tbl;"
  776. "CREATE TABLE temp.triggers AS SELECT "
  777. "triggername FROM temp.v_triggers WHERE database='main' AND "
  778. "triggername LIKE 'genfkey%';"
  779. , 0, 0, 0
  780. );
  781. if( rc!=SQLITE_OK ) return rc;
  782. rc = detectSchemaProblem(db, "foreign key is not unique",
  783. "SELECT fkid, from_tbl "
  784. "FROM temp.fkey2 "
  785. "WHERE NOT EXISTS (SELECT 1 "
  786. "FROM temp.idx WHERE tablename=to_tbl AND fkey2.cols==idx.cols"
  787. ")", pCallback
  788. );
  789. if( rc!=SQLITE_OK ) return rc;
  790. return rc;
  791. }
  792. #define GENFKEY_ERROR 1
  793. #define GENFKEY_DROPTRIGGER 2
  794. #define GENFKEY_CREATETRIGGER 3
  795. static int genfkey_create_triggers(
  796. sqlite3 *sdb, /* Connection to read schema from */
  797. const char *zDb, /* Name of db to read ("main", "temp") */
  798. void *pCtx, /* Context pointer to pass to xData */
  799. int (*xData)(void *, int, const char *)
  800. ){
  801. const char *zSql =
  802. "SELECT multireplace('"
  803. "-- Triggers for foreign key mapping:\n"
  804. "--\n"
  805. "-- /from_readable/ REFERENCES /to_readable/\n"
  806. "-- on delete /on_delete/\n"
  807. "-- on update /on_update/\n"
  808. "--\n"
  809. /* The "BEFORE INSERT ON <referencing>" trigger. This trigger's job is to
  810. ** throw an exception if the user tries to insert a row into the
  811. ** referencing table for which there is no corresponding row in
  812. ** the referenced table.
  813. */
  814. "CREATE TRIGGER /name/_insert_referencing BEFORE INSERT ON /tbl/ WHEN \n"
  815. " /key_notnull/ AND NOT EXISTS (SELECT 1 FROM /ref/ WHERE /cond1/)\n"
  816. "BEGIN\n"
  817. " SELECT RAISE(ABORT, ''constraint failed'');\n"
  818. "END;\n"
  819. /* The "BEFORE UPDATE ON <referencing>" trigger. This trigger's job
  820. ** is to throw an exception if the user tries to update a row in the
  821. ** referencing table causing it to correspond to no row in the
  822. ** referenced table.
  823. */
  824. "CREATE TRIGGER /name/_update_referencing BEFORE\n"
  825. " UPDATE OF /rkey_list/ ON /tbl/ WHEN \n"
  826. " /key_notnull/ AND \n"
  827. " NOT EXISTS (SELECT 1 FROM /ref/ WHERE /cond1/)\n"
  828. "BEGIN\n"
  829. " SELECT RAISE(ABORT, ''constraint failed'');\n"
  830. "END;\n"
  831. /* The "BEFORE DELETE ON <referenced>" trigger. This trigger's job
  832. ** is to detect when a row is deleted from the referenced table to
  833. ** which rows in the referencing table correspond. The action taken
  834. ** depends on the value of the 'ON DELETE' clause.
  835. */
  836. "CREATE TRIGGER /name/_delete_referenced BEFORE DELETE ON /ref/ WHEN\n"
  837. " EXISTS (SELECT 1 FROM /tbl/ WHERE /cond2/)\n"
  838. "BEGIN\n"
  839. " /delete_action/\n"
  840. "END;\n"
  841. /* The "AFTER UPDATE ON <referenced>" trigger. This trigger's job
  842. ** is to detect when the key columns of a row in the referenced table
  843. ** to which one or more rows in the referencing table correspond are
  844. ** updated. The action taken depends on the value of the 'ON UPDATE'
  845. ** clause.
  846. */
  847. "CREATE TRIGGER /name/_update_referenced AFTER\n"
  848. " UPDATE OF /fkey_list/ ON /ref/ WHEN \n"
  849. " EXISTS (SELECT 1 FROM /tbl/ WHERE /cond2/)\n"
  850. "BEGIN\n"
  851. " /update_action/\n"
  852. "END;\n"
  853. "'"
  854. /* These are used in the SQL comment written above each set of triggers */
  855. ", '/from_readable/', from_tbl || '(' || sj(from_col, ', ') || ')'"
  856. ", '/to_readable/', to_tbl || '(' || sj(to_col, ', ') || ')'"
  857. ", '/on_delete/', on_delete"
  858. ", '/on_update/', on_update"
  859. ", '/name/', 'genfkey' || min(rowid)"
  860. ", '/tbl/', dq(from_tbl)"
  861. ", '/ref/', dq(to_tbl)"
  862. ", '/key_notnull/', sj('new.' || dq(from_col) || ' IS NOT NULL', ' AND ')"
  863. ", '/fkey_list/', sj(dq(to_col), ', ')"
  864. ", '/rkey_list/', sj(dq(from_col), ', ')"
  865. ", '/cond1/', sj(multireplace('new./from/ == /to/'"
  866. ", '/from/', dq(from_col)"
  867. ", '/to/', dq(to_col)"
  868. "), ' AND ')"
  869. ", '/cond2/', sj(multireplace('old./to/ == /from/'"
  870. ", '/from/', dq(from_col)"
  871. ", '/to/', dq(to_col)"
  872. "), ' AND ')"
  873. ", '/update_action/', CASE on_update "
  874. "WHEN 'SET NULL' THEN "
  875. "multireplace('UPDATE /tbl/ SET /setlist/ WHERE /where/;' "
  876. ", '/setlist/', sj(dq(from_col)||' = NULL',', ')"
  877. ", '/tbl/', dq(from_tbl)"
  878. ", '/where/', sj(dq(from_col)||' = old.'||dq(to_col),' AND ')"
  879. ")"
  880. "WHEN 'CASCADE' THEN "
  881. "multireplace('UPDATE /tbl/ SET /setlist/ WHERE /where/;' "
  882. ", '/setlist/', sj(dq(from_col)||' = new.'||dq(to_col),', ')"
  883. ", '/tbl/', dq(from_tbl)"
  884. ", '/where/', sj(dq(from_col)||' = old.'||dq(to_col),' AND ')"
  885. ")"
  886. "ELSE "
  887. " 'SELECT RAISE(ABORT, ''constraint failed'');'"
  888. "END "
  889. ", '/delete_action/', CASE on_delete "
  890. "WHEN 'SET NULL' THEN "
  891. "multireplace('UPDATE /tbl/ SET /setlist/ WHERE /where/;' "
  892. ", '/setlist/', sj(dq(from_col)||' = NULL',', ')"
  893. ", '/tbl/', dq(from_tbl)"
  894. ", '/where/', sj(dq(from_col)||' = old.'||dq(to_col),' AND ')"
  895. ")"
  896. "WHEN 'CASCADE' THEN "
  897. "multireplace('DELETE FROM /tbl/ WHERE /where/;' "
  898. ", '/tbl/', dq(from_tbl)"
  899. ", '/where/', sj(dq(from_col)||' = old.'||dq(to_col),' AND ')"
  900. ")"
  901. "ELSE "
  902. " 'SELECT RAISE(ABORT, ''constraint failed'');'"
  903. "END "
  904. ") FROM temp.fkey "
  905. "GROUP BY from_tbl, fkid"
  906. ;
  907. int rc;
  908. const int enc = SQLITE_UTF8;
  909. sqlite3 *db = 0;
  910. GenfkeyCb cb;
  911. cb.xData = xData;
  912. cb.pCtx = pCtx;
  913. UNUSED_PARAMETER(zDb);
  914. /* Open the working database handle. */
  915. rc = sqlite3_open(":memory:", &db);
  916. if( rc!=SQLITE_OK ) goto genfkey_exit;
  917. /* Create the special scalar and aggregate functions used by this program. */
  918. sqlite3_create_function(db, "dq", 1, enc, 0, doublequote, 0, 0);
  919. sqlite3_create_function(db, "multireplace", -1, enc, db, multireplace, 0, 0);
  920. sqlite3_create_function(db, "sj", 2, enc, 0, 0, joinStep, joinFinalize);
  921. /* Install the "schema" virtual table module */
  922. installSchemaModule(db, sdb);
  923. /* Create and populate a temp table with the information required to
  924. ** build the foreign key triggers. See function populateTempTable()
  925. ** for details.
  926. */
  927. cb.eType = GENFKEY_ERROR;
  928. rc = populateTempTable(db, &cb);
  929. if( rc!=SQLITE_OK ) goto genfkey_exit;
  930. /* Unless the --no-drop option was specified, generate DROP TRIGGER
  931. ** statements to drop any triggers in the database generated by a
  932. ** previous run of this program.
  933. */
  934. cb.eType = GENFKEY_DROPTRIGGER;
  935. rc = sqlite3_exec(db,
  936. "SELECT 'DROP TRIGGER main.' || dq(triggername) || ';' FROM triggers"
  937. ,invokeCallback, (void *)&cb, 0
  938. );
  939. if( rc!=SQLITE_OK ) goto genfkey_exit;
  940. /* Run the main query to create the trigger definitions. */
  941. cb.eType = GENFKEY_CREATETRIGGER;
  942. rc = sqlite3_exec(db, zSql, invokeCallback, (void *)&cb, 0);
  943. if( rc!=SQLITE_OK ) goto genfkey_exit;
  944. genfkey_exit:
  945. sqlite3_close(db);
  946. return rc;
  947. }
  948. #endif
  949. /* End genfkey logic. */
  950. /*************************************************************************/
  951. /*************************************************************************/
  952. /*
  953. ** If the following flag is set, then command execution stops
  954. ** at an error if we are not interactive.
  955. */
  956. static int bail_on_error = 0;
  957. /*
  958. ** Threat stdin as an interactive input if the following variable
  959. ** is true. Otherwise, assume stdin is connected to a file or pipe.
  960. */
  961. static int stdin_is_interactive = 1;
  962. /*
  963. ** The following is the open SQLite database. We make a pointer
  964. ** to this database a static variable so that it can be accessed
  965. ** by the SIGINT handler to interrupt database processing.
  966. */
  967. static sqlite3 *db = 0;
  968. /*
  969. ** True if an interrupt (Control-C) has been received.
  970. */
  971. static volatile int seenInterrupt = 0;
  972. /*
  973. ** This is the name of our program. It is set in main(), used
  974. ** in a number of other places, mostly for error messages.
  975. */
  976. static char *Argv0;
  977. /*
  978. ** Prompt strings. Initialized in main. Settable with
  979. ** .prompt main continue
  980. */
  981. static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
  982. static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
  983. /*
  984. ** Write I/O traces to the following stream.
  985. */
  986. #ifdef SQLITE_ENABLE_IOTRACE
  987. static FILE *iotrace = 0;
  988. #endif
  989. /*
  990. ** This routine works like printf in that its first argument is a
  991. ** format string and subsequent arguments are values to be substituted
  992. ** in place of % fields. The result of formatting this string
  993. ** is written to iotrace.
  994. */
  995. #ifdef SQLITE_ENABLE_IOTRACE
  996. static void iotracePrintf(const char *zFormat, ...){
  997. va_list ap;
  998. char *z;
  999. if( iotrace==0 ) return;
  1000. va_start(ap, zFormat);
  1001. z = sqlite3_vmprintf(zFormat, ap);
  1002. va_end(ap);
  1003. fprintf(iotrace, "%s", z);
  1004. sqlite3_free(z);
  1005. }
  1006. #endif
  1007. /*
  1008. ** Determines if a string is a number of not.
  1009. */
  1010. static int isNumber(const char *z, int *realnum){
  1011. if( *z=='-' || *z=='+' ) z++;
  1012. if( !isdigit(*z) ){
  1013. return 0;
  1014. }
  1015. z++;
  1016. if( realnum ) *realnum = 0;
  1017. while( isdigit(*z) ){ z++; }
  1018. if( *z=='.' ){
  1019. z++;
  1020. if( !isdigit(*z) ) return 0;
  1021. while( isdigit(*z) ){ z++; }
  1022. if( realnum ) *realnum = 1;
  1023. }
  1024. if( *z=='e' || *z=='E' ){
  1025. z++;
  1026. if( *z=='+' || *z=='-' ) z++;
  1027. if( !isdigit(*z) ) return 0;
  1028. while( isdigit(*z) ){ z++; }
  1029. if( realnum ) *realnum = 1;
  1030. }
  1031. return *z==0;
  1032. }
  1033. /*
  1034. ** A global char* and an SQL function to access its current value
  1035. ** from within an SQL statement. This program used to use the
  1036. ** sqlite_exec_printf() API to substitue a string into an SQL statement.
  1037. ** The correct way to do this with sqlite3 is to use the bind API, but
  1038. ** since the shell is built around the callback paradigm it would be a lot
  1039. ** of work. Instead just use this hack, which is quite harmless.
  1040. */
  1041. static const char *zShellStatic = 0;
  1042. static void shellstaticFunc(
  1043. sqlite3_context *context,
  1044. int argc,
  1045. sqlite3_value **argv
  1046. ){
  1047. assert( 0==argc );
  1048. assert( zShellStatic );
  1049. UNUSED_PARAMETER(argc);
  1050. UNUSED_PARAMETER(argv);
  1051. sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
  1052. }
  1053. /*
  1054. ** This routine reads a line of text from FILE in, stores
  1055. ** the text in memory obtained from malloc() and returns a pointer
  1056. ** to the text. NULL is returned at end of file, or if malloc()
  1057. ** fails.
  1058. **
  1059. ** The interface is like "readline" but no command-line editing
  1060. ** is done.
  1061. */
  1062. static char *local_getline(char *zPrompt, FILE *in){
  1063. char *zLine;
  1064. int nLine;
  1065. int n;
  1066. int eol;
  1067. if( zPrompt && *zPrompt ){
  1068. printf("%s",zPrompt);
  1069. fflush(stdout);
  1070. }
  1071. nLine = 100;
  1072. zLine = malloc( nLine );
  1073. if( zLine==0 ) return 0;
  1074. n = 0;
  1075. eol = 0;
  1076. while( !eol ){
  1077. if( n+100>nLine ){
  1078. nLine = nLine*2 + 100;
  1079. zLine = realloc(zLine, nLine);
  1080. if( zLine==0 ) return 0;
  1081. }
  1082. if( fgets(&zLine[n], nLine - n, in)==0 ){
  1083. if( n==0 ){
  1084. free(zLine);
  1085. return 0;
  1086. }
  1087. zLine[n] = 0;
  1088. eol = 1;
  1089. break;
  1090. }
  1091. while( zLine[n] ){ n++; }
  1092. if( n>0 && zLine[n-1]=='\n' ){
  1093. n--;
  1094. if( n>0 && zLine[n-1]=='\r' ) n--;
  1095. zLine[n] = 0;
  1096. eol = 1;
  1097. }
  1098. }
  1099. zLine = realloc( zLine, n+1 );
  1100. return zLine;
  1101. }
  1102. /*
  1103. ** Retrieve a single line of input text.
  1104. **
  1105. ** zPrior is a string of prior text retrieved. If not the empty
  1106. ** string, then issue a continuation prompt.
  1107. */
  1108. static char *one_input_line(const char *zPrior, FILE *in){
  1109. char *zPrompt;
  1110. char *zResult;
  1111. if( in!=0 ){
  1112. return local_getline(0, in);
  1113. }
  1114. if( zPrior && zPrior[0] ){
  1115. zPrompt = continuePrompt;
  1116. }else{
  1117. zPrompt = mainPrompt;
  1118. }
  1119. zResult = readline(zPrompt);
  1120. #if defined(HAVE_READLINE) && HAVE_READLINE==1
  1121. if( zResult && *zResult ) add_history(zResult);
  1122. #endif
  1123. return zResult;
  1124. }
  1125. struct previous_mode_data {
  1126. int valid; /* Is there legit data in here? */
  1127. int mode;
  1128. int showHeader;
  1129. int colWidth[100];
  1130. };
  1131. /*
  1132. ** An pointer to an instance of this structure is passed from
  1133. ** the main program to the callback. This is used to communicate
  1134. ** state and mode information.
  1135. */
  1136. struct callback_data {
  1137. sqlite3 *db; /* The database */
  1138. int echoOn; /* True to echo input commands */
  1139. int cnt; /* Number of records displayed so far */
  1140. FILE *out; /* Write results here */
  1141. int mode; /* An output mode setting */
  1142. int writableSchema; /* True if PRAGMA writable_schema=ON */
  1143. int showHeader; /* True to show column names in List or Column mode */
  1144. char *zDestTable; /* Name of destination table when MODE_Insert */
  1145. char separator[20]; /* Separator character for MODE_List */
  1146. int colWidth[100]; /* Requested width of each column when in column mode*/
  1147. int actualWidth[100]; /* Actual width of each column */
  1148. char nullvalue[20]; /* The text to print when a NULL comes back from
  1149. ** the database */
  1150. struct previous_mode_data explainPrev;
  1151. /* Holds the mode information just before
  1152. ** .explain ON */
  1153. char outfile[FILENAME_MAX]; /* Filename for *out */
  1154. const char *zDbFilename; /* name of the database file */
  1155. sqlite3_stmt *pStmt; /* Current statement if any. */
  1156. FILE *pLog; /* Write log output here */
  1157. };
  1158. /*
  1159. ** These are the allowed modes.
  1160. */
  1161. #define MODE_Line 0 /* One column per line. Blank line between records */
  1162. #define MODE_Column 1 /* One record per line in neat columns */
  1163. #define MODE_List 2 /* One record per line with a separator */
  1164. #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
  1165. #define MODE_Html 4 /* Generate an XHTML table */
  1166. #define MODE_Insert 5 /* Generate SQL "insert" statements */
  1167. #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */
  1168. #define MODE_Csv 7 /* Quote strings, numbers are plain */
  1169. #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */
  1170. static const char *modeDescr[] = {
  1171. "line",
  1172. "column",
  1173. "list",
  1174. "semi",
  1175. "html",
  1176. "insert",
  1177. "tcl",
  1178. "csv",
  1179. "explain",
  1180. };
  1181. /*
  1182. ** Number of elements in an array
  1183. */
  1184. #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
  1185. /*
  1186. ** Compute a string length that is limited to what can be stored in
  1187. ** lower 30 bits of a 32-bit signed integer.
  1188. */
  1189. static int strlen30(const char *z){
  1190. const char *z2 = z;
  1191. while( *z2 ){ z2++; }
  1192. return 0x3fffffff & (int)(z2 - z);
  1193. }
  1194. /*
  1195. ** A callback for the sqlite3_log() interface.
  1196. */
  1197. static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  1198. struct callback_data *p = (struct callback_data*)pArg;
  1199. if( p->pLog==0 ) return;
  1200. fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  1201. fflush(p->pLog);
  1202. }
  1203. /*
  1204. ** Output the given string as a hex-encoded blob (eg. X'1234' )
  1205. */
  1206. static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  1207. int i;
  1208. char *zBlob = (char *)pBlob;
  1209. fprintf(out,"X'");
  1210. for(i=0; i<nBlob; i++){ fprintf(out,"%02x",zBlob[i]); }
  1211. fprintf(out,"'");
  1212. }
  1213. /*
  1214. ** Output the given string as a quoted string using SQL quoting conventions.
  1215. */
  1216. static void output_quoted_string(FILE *out, const char *z){
  1217. int i;
  1218. int nSingle = 0;
  1219. for(i=0; z[i]; i++){
  1220. if( z[i]=='\'' ) nSingle++;
  1221. }
  1222. if( nSingle==0 ){
  1223. fprintf(out,"'%s'",z);
  1224. }else{
  1225. fprintf(out,"'");
  1226. while( *z ){
  1227. for(i=0; z[i] && z[i]!='\''; i++){}
  1228. if( i==0 ){
  1229. fprintf(out,"''");
  1230. z++;
  1231. }else if( z[i]=='\'' ){
  1232. fprintf(out,"%.*s''",i,z);
  1233. z += i+1;
  1234. }else{
  1235. fprintf(out,"%s",z);
  1236. break;
  1237. }
  1238. }
  1239. fprintf(out,"'");
  1240. }
  1241. }
  1242. /*
  1243. ** Output the given string as a quoted according to C or TCL quoting rules.
  1244. */
  1245. static void output_c_string(FILE *out, const char *z){
  1246. unsigned int c;
  1247. fputc('"', out);
  1248. while( (c = *(z++))!=0 ){
  1249. if( c=='\\' ){
  1250. fputc(c, out);
  1251. fputc(c, out);
  1252. }else if( c=='\t' ){
  1253. fputc('\\', out);
  1254. fputc('t', out);
  1255. }else if( c=='\n' ){
  1256. fputc('\\', out);
  1257. fputc('n', out);
  1258. }else if( c=='\r' ){
  1259. fputc('\\', out);
  1260. fputc('r', out);
  1261. }else if( !isprint(c) ){
  1262. fprintf(out, "\\%03o", c&0xff);
  1263. }else{
  1264. fputc(c, out);
  1265. }
  1266. }
  1267. fputc('"', out);
  1268. }
  1269. /*
  1270. ** Output the given string with characters that are special to
  1271. ** HTML escaped.
  1272. */
  1273. static void output_html_string(FILE *out, const char *z){
  1274. int i;
  1275. while( *z ){
  1276. for(i=0; z[i]
  1277. && z[i]!='<'
  1278. && z[i]!='&'
  1279. && z[i]!='>'
  1280. && z[i]!='\"'
  1281. && z[i]!='\'';
  1282. i++){}
  1283. if( i>0 ){
  1284. fprintf(out,"%.*s",i,z);
  1285. }
  1286. if( z[i]=='<' ){
  1287. fprintf(out,"&lt;");
  1288. }else if( z[i]=='&' ){
  1289. fprintf(out,"&amp;");
  1290. }else if( z[i]=='>' ){
  1291. fprintf(out,"&gt;");
  1292. }else if( z[i]=='\"' ){
  1293. fprintf(out,"&quot;");
  1294. }else if( z[i]=='\'' ){
  1295. fprintf(out,"&#39;");
  1296. }else{
  1297. break;
  1298. }
  1299. z += i + 1;
  1300. }
  1301. }
  1302. /*
  1303. ** If a field contains any character identified by a 1 in the following
  1304. ** array, then the string must be quoted for CSV.
  1305. */
  1306. static const char needCsvQuote[] = {
  1307. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1308. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1309. 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  1310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  1315. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1316. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1317. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1318. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1319. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1320. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1321. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1322. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1323. };
  1324. /*
  1325. ** Output a single term of CSV. Actually, p->separator is used for
  1326. ** the separator, which may or may not be a comma. p->nullvalue is
  1327. ** the null value. Strings are quoted using ANSI-C rules. Numbers
  1328. ** appear outside of quotes.
  1329. */
  1330. static void output_csv(struct callback_data *p, const char *z, int bSep){
  1331. FILE *out = p->out;
  1332. if( z==0 ){
  1333. fprintf(out,"%s",p->nullvalue);
  1334. }else{
  1335. int i;
  1336. int nSep = strlen30(p->separator);
  1337. for(i=0; z[i]; i++){
  1338. if( needCsvQuote[((unsigned char*)z)[i]]
  1339. || (z[i]==p->separator[0] &&
  1340. (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){
  1341. i = 0;
  1342. break;
  1343. }
  1344. }
  1345. if( i==0 ){
  1346. putc('"', out);
  1347. for(i=0; z[i]; i++){
  1348. if( z[i]=='"' ) putc('"', out);
  1349. putc(z[i], out);
  1350. }
  1351. putc('"', out);
  1352. }else{
  1353. fprintf(out, "%s", z);
  1354. }
  1355. }
  1356. if( bSep ){
  1357. fprintf(p->out, "%s", p->separator);
  1358. }
  1359. }
  1360. #ifdef SIGINT
  1361. /*
  1362. ** This routine runs when the user presses Ctrl-C
  1363. */
  1364. static void interrupt_handler(int NotUsed){
  1365. UNUSED_PARAMETER(NotUsed);
  1366. seenInterrupt = 1;
  1367. if( db ) sqlite3_interrupt(db);
  1368. }
  1369. #endif
  1370. /*
  1371. ** This is the callback routine that the shell
  1372. ** invokes for each row of a query result.
  1373. */
  1374. static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType){
  1375. int i;
  1376. struct callback_data *p = (struct callback_data*)pArg;
  1377. if( p->echoOn && p->cnt==0 && p->pStmt){
  1378. printf("%s\n", sqlite3_sql(p->pStmt));
  1379. }
  1380. switch( p->mode ){
  1381. case MODE_Line: {
  1382. int w = 5;
  1383. if( azArg==0 ) break;
  1384. for(i=0; i<nArg; i++){
  1385. int len = strlen30(azCol[i] ? azCol[i] : "");
  1386. if( len>w ) w = len;
  1387. }
  1388. if( p->cnt++>0 ) fprintf(p->out,"\n");
  1389. for(i=0; i<nArg; i++){
  1390. fprintf(p->out,"%*s = %s\n", w, azCol[i],
  1391. azArg[i] ? azArg[i] : p->nullvalue);
  1392. }
  1393. break;
  1394. }
  1395. case MODE_Explain:
  1396. case MODE_Column: {
  1397. if( p->cnt++==0 ){
  1398. for(i=0; i<nArg; i++){
  1399. int w, n;
  1400. if( i<ArraySize(p->colWidth) ){
  1401. w = p->colWidth[i];
  1402. }else{
  1403. w = 0;
  1404. }
  1405. if( w<=0 ){
  1406. w = strlen30(azCol[i] ? azCol[i] : "");
  1407. if( w<10 ) w = 10;
  1408. n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullvalue);
  1409. if( w<n ) w = n;
  1410. }
  1411. if( i<ArraySize(p->actualWidth) ){
  1412. p->actualWidth[i] = w;
  1413. }
  1414. if( p->showHeader ){
  1415. fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": " ");
  1416. }
  1417. }
  1418. if( p->showHeader ){
  1419. for(i=0; i<nArg; i++){
  1420. int w;
  1421. if( i<ArraySize(p->actualWidth) ){
  1422. w = p->actualWidth[i];
  1423. }else{
  1424. w = 10;
  1425. }
  1426. fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------"
  1427. "----------------------------------------------------------",
  1428. i==nArg-1 ? "\n": " ");
  1429. }
  1430. }
  1431. }
  1432. if( azArg==0 ) break;
  1433. for(i=0; i<nArg; i++){
  1434. int w;
  1435. if( i<ArraySize(p->actualWidth) ){
  1436. w = p->actualWidth[i];
  1437. }else{
  1438. w = 10;
  1439. }
  1440. if( p->mode==MODE_Explain && azArg[i] &&
  1441. strlen30(azArg[i])>w ){
  1442. w = strlen30(azArg[i]);
  1443. }
  1444. fprintf(p->out,"%-*.*s%s",w,w,
  1445. azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " ");
  1446. }
  1447. break;
  1448. }
  1449. case MODE_Semi:
  1450. case MODE_List: {
  1451. if( p->cnt++==0 && p->showHeader ){
  1452. for(i=0; i<nArg; i++){
  1453. fprintf(p->out,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator);
  1454. }
  1455. }
  1456. if( azArg==0 ) break;
  1457. for(i=0; i<nArg; i++){
  1458. char *z = azArg[i];
  1459. if( z==0 ) z = p->nullvalue;
  1460. fprintf(p->out, "%s", z);
  1461. if( i<nArg-1 ){
  1462. fprintf(p->out, "%s", p->separator);
  1463. }else if( p->mode==MODE_Semi ){
  1464. fprintf(p->out, ";\n");
  1465. }else{
  1466. fprintf(p->out, "\n");
  1467. }
  1468. }
  1469. break;
  1470. }
  1471. case MODE_Html: {
  1472. if( p->cnt++==0 && p->showHeader ){
  1473. fprintf(p->out,"<TR>");
  1474. for(i=0; i<nArg; i++){
  1475. fprintf(p->out,"<TH>");
  1476. output_html_string(p->out, azCol[i]);
  1477. fprintf(p->out,"</TH>\n");
  1478. }
  1479. fprintf(p->out,"</TR>\n");
  1480. }
  1481. if( azArg==0 ) break;
  1482. fprintf(p->out,"<TR>");
  1483. for(i=0; i<nArg; i++){
  1484. fprintf(p->out,"<TD>");
  1485. output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
  1486. fprintf(p->out,"</TD>\n");
  1487. }
  1488. fprintf(p->out,"</TR>\n");
  1489. break;
  1490. }
  1491. case MODE_Tcl: {
  1492. if( p->cnt++==0 && p->showHeader ){
  1493. for(i=0; i<nArg; i++){
  1494. output_c_string(p->out,azCol[i] ? azCol[i] : "");
  1495. fprintf(p->out, "%s", p->separator);
  1496. }
  1497. fprintf(p->out,"\n");
  1498. }
  1499. if( azArg==0 ) break;
  1500. for(i=0; i<nArg; i++){
  1501. output_c_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
  1502. fprintf(p->out, "%s", p->separator);
  1503. }
  1504. fprintf(p->out,"\n");
  1505. break;
  1506. }
  1507. case MODE_Csv: {
  1508. if( p->cnt++==0 && p->showHeader ){
  1509. for(i=0; i<nArg; i++){
  1510. output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  1511. }
  1512. fprintf(p->out,"\n");
  1513. }
  1514. if( azArg==0 ) break;
  1515. for(i=0; i<nArg; i++){
  1516. output_csv(p, azArg[i], i<nArg-1);
  1517. }
  1518. fprintf(p->out,"\n");
  1519. break;
  1520. }
  1521. case MODE_Insert: {
  1522. p->cnt++;
  1523. if( azArg==0 ) break;
  1524. fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
  1525. for(i=0; i<nArg; i++){
  1526. char *zSep = i>0 ? ",": "";
  1527. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  1528. fprintf(p->out,"%sNULL",zSep);
  1529. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  1530. if( zSep[0] ) fprintf(p->out,"%s",zSep);
  1531. output_quoted_string(p->out, azArg[i]);
  1532. }else if( aiType && (aiType[i]==SQLITE_INTEGER || aiType[i]==SQLITE_FLOAT) ){
  1533. fprintf(p->out,"%s%s",zSep, azArg[i]);
  1534. }else if( aiType && aiType[i]==

Large files files are truncated, but you can click here to view the full file