PageRenderTime 103ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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]==SQLITE_BLOB && p->pStmt ){
  1535. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  1536. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  1537. if( zSep[0] ) fprintf(p->out,"%s",zSep);
  1538. output_hex_blob(p->out, pBlob, nBlob);
  1539. }else if( isNumber(azArg[i], 0) ){
  1540. fprintf(p->out,"%s%s",zSep, azArg[i]);
  1541. }else{
  1542. if( zSep[0] ) fprintf(p->out,"%s",zSep);
  1543. output_quoted_string(p->out, azArg[i]);
  1544. }
  1545. }
  1546. fprintf(p->out,");\n");
  1547. break;
  1548. }
  1549. }
  1550. return 0;
  1551. }
  1552. /*
  1553. ** This is the callback routine that the SQLite library
  1554. ** invokes for each row of a query result.
  1555. */
  1556. static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  1557. /* since we don't have type info, call the shell_callback with a NULL value */
  1558. return shell_callback(pArg, nArg, azArg, azCol, NULL);
  1559. }
  1560. /*
  1561. ** Set the destination table field of the callback_data structure to
  1562. ** the name of the table given. Escape any quote characters in the
  1563. ** table name.
  1564. */
  1565. static void set_table_name(struct callback_data *p, const char *zName){
  1566. int i, n;
  1567. int needQuote;
  1568. char *z;
  1569. if( p->zDestTable ){
  1570. free(p->zDestTable);
  1571. p->zDestTable = 0;
  1572. }
  1573. if( zName==0 ) return;
  1574. needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
  1575. for(i=n=0; zName[i]; i++, n++){
  1576. if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
  1577. needQuote = 1;
  1578. if( zName[i]=='\'' ) n++;
  1579. }
  1580. }
  1581. if( needQuote ) n += 2;
  1582. z = p->zDestTable = malloc( n+1 );
  1583. if( z==0 ){
  1584. fprintf(stderr,"Error: out of memory\n");
  1585. exit(1);
  1586. }
  1587. n = 0;
  1588. if( needQuote ) z[n++] = '\'';
  1589. for(i=0; zName[i]; i++){
  1590. z[n++] = zName[i];
  1591. if( zName[i]=='\'' ) z[n++] = '\'';
  1592. }
  1593. if( needQuote ) z[n++] = '\'';
  1594. z[n] = 0;
  1595. }
  1596. /* zIn is either a pointer to a NULL-terminated string in memory obtained
  1597. ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  1598. ** added to zIn, and the result returned in memory obtained from malloc().
  1599. ** zIn, if it was not NULL, is freed.
  1600. **
  1601. ** If the third argument, quote, is not '\0', then it is used as a
  1602. ** quote character for zAppend.
  1603. */
  1604. static char *appendText(char *zIn, char const *zAppend, char quote){
  1605. int len;
  1606. int i;
  1607. int nAppend = strlen30(zAppend);
  1608. int nIn = (zIn?strlen30(zIn):0);
  1609. len = nAppend+nIn+1;
  1610. if( quote ){
  1611. len += 2;
  1612. for(i=0; i<nAppend; i++){
  1613. if( zAppend[i]==quote ) len++;
  1614. }
  1615. }
  1616. zIn = (char *)realloc(zIn, len);
  1617. if( !zIn ){
  1618. return 0;
  1619. }
  1620. if( quote ){
  1621. char *zCsr = &zIn[nIn];
  1622. *zCsr++ = quote;
  1623. for(i=0; i<nAppend; i++){
  1624. *zCsr++ = zAppend[i];
  1625. if( zAppend[i]==quote ) *zCsr++ = quote;
  1626. }
  1627. *zCsr++ = quote;
  1628. *zCsr++ = '\0';
  1629. assert( (zCsr-zIn)==len );
  1630. }else{
  1631. memcpy(&zIn[nIn], zAppend, nAppend);
  1632. zIn[len-1] = '\0';
  1633. }
  1634. return zIn;
  1635. }
  1636. /*
  1637. ** Execute a query statement that has a single result column. Print
  1638. ** that result column on a line by itself with a semicolon terminator.
  1639. **
  1640. ** This is used, for example, to show the schema of the database by
  1641. ** querying the SQLITE_MASTER table.
  1642. */
  1643. static int run_table_dump_query(
  1644. FILE *out, /* Send output here */
  1645. sqlite3 *db, /* Database to query */
  1646. const char *zSelect, /* SELECT statement to extract content */
  1647. const char *zFirstRow /* Print before first row, if not NULL */
  1648. ){
  1649. sqlite3_stmt *pSelect;
  1650. int rc;
  1651. rc = sqlite3_prepare(db, zSelect, -1, &pSelect, 0);
  1652. if( rc!=SQLITE_OK || !pSelect ){
  1653. return rc;
  1654. }
  1655. rc = sqlite3_step(pSelect);
  1656. while( rc==SQLITE_ROW ){
  1657. if( zFirstRow ){
  1658. fprintf(out, "%s", zFirstRow);
  1659. zFirstRow = 0;
  1660. }
  1661. fprintf(out, "%s;\n", sqlite3_column_text(pSelect, 0));
  1662. rc = sqlite3_step(pSelect);
  1663. }
  1664. return sqlite3_finalize(pSelect);
  1665. }
  1666. /*
  1667. ** Allocate space and save off current error string.
  1668. */
  1669. static char *save_err_msg(
  1670. sqlite3 *db /* Database to query */
  1671. ){
  1672. int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
  1673. char *zErrMsg = sqlite3_malloc(nErrMsg);
  1674. if( zErrMsg ){
  1675. memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
  1676. }
  1677. return zErrMsg;
  1678. }
  1679. /*
  1680. ** Execute a statement or set of statements. Print
  1681. ** any result rows/columns depending on the current mode
  1682. ** set via the supplied callback.
  1683. **
  1684. ** This is very similar to SQLite's built-in sqlite3_exec()
  1685. ** function except it takes a slightly different callback
  1686. ** and callback data argument.
  1687. */
  1688. static int shell_exec(
  1689. sqlite3 *db, /* An open database */
  1690. const char *zSql, /* SQL to be evaluated */
  1691. int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
  1692. /* (not the same as sqlite3_exec) */
  1693. struct callback_data *pArg, /* Pointer to struct callback_data */
  1694. char **pzErrMsg /* Error msg written here */
  1695. ){
  1696. sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
  1697. int rc = SQLITE_OK; /* Return Code */
  1698. const char *zLeftover; /* Tail of unprocessed SQL */
  1699. if( pzErrMsg ){
  1700. *pzErrMsg = NULL;
  1701. }
  1702. while( zSql[0] && (SQLITE_OK == rc) ){
  1703. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  1704. if( SQLITE_OK != rc ){
  1705. if( pzErrMsg ){
  1706. *pzErrMsg = save_err_msg(db);
  1707. }
  1708. }else{
  1709. if( !pStmt ){
  1710. /* this happens for a comment or white-space */
  1711. zSql = zLeftover;
  1712. while( isspace(zSql[0]) ) zSql++;
  1713. continue;
  1714. }
  1715. /* perform the first step. this will tell us if we
  1716. ** have a result set or not and how wide it is.
  1717. */
  1718. rc = sqlite3_step(pStmt);
  1719. /* if we have a result set... */
  1720. if( SQLITE_ROW == rc ){
  1721. /* if we have a callback... */
  1722. if( xCallback ){
  1723. /* allocate space for col name ptr, value ptr, and type */
  1724. int nCol = sqlite3_column_count(pStmt);
  1725. void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1);
  1726. if( !pData ){
  1727. rc = SQLITE_NOMEM;
  1728. }else{
  1729. char **azCols = (char **)pData; /* Names of result columns */
  1730. char **azVals = &azCols[nCol]; /* Results */
  1731. int *aiTypes = (int *)&azVals[nCol]; /* Result types */
  1732. int i;
  1733. assert(sizeof(int) <= sizeof(char *));
  1734. /* save off ptrs to column names */
  1735. for(i=0; i<nCol; i++){
  1736. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  1737. }
  1738. /* save off the prepared statment handle and reset row count */
  1739. if( pArg ){
  1740. pArg->pStmt = pStmt;
  1741. pArg->cnt = 0;
  1742. }
  1743. do{
  1744. /* extract the data and data types */
  1745. for(i=0; i<nCol; i++){
  1746. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  1747. aiTypes[i] = sqlite3_column_type(pStmt, i);
  1748. if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
  1749. rc = SQLITE_NOMEM;
  1750. break; /* from for */
  1751. }
  1752. } /* end for */
  1753. /* if data and types extracted successfully... */
  1754. if( SQLITE_ROW == rc ){
  1755. /* call the supplied callback with the result row data */
  1756. if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
  1757. rc = SQLITE_ABORT;
  1758. }else{
  1759. rc = sqlite3_step(pStmt);
  1760. }
  1761. }
  1762. } while( SQLITE_ROW == rc );
  1763. sqlite3_free(pData);
  1764. if( pArg ){
  1765. pArg->pStmt = NULL;
  1766. }
  1767. }
  1768. }else{
  1769. do{
  1770. rc = sqlite3_step(pStmt);
  1771. } while( rc == SQLITE_ROW );
  1772. }
  1773. }
  1774. /* Finalize the statement just executed. If this fails, save a
  1775. ** copy of the error message. Otherwise, set zSql to point to the
  1776. ** next statement to execute. */
  1777. rc = sqlite3_finalize(pStmt);
  1778. if( rc==SQLITE_OK ){
  1779. zSql = zLeftover;
  1780. while( isspace(zSql[0]) ) zSql++;
  1781. }else if( pzErrMsg ){
  1782. *pzErrMsg = save_err_msg(db);
  1783. }
  1784. }
  1785. } /* end while */
  1786. return rc;
  1787. }
  1788. /*
  1789. ** This is a different callback routine used for dumping the database.
  1790. ** Each row received by this callback consists of a table name,
  1791. ** the table type ("index" or "table") and SQL to create the table.
  1792. ** This routine should print text sufficient to recreate the table.
  1793. */
  1794. static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
  1795. int rc;
  1796. const char *zTable;
  1797. const char *zType;
  1798. const char *zSql;
  1799. const char *zPrepStmt = 0;
  1800. struct callback_data *p = (struct callback_data *)pArg;
  1801. UNUSED_PARAMETER(azCol);
  1802. if( nArg!=3 ) return 1;
  1803. zTable = azArg[0];
  1804. zType = azArg[1];
  1805. zSql = azArg[2];
  1806. if( strcmp(zTable, "sqlite_sequence")==0 ){
  1807. zPrepStmt = "DELETE FROM sqlite_sequence;\n";
  1808. }else if( strcmp(zTable, "sqlite_stat1")==0 ){
  1809. fprintf(p->out, "ANALYZE sqlite_master;\n");
  1810. }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  1811. return 0;
  1812. }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  1813. char *zIns;
  1814. if( !p->writableSchema ){
  1815. fprintf(p->out, "PRAGMA writable_schema=ON;\n");
  1816. p->writableSchema = 1;
  1817. }
  1818. zIns = sqlite3_mprintf(
  1819. "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
  1820. "VALUES('table','%q','%q',0,'%q');",
  1821. zTable, zTable, zSql);
  1822. fprintf(p->out, "%s\n", zIns);
  1823. sqlite3_free(zIns);
  1824. return 0;
  1825. }else{
  1826. fprintf(p->out, "%s;\n", zSql);
  1827. }
  1828. if( strcmp(zType, "table")==0 ){
  1829. sqlite3_stmt *pTableInfo = 0;
  1830. char *zSelect = 0;
  1831. char *zTableInfo = 0;
  1832. char *zTmp = 0;
  1833. int nRow = 0;
  1834. zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
  1835. zTableInfo = appendText(zTableInfo, zTable, '"');
  1836. zTableInfo = appendText(zTableInfo, ");", 0);
  1837. rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0);
  1838. free(zTableInfo);
  1839. if( rc!=SQLITE_OK || !pTableInfo ){
  1840. return 1;
  1841. }
  1842. zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
  1843. zTmp = appendText(zTmp, zTable, '"');
  1844. if( zTmp ){
  1845. zSelect = appendText(zSelect, zTmp, '\'');
  1846. }
  1847. zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
  1848. rc = sqlite3_step(pTableInfo);
  1849. while( rc==SQLITE_ROW ){
  1850. const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
  1851. zSelect = appendText(zSelect, "quote(", 0);
  1852. zSelect = appendText(zSelect, zText, '"');
  1853. rc = sqlite3_step(pTableInfo);
  1854. if( rc==SQLITE_ROW ){
  1855. zSelect = appendText(zSelect, ") || ',' || ", 0);
  1856. }else{
  1857. zSelect = appendText(zSelect, ") ", 0);
  1858. }
  1859. nRow++;
  1860. }
  1861. rc = sqlite3_finalize(pTableInfo);
  1862. if( rc!=SQLITE_OK || nRow==0 ){
  1863. free(zSelect);
  1864. return 1;
  1865. }
  1866. zSelect = appendText(zSelect, "|| ')' FROM ", 0);
  1867. zSelect = appendText(zSelect, zTable, '"');
  1868. rc = run_table_dump_query(p->out, p->db, zSelect, zPrepStmt);
  1869. if( rc==SQLITE_CORRUPT ){
  1870. zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
  1871. rc = run_table_dump_query(p->out, p->db, zSelect, 0);
  1872. }
  1873. if( zSelect ) free(zSelect);
  1874. }
  1875. return 0;
  1876. }
  1877. /*
  1878. ** Run zQuery. Use dump_callback() as the callback routine so that
  1879. ** the contents of the query are output as SQL statements.
  1880. **
  1881. ** If we get a SQLITE_CORRUPT error, rerun the query after appending
  1882. ** "ORDER BY rowid DESC" to the end.
  1883. */
  1884. static int run_schema_dump_query(
  1885. struct callback_data *p,
  1886. const char *zQuery,
  1887. char **pzErrMsg
  1888. ){
  1889. int rc;
  1890. rc = sqlite3_exec(p->db, zQuery, dump_callback, p, pzErrMsg);
  1891. if( rc==SQLITE_CORRUPT ){
  1892. char *zQ2;
  1893. int len = strlen30(zQuery);
  1894. if( pzErrMsg ) sqlite3_free(*pzErrMsg);
  1895. zQ2 = malloc( len+100 );
  1896. if( zQ2==0 ) return rc;
  1897. sqlite3_snprintf(sizeof(zQ2), zQ2, "%s ORDER BY rowid DESC", zQuery);
  1898. rc = sqlite3_exec(p->db, zQ2, dump_callback, p, pzErrMsg);
  1899. free(zQ2);
  1900. }
  1901. return rc;
  1902. }
  1903. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_SUBQUERY)
  1904. struct GenfkeyCmd {
  1905. sqlite3 *db; /* Database handle */
  1906. struct callback_data *pCb; /* Callback data */
  1907. int isIgnoreErrors; /* True for --ignore-errors */
  1908. int isExec; /* True for --exec */
  1909. int isNoDrop; /* True for --no-drop */
  1910. int nErr; /* Number of errors seen so far */
  1911. };
  1912. typedef struct GenfkeyCmd GenfkeyCmd;
  1913. static int genfkeyParseArgs(GenfkeyCmd *p, char **azArg, int nArg){
  1914. int ii;
  1915. memset(p, 0, sizeof(GenfkeyCmd));
  1916. for(ii=0; ii<nArg; ii++){
  1917. int n = strlen30(azArg[ii]);
  1918. if( n>2 && n<10 && 0==strncmp(azArg[ii], "--no-drop", n) ){
  1919. p->isNoDrop = 1;
  1920. }else if( n>2 && n<16 && 0==strncmp(azArg[ii], "--ignore-errors", n) ){
  1921. p->isIgnoreErrors = 1;
  1922. }else if( n>2 && n<7 && 0==strncmp(azArg[ii], "--exec", n) ){
  1923. p->isExec = 1;
  1924. }else{
  1925. fprintf(stderr, "unknown option: %s\n", azArg[ii]);
  1926. return -1;
  1927. }
  1928. }
  1929. return SQLITE_OK;
  1930. }
  1931. static int genfkeyCmdCb(void *pCtx, int eType, const char *z){
  1932. GenfkeyCmd *p = (GenfkeyCmd *)pCtx;
  1933. if( eType==GENFKEY_ERROR && !p->isIgnoreErrors ){
  1934. p->nErr++;
  1935. fprintf(stderr, "%s\n", z);
  1936. }
  1937. if( p->nErr==0 && (
  1938. (eType==GENFKEY_CREATETRIGGER)
  1939. || (eType==GENFKEY_DROPTRIGGER && !p->isNoDrop)
  1940. )){
  1941. if( p->isExec ){
  1942. sqlite3_exec(p->db, z, 0, 0, 0);
  1943. }else{
  1944. char *zCol = "sql";
  1945. callback((void *)p->pCb, 1, (char **)&z, (char **)&zCol);
  1946. }
  1947. }
  1948. return SQLITE_OK;
  1949. }
  1950. #endif
  1951. /*
  1952. ** Text of a help message
  1953. */
  1954. static char zHelp[] =
  1955. ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
  1956. ".bail ON|OFF Stop after hitting an error. Default OFF\n"
  1957. ".databases List names and files of attached databases\n"
  1958. ".dump ?TABLE? ... Dump the database in an SQL text format\n"
  1959. " If TABLE specified, only dump tables matching\n"
  1960. " LIKE pattern TABLE.\n"
  1961. ".echo ON|OFF Turn command echo on or off\n"
  1962. ".exit Exit this program\n"
  1963. ".explain ?ON|OFF? Turn output mode suitable for EXPLAIN on or off.\n"
  1964. " With no args, it turns EXPLAIN on.\n"
  1965. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_SUBQUERY)
  1966. ".genfkey ?OPTIONS? Options are:\n"
  1967. " --no-drop: Do not drop old fkey triggers.\n"
  1968. " --ignore-errors: Ignore tables with fkey errors\n"
  1969. " --exec: Execute generated SQL immediately\n"
  1970. " See file tool/genfkey.README in the source \n"
  1971. " distribution for further information.\n"
  1972. #endif
  1973. ".header(s) ON|OFF Turn display of headers on or off\n"
  1974. ".help Show this message\n"
  1975. ".import FILE TABLE Import data from FILE into TABLE\n"
  1976. ".indices ?TABLE? Show names of all indices\n"
  1977. " If TABLE specified, only show indices for tables\n"
  1978. " matching LIKE pattern TABLE.\n"
  1979. #ifdef SQLITE_ENABLE_IOTRACE
  1980. ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
  1981. #endif
  1982. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1983. ".load FILE ?ENTRY? Load an extension library\n"
  1984. #endif
  1985. ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
  1986. ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
  1987. " csv Comma-separated values\n"
  1988. " column Left-aligned columns. (See .width)\n"
  1989. " html HTML <table> code\n"
  1990. " insert SQL insert statements for TABLE\n"
  1991. " line One value per line\n"
  1992. " list Values delimited by .separator string\n"
  1993. " tabs Tab-separated values\n"
  1994. " tcl TCL list elements\n"
  1995. ".nullvalue STRING Print STRING in place of NULL values\n"
  1996. ".output FILENAME Send output to FILENAME\n"
  1997. ".output stdout Send output to the screen\n"
  1998. ".prompt MAIN CONTINUE Replace the standard prompts\n"
  1999. ".quit Exit this program\n"
  2000. ".read FILENAME Execute SQL in FILENAME\n"
  2001. ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
  2002. ".schema ?TABLE? Show the CREATE statements\n"
  2003. " If TABLE specified, only show tables matching\n"
  2004. " LIKE pattern TABLE.\n"
  2005. ".separator STRING Change separator used by output mode and .import\n"
  2006. ".show Show the current values for various settings\n"
  2007. ".tables ?TABLE? List names of tables\n"
  2008. " If TABLE specified, only list tables matching\n"
  2009. " LIKE pattern TABLE.\n"
  2010. ".timeout MS Try opening locked tables for MS milliseconds\n"
  2011. ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
  2012. ;
  2013. static char zTimerHelp[] =
  2014. ".timer ON|OFF Turn the CPU timer measurement on or off\n"
  2015. ;
  2016. /* Forward reference */
  2017. static int process_input(struct callback_data *p, FILE *in);
  2018. /*
  2019. ** Make sure the database is open. If it is not, then open it. If
  2020. ** the database fails to open, print an error message and exit.
  2021. */
  2022. static void open_db(struct callback_data *p){
  2023. if( p->db==0 ){
  2024. sqlite3_open(p->zDbFilename, &p->db);
  2025. db = p->db;
  2026. if( db && sqlite3_errcode(db)==SQLITE_OK ){
  2027. sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0,
  2028. shellstaticFunc, 0, 0);
  2029. }
  2030. if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){
  2031. fprintf(stderr,"Error: unable to open database \"%s\": %s\n",
  2032. p->zDbFilename, sqlite3_errmsg(db));
  2033. exit(1);
  2034. }
  2035. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  2036. sqlite3_enable_load_extension(p->db, 1);
  2037. #endif
  2038. }
  2039. }
  2040. /*
  2041. ** Do C-language style dequoting.
  2042. **
  2043. ** \t -> tab
  2044. ** \n -> newline
  2045. ** \r -> carriage return
  2046. ** \NNN -> ascii character NNN in octal
  2047. ** \\ -> backslash
  2048. */
  2049. static void resolve_backslashes(char *z){
  2050. int i, j;
  2051. char c;
  2052. for(i=j=0; (c = z[i])!=0; i++, j++){
  2053. if( c=='\\' ){
  2054. c = z[++i];
  2055. if( c=='n' ){
  2056. c = '\n';
  2057. }else if( c=='t' ){
  2058. c = '\t';
  2059. }else if( c=='r' ){
  2060. c = '\r';
  2061. }else if( c>='0' && c<='7' ){
  2062. c -= '0';
  2063. if( z[i+1]>='0' && z[i+1]<='7' ){
  2064. i++;
  2065. c = (c<<3) + z[i] - '0';
  2066. if( z[i+1]>='0' && z[i+1]<='7' ){
  2067. i++;
  2068. c = (c<<3) + z[i] - '0';
  2069. }
  2070. }
  2071. }
  2072. }
  2073. z[j] = c;
  2074. }
  2075. z[j] = 0;
  2076. }
  2077. /*
  2078. ** Interpret zArg as a boolean value. Return either 0 or 1.
  2079. */
  2080. static int booleanValue(char *zArg){
  2081. int val = atoi(zArg);
  2082. int j;
  2083. for(j=0; zArg[j]; j++){
  2084. zArg[j] = (char)tolower(zArg[j]);
  2085. }
  2086. if( strcmp(zArg,"on")==0 ){
  2087. val = 1;
  2088. }else if( strcmp(zArg,"yes")==0 ){
  2089. val = 1;
  2090. }
  2091. return val;
  2092. }
  2093. /*
  2094. ** If an input line begins with "." then invoke this routine to
  2095. ** process that line.
  2096. **
  2097. ** Return 1 on error, 2 to exit, and 0 otherwise.
  2098. */
  2099. static int do_meta_command(char *zLine, struct callback_data *p){
  2100. int i = 1;
  2101. int nArg = 0;
  2102. int n, c;
  2103. int rc = 0;
  2104. char *azArg[50];
  2105. /* Parse the input line into tokens.
  2106. */
  2107. while( zLine[i] && nArg<ArraySize(azArg) ){
  2108. while( isspace((unsigned char)zLine[i]) ){ i++; }
  2109. if( zLine[i]==0 ) break;
  2110. if( zLine[i]=='\'' || zLine[i]=='"' ){
  2111. int delim = zLine[i++];
  2112. azArg[nArg++] = &zLine[i];
  2113. while( zLine[i] && zLine[i]!=delim ){ i++; }
  2114. if( zLine[i]==delim ){
  2115. zLine[i++] = 0;
  2116. }
  2117. if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  2118. }else{
  2119. azArg[nArg++] = &zLine[i];
  2120. while( zLine[i] && !isspace((unsigned char)zLine[i]) ){ i++; }
  2121. if( zLine[i] ) zLine[i++] = 0;
  2122. resolve_backslashes(azArg[nArg-1]);
  2123. }
  2124. }
  2125. /* Process the input line.
  2126. */
  2127. if( nArg==0 ) return 0; /* no tokens, no error */
  2128. n = strlen30(azArg[0]);
  2129. c = azArg[0][0];
  2130. if( c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0 && nArg>1 && nArg<4){
  2131. const char *zDestFile;
  2132. const char *zDb;
  2133. sqlite3 *pDest;
  2134. sqlite3_backup *pBackup;
  2135. if( nArg==2 ){
  2136. zDestFile = azArg[1];
  2137. zDb = "main";
  2138. }else{
  2139. zDestFile = azArg[2];
  2140. zDb = azArg[1];
  2141. }
  2142. rc = sqlite3_open(zDestFile, &pDest);
  2143. if( rc!=SQLITE_OK ){
  2144. fprintf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  2145. sqlite3_close(pDest);
  2146. return 1;
  2147. }
  2148. open_db(p);
  2149. pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  2150. if( pBackup==0 ){
  2151. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  2152. sqlite3_close(pDest);
  2153. return 1;
  2154. }
  2155. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  2156. sqlite3_backup_finish(pBackup);
  2157. if( rc==SQLITE_DONE ){
  2158. rc = 0;
  2159. }else{
  2160. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  2161. rc = 1;
  2162. }
  2163. sqlite3_close(pDest);
  2164. }else
  2165. if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 && nArg>1 && nArg<3 ){
  2166. bail_on_error = booleanValue(azArg[1]);
  2167. }else
  2168. if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 && nArg==1 ){
  2169. struct callback_data data;
  2170. char *zErrMsg = 0;
  2171. open_db(p);
  2172. memcpy(&data, p, sizeof(data));
  2173. data.showHeader = 1;
  2174. data.mode = MODE_Column;
  2175. data.colWidth[0] = 3;
  2176. data.colWidth[1] = 15;
  2177. data.colWidth[2] = 58;
  2178. data.cnt = 0;
  2179. sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
  2180. if( zErrMsg ){
  2181. fprintf(stderr,"Error: %s\n", zErrMsg);
  2182. sqlite3_free(zErrMsg);
  2183. rc = 1;
  2184. }
  2185. }else
  2186. if( c=='d' && strncmp(azArg[0], "dump", n)==0 && nArg<3 ){
  2187. char *zErrMsg = 0;
  2188. open_db(p);
  2189. /* When playing back a "dump", the content might appear in an order
  2190. ** which causes immediate foreign key constraints to be violated.
  2191. ** So disable foreign-key constraint enforcement to prevent problems. */
  2192. fprintf(p->out, "PRAGMA foreign_keys=OFF;\n");
  2193. fprintf(p->out, "BEGIN TRANSACTION;\n");
  2194. p->writableSchema = 0;
  2195. sqlite3_exec(p->db, "PRAGMA writable_schema=ON", 0, 0, 0);
  2196. if( nArg==1 ){
  2197. run_schema_dump_query(p,
  2198. "SELECT name, type, sql FROM sqlite_master "
  2199. "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'", 0
  2200. );
  2201. run_schema_dump_query(p,
  2202. "SELECT name, type, sql FROM sqlite_master "
  2203. "WHERE name=='sqlite_sequence'", 0
  2204. );
  2205. run_table_dump_query(p->out, p->db,
  2206. "SELECT sql FROM sqlite_master "
  2207. "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
  2208. );
  2209. }else{
  2210. int i;
  2211. for(i=1; i<nArg; i++){
  2212. zShellStatic = azArg[i];
  2213. run_schema_dump_query(p,
  2214. "SELECT name, type, sql FROM sqlite_master "
  2215. "WHERE tbl_name LIKE shellstatic() AND type=='table'"
  2216. " AND sql NOT NULL", 0);
  2217. run_table_dump_query(p->out, p->db,
  2218. "SELECT sql FROM sqlite_master "
  2219. "WHERE sql NOT NULL"
  2220. " AND type IN ('index','trigger','view')"
  2221. " AND tbl_name LIKE shellstatic()", 0
  2222. );
  2223. zShellStatic = 0;
  2224. }
  2225. }
  2226. if( p->writableSchema ){
  2227. fprintf(p->out, "PRAGMA writable_schema=OFF;\n");
  2228. p->writableSchema = 0;
  2229. }
  2230. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF", 0, 0, 0);
  2231. if( zErrMsg ){
  2232. fprintf(stderr,"Error: %s\n", zErrMsg);
  2233. sqlite3_free(zErrMsg);
  2234. }else{
  2235. fprintf(p->out, "COMMIT;\n");
  2236. }
  2237. }else
  2238. if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 && nArg<3 ){
  2239. p->echoOn = booleanValue(azArg[1]);
  2240. }else
  2241. if( c=='e' && strncmp(azArg[0], "exit", n)==0 && nArg==1 ){
  2242. rc = 2;
  2243. }else
  2244. if( c=='e' && strncmp(azArg[0], "explain", n)==0 && nArg<3 ){
  2245. int val = nArg>=2 ? booleanValue(azArg[1]) : 1;
  2246. if(val == 1) {
  2247. if(!p->explainPrev.valid) {
  2248. p->explainPrev.valid = 1;
  2249. p->explainPrev.mode = p->mode;
  2250. p->explainPrev.showHeader = p->showHeader;
  2251. memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth));
  2252. }
  2253. /* We could put this code under the !p->explainValid
  2254. ** condition so that it does not execute if we are already in
  2255. ** explain mode. However, always executing it allows us an easy
  2256. ** was to reset to explain mode in case the user previously
  2257. ** did an .explain followed by a .width, .mode or .header
  2258. ** command.
  2259. */
  2260. p->mode = MODE_Explain;
  2261. p->showHeader = 1;
  2262. memset(p->colWidth,0,ArraySize(p->colWidth));
  2263. p->colWidth[0] = 4; /* addr */
  2264. p->colWidth[1] = 13; /* opcode */
  2265. p->colWidth[2] = 4; /* P1 */
  2266. p->colWidth[3] = 4; /* P2 */
  2267. p->colWidth[4] = 4; /* P3 */
  2268. p->colWidth[5] = 13; /* P4 */
  2269. p->colWidth[6] = 2; /* P5 */
  2270. p->colWidth[7] = 13; /* Comment */
  2271. }else if (p->explainPrev.valid) {
  2272. p->explainPrev.valid = 0;
  2273. p->mode = p->explainPrev.mode;
  2274. p->showHeader = p->explainPrev.showHeader;
  2275. memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth));
  2276. }
  2277. }else
  2278. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_SUBQUERY)
  2279. if( c=='g' && strncmp(azArg[0], "genfkey", n)==0 ){
  2280. GenfkeyCmd cmd;
  2281. if( 0==genfkeyParseArgs(&cmd, &azArg[1], nArg-1) ){
  2282. cmd.db = p->db;
  2283. cmd.pCb = p;
  2284. genfkey_create_triggers(p->db, "main", (void *)&cmd, genfkeyCmdCb);
  2285. }
  2286. }else
  2287. #endif
  2288. if( c=='h' && (strncmp(azArg[0], "header", n)==0 ||
  2289. strncmp(azArg[0], "headers", n)==0) && nArg>1 && nArg<3 ){
  2290. p->showHeader = booleanValue(azArg[1]);
  2291. }else
  2292. if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  2293. fprintf(stderr,"%s",zHelp);
  2294. if( HAS_TIMER ){
  2295. fprintf(stderr,"%s",zTimerHelp);
  2296. }
  2297. }else
  2298. if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg==3 ){
  2299. char *zTable = azArg[2]; /* Insert data into this table */
  2300. char *zFile = azArg[1]; /* The file from which to extract data */
  2301. sqlite3_stmt *pStmt = NULL; /* A statement */
  2302. int nCol; /* Number of columns in the table */
  2303. int nByte; /* Number of bytes in an SQL string */
  2304. int i, j; /* Loop counters */
  2305. int nSep; /* Number of bytes in p->separator[] */
  2306. char *zSql; /* An SQL statement */
  2307. char *zLine; /* A single line of input from the file */
  2308. char **azCol; /* zLine[] broken up into columns */
  2309. char *zCommit; /* How to commit changes */
  2310. FILE *in; /* The input file */
  2311. int lineno = 0; /* Line number of input file */
  2312. open_db(p);
  2313. nSep = strlen30(p->separator);
  2314. if( nSep==0 ){
  2315. fprintf(stderr, "Error: non-null separator required for import\n");
  2316. return 1;
  2317. }
  2318. zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
  2319. if( zSql==0 ){
  2320. fprintf(stderr, "Error: out of memory\n");
  2321. return 1;
  2322. }
  2323. nByte = strlen30(zSql);
  2324. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  2325. sqlite3_free(zSql);
  2326. if( rc ){
  2327. if (pStmt) sqlite3_finalize(pStmt);
  2328. fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
  2329. return 1;
  2330. }
  2331. nCol = sqlite3_column_count(pStmt);
  2332. sqlite3_finalize(pStmt);
  2333. pStmt = 0;
  2334. if( nCol==0 ) return 0; /* no columns, no error */
  2335. zSql = malloc( nByte + 20 + nCol*2 );
  2336. if( zSql==0 ){
  2337. fprintf(stderr, "Error: out of memory\n");
  2338. return 1;
  2339. }
  2340. sqlite3_snprintf(nByte+20, zSql, "INSERT INTO '%q' VALUES(?", zTable);
  2341. j = strlen30(zSql);
  2342. for(i=1; i<nCol; i++){
  2343. zSql[j++] = ',';
  2344. zSql[j++] = '?';
  2345. }
  2346. zSql[j++] = ')';
  2347. zSql[j] = 0;
  2348. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  2349. free(zSql);
  2350. if( rc ){
  2351. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
  2352. if (pStmt) sqlite3_finalize(pStmt);
  2353. return 1;
  2354. }
  2355. in = fopen(zFile, "rb");
  2356. if( in==0 ){
  2357. fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
  2358. sqlite3_finalize(pStmt);
  2359. return 1;
  2360. }
  2361. azCol = malloc( sizeof(azCol[0])*(nCol+1) );
  2362. if( azCol==0 ){
  2363. fprintf(stderr, "Error: out of memory\n");
  2364. fclose(in);
  2365. sqlite3_finalize(pStmt);
  2366. return 1;
  2367. }
  2368. sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
  2369. zCommit = "COMMIT";
  2370. while( (zLine = local_getline(0, in))!=0 ){
  2371. char *z;
  2372. i = 0;
  2373. lineno++;
  2374. azCol[0] = zLine;
  2375. for(i=0, z=zLine; *z && *z!='\n' && *z!='\r'; z++){
  2376. if( *z==p->separator[0] && strncmp(z, p->separator, nSep)==0 ){
  2377. *z = 0;
  2378. i++;
  2379. if( i<nCol ){
  2380. azCol[i] = &z[nSep];
  2381. z += nSep-1;
  2382. }
  2383. }
  2384. } /* end for */
  2385. *z = 0;
  2386. if( i+1!=nCol ){
  2387. fprintf(stderr,
  2388. "Error: %s line %d: expected %d columns of data but found %d\n",
  2389. zFile, lineno, nCol, i+1);
  2390. zCommit = "ROLLBACK";
  2391. free(zLine);
  2392. rc = 1;
  2393. break; /* from while */
  2394. }
  2395. for(i=0; i<nCol; i++){
  2396. sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
  2397. }
  2398. sqlite3_step(pStmt);
  2399. rc = sqlite3_reset(pStmt);
  2400. free(zLine);
  2401. if( rc!=SQLITE_OK ){
  2402. fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
  2403. zCommit = "ROLLBACK";
  2404. rc = 1;
  2405. break; /* from while */
  2406. }
  2407. } /* end while */
  2408. free(azCol);
  2409. fclose(in);
  2410. sqlite3_finalize(pStmt);
  2411. sqlite3_exec(p->db, zCommit, 0, 0, 0);
  2412. }else
  2413. if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg<3 ){
  2414. struct callback_data data;
  2415. char *zErrMsg = 0;
  2416. open_db(p);
  2417. memcpy(&data, p, sizeof(data));
  2418. data.showHeader = 0;
  2419. data.mode = MODE_List;
  2420. if( nArg==1 ){
  2421. rc = sqlite3_exec(p->db,
  2422. "SELECT name FROM sqlite_master "
  2423. "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
  2424. "UNION ALL "
  2425. "SELECT name FROM sqlite_temp_master "
  2426. "WHERE type='index' "
  2427. "ORDER BY 1",
  2428. callback, &data, &zErrMsg
  2429. );
  2430. }else{
  2431. zShellStatic = azArg[1];
  2432. rc = sqlite3_exec(p->db,
  2433. "SELECT name FROM sqlite_master "
  2434. "WHERE type='index' AND tbl_name LIKE shellstatic() "
  2435. "UNION ALL "
  2436. "SELECT name FROM sqlite_temp_master "
  2437. "WHERE type='index' AND tbl_name LIKE shellstatic() "
  2438. "ORDER BY 1",
  2439. callback, &data, &zErrMsg
  2440. );
  2441. zShellStatic = 0;
  2442. }
  2443. if( zErrMsg ){
  2444. fprintf(stderr,"Error: %s\n", zErrMsg);
  2445. sqlite3_free(zErrMsg);
  2446. rc = 1;
  2447. }else if( rc != SQLITE_OK ){
  2448. fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
  2449. rc = 1;
  2450. }
  2451. }else
  2452. #ifdef SQLITE_ENABLE_IOTRACE
  2453. if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
  2454. extern void (*sqlite3IoTrace)(const char*, ...);
  2455. if( iotrace && iotrace!=stdout ) fclose(iotrace);
  2456. iotrace = 0;
  2457. if( nArg<2 ){
  2458. sqlite3IoTrace = 0;
  2459. }else if( strcmp(azArg[1], "-")==0 ){
  2460. sqlite3IoTrace = iotracePrintf;
  2461. iotrace = stdout;
  2462. }else{
  2463. iotrace = fopen(azArg[1], "w");
  2464. if( iotrace==0 ){
  2465. fprintf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  2466. sqlite3IoTrace = 0;
  2467. rc = 1;
  2468. }else{
  2469. sqlite3IoTrace = iotracePrintf;
  2470. }
  2471. }
  2472. }else
  2473. #endif
  2474. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  2475. if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){
  2476. const char *zFile, *zProc;
  2477. char *zErrMsg = 0;
  2478. zFile = azArg[1];
  2479. zProc = nArg>=3 ? azArg[2] : 0;
  2480. open_db(p);
  2481. rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  2482. if( rc!=SQLITE_OK ){
  2483. fprintf(stderr, "Error: %s\n", zErrMsg);
  2484. sqlite3_free(zErrMsg);
  2485. rc = 1;
  2486. }
  2487. }else
  2488. #endif
  2489. if( c=='l' && strncmp(azArg[0], "log", n)==0 && nArg>=1 ){
  2490. const char *zFile = azArg[1];
  2491. if( p->pLog && p->pLog!=stdout && p->pLog!=stderr ){
  2492. fclose(p->pLog);
  2493. p->pLog = 0;
  2494. }
  2495. if( strcmp(zFile,"stdout")==0 ){
  2496. p->pLog = stdout;
  2497. }else if( strcmp(zFile, "stderr")==0 ){
  2498. p->pLog = stderr;
  2499. }else if( strcmp(zFile, "off")==0 ){
  2500. p->pLog = 0;
  2501. }else{
  2502. p->pLog = fopen(zFile, "w");
  2503. if( p->pLog==0 ){
  2504. fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
  2505. }
  2506. }
  2507. }else
  2508. if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==2 ){
  2509. int n2 = strlen30(azArg[1]);
  2510. if( (n2==4 && strncmp(azArg[1],"line",n2)==0)
  2511. ||
  2512. (n2==5 && strncmp(azArg[1],"lines",n2)==0) ){
  2513. p->mode = MODE_Line;
  2514. }else if( (n2==6 && strncmp(azArg[1],"column",n2)==0)
  2515. ||
  2516. (n2==7 && strncmp(azArg[1],"columns",n2)==0) ){
  2517. p->mode = MODE_Column;
  2518. }else if( n2==4 && strncmp(azArg[1],"list",n2)==0 ){
  2519. p->mode = MODE_List;
  2520. }else if( n2==4 && strncmp(azArg[1],"html",n2)==0 ){
  2521. p->mode = MODE_Html;
  2522. }else if( n2==3 && strncmp(azArg[1],"tcl",n2)==0 ){
  2523. p->mode = MODE_Tcl;
  2524. }else if( n2==3 && strncmp(azArg[1],"csv",n2)==0 ){
  2525. p->mode = MODE_Csv;
  2526. sqlite3_snprintf(sizeof(p->separator), p->separator, ",");
  2527. }else if( n2==4 && strncmp(azArg[1],"tabs",n2)==0 ){
  2528. p->mode = MODE_List;
  2529. sqlite3_snprintf(sizeof(p->separator), p->separator, "\t");
  2530. }else if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){
  2531. p->mode = MODE_Insert;
  2532. set_table_name(p, "table");
  2533. }else {
  2534. fprintf(stderr,"Error: mode should be one of: "
  2535. "column csv html insert line list tabs tcl\n");
  2536. rc = 1;
  2537. }
  2538. }else
  2539. if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==3 ){
  2540. int n2 = strlen30(azArg[1]);
  2541. if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){
  2542. p->mode = MODE_Insert;
  2543. set_table_name(p, azArg[2]);
  2544. }else {
  2545. fprintf(stderr, "Error: invalid arguments: "
  2546. " \"%s\". Enter \".help\" for help\n", azArg[2]);
  2547. rc = 1;
  2548. }
  2549. }else
  2550. if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
  2551. sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue,
  2552. "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
  2553. }else
  2554. if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
  2555. if( p->out!=stdout ){
  2556. fclose(p->out);
  2557. }
  2558. if( strcmp(azArg[1],"stdout")==0 ){
  2559. p->out = stdout;
  2560. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "stdout");
  2561. }else{
  2562. p->out = fopen(azArg[1], "wb");
  2563. if( p->out==0 ){
  2564. fprintf(stderr,"Error: cannot write to \"%s\"\n", azArg[1]);
  2565. p->out = stdout;
  2566. rc = 1;
  2567. } else {
  2568. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
  2569. }
  2570. }
  2571. }else
  2572. if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){
  2573. if( nArg >= 2) {
  2574. strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  2575. }
  2576. if( nArg >= 3) {
  2577. strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  2578. }
  2579. }else
  2580. if( c=='q' && strncmp(azArg[0], "quit", n)==0 && nArg==1 ){
  2581. rc = 2;
  2582. }else
  2583. if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 && nArg==2 ){
  2584. FILE *alt = fopen(azArg[1], "rb");
  2585. if( alt==0 ){
  2586. fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
  2587. rc = 1;
  2588. }else{
  2589. rc = process_input(p, alt);
  2590. fclose(alt);
  2591. }
  2592. }else
  2593. if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 && nArg>1 && nArg<4){
  2594. const char *zSrcFile;
  2595. const char *zDb;
  2596. sqlite3 *pSrc;
  2597. sqlite3_backup *pBackup;
  2598. int nTimeout = 0;
  2599. if( nArg==2 ){
  2600. zSrcFile = azArg[1];
  2601. zDb = "main";
  2602. }else{
  2603. zSrcFile = azArg[2];
  2604. zDb = azArg[1];
  2605. }
  2606. rc = sqlite3_open(zSrcFile, &pSrc);
  2607. if( rc!=SQLITE_OK ){
  2608. fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  2609. sqlite3_close(pSrc);
  2610. return 1;
  2611. }
  2612. open_db(p);
  2613. pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  2614. if( pBackup==0 ){
  2615. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  2616. sqlite3_close(pSrc);
  2617. return 1;
  2618. }
  2619. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  2620. || rc==SQLITE_BUSY ){
  2621. if( rc==SQLITE_BUSY ){
  2622. if( nTimeout++ >= 3 ) break;
  2623. sqlite3_sleep(100);
  2624. }
  2625. }
  2626. sqlite3_backup_finish(pBackup);
  2627. if( rc==SQLITE_DONE ){
  2628. rc = 0;
  2629. }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  2630. fprintf(stderr, "Error: source database is busy\n");
  2631. rc = 1;
  2632. }else{
  2633. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  2634. rc = 1;
  2635. }
  2636. sqlite3_close(pSrc);
  2637. }else
  2638. if( c=='s' && strncmp(azArg[0], "schema", n)==0 && nArg<3 ){
  2639. struct callback_data data;
  2640. char *zErrMsg = 0;
  2641. open_db(p);
  2642. memcpy(&data, p, sizeof(data));
  2643. data.showHeader = 0;
  2644. data.mode = MODE_Semi;
  2645. if( nArg>1 ){
  2646. int i;
  2647. for(i=0; azArg[1][i]; i++) azArg[1][i] = (char)tolower(azArg[1][i]);
  2648. if( strcmp(azArg[1],"sqlite_master")==0 ){
  2649. char *new_argv[2], *new_colv[2];
  2650. new_argv[0] = "CREATE TABLE sqlite_master (\n"
  2651. " type text,\n"
  2652. " name text,\n"
  2653. " tbl_name text,\n"
  2654. " rootpage integer,\n"
  2655. " sql text\n"
  2656. ")";
  2657. new_argv[1] = 0;
  2658. new_colv[0] = "sql";
  2659. new_colv[1] = 0;
  2660. callback(&data, 1, new_argv, new_colv);
  2661. rc = SQLITE_OK;
  2662. }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
  2663. char *new_argv[2], *new_colv[2];
  2664. new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
  2665. " type text,\n"
  2666. " name text,\n"
  2667. " tbl_name text,\n"
  2668. " rootpage integer,\n"
  2669. " sql text\n"
  2670. ")";
  2671. new_argv[1] = 0;
  2672. new_colv[0] = "sql";
  2673. new_colv[1] = 0;
  2674. callback(&data, 1, new_argv, new_colv);
  2675. rc = SQLITE_OK;
  2676. }else{
  2677. zShellStatic = azArg[1];
  2678. rc = sqlite3_exec(p->db,
  2679. "SELECT sql FROM "
  2680. " (SELECT sql sql, type type, tbl_name tbl_name, name name"
  2681. " FROM sqlite_master UNION ALL"
  2682. " SELECT sql, type, tbl_name, name FROM sqlite_temp_master) "
  2683. "WHERE tbl_name LIKE shellstatic() AND type!='meta' AND sql NOTNULL "
  2684. "ORDER BY substr(type,2,1), name",
  2685. callback, &data, &zErrMsg);
  2686. zShellStatic = 0;
  2687. }
  2688. }else{
  2689. rc = sqlite3_exec(p->db,
  2690. "SELECT sql FROM "
  2691. " (SELECT sql sql, type type, tbl_name tbl_name, name name"
  2692. " FROM sqlite_master UNION ALL"
  2693. " SELECT sql, type, tbl_name, name FROM sqlite_temp_master) "
  2694. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'"
  2695. "ORDER BY substr(type,2,1), name",
  2696. callback, &data, &zErrMsg
  2697. );
  2698. }
  2699. if( zErrMsg ){
  2700. fprintf(stderr,"Error: %s\n", zErrMsg);
  2701. sqlite3_free(zErrMsg);
  2702. rc = 1;
  2703. }else if( rc != SQLITE_OK ){
  2704. fprintf(stderr,"Error: querying schema information\n");
  2705. rc = 1;
  2706. }else{
  2707. rc = 0;
  2708. }
  2709. }else
  2710. if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
  2711. sqlite3_snprintf(sizeof(p->separator), p->separator,
  2712. "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
  2713. }else
  2714. if( c=='s' && strncmp(azArg[0], "show", n)==0 && nArg==1 ){
  2715. int i;
  2716. fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
  2717. fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
  2718. fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
  2719. fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
  2720. fprintf(p->out,"%9.9s: ", "nullvalue");
  2721. output_c_string(p->out, p->nullvalue);
  2722. fprintf(p->out, "\n");
  2723. fprintf(p->out,"%9.9s: %s\n","output",
  2724. strlen30(p->outfile) ? p->outfile : "stdout");
  2725. fprintf(p->out,"%9.9s: ", "separator");
  2726. output_c_string(p->out, p->separator);
  2727. fprintf(p->out, "\n");
  2728. fprintf(p->out,"%9.9s: ","width");
  2729. for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
  2730. fprintf(p->out,"%d ",p->colWidth[i]);
  2731. }
  2732. fprintf(p->out,"\n");
  2733. }else
  2734. if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 && nArg<3 ){
  2735. char **azResult;
  2736. int nRow;
  2737. char *zErrMsg;
  2738. open_db(p);
  2739. if( nArg==1 ){
  2740. rc = sqlite3_get_table(p->db,
  2741. "SELECT name FROM sqlite_master "
  2742. "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' "
  2743. "UNION ALL "
  2744. "SELECT name FROM sqlite_temp_master "
  2745. "WHERE type IN ('table','view') "
  2746. "ORDER BY 1",
  2747. &azResult, &nRow, 0, &zErrMsg
  2748. );
  2749. }else{
  2750. zShellStatic = azArg[1];
  2751. rc = sqlite3_get_table(p->db,
  2752. "SELECT name FROM sqlite_master "
  2753. "WHERE type IN ('table','view') AND name LIKE shellstatic() "
  2754. "UNION ALL "
  2755. "SELECT name FROM sqlite_temp_master "
  2756. "WHERE type IN ('table','view') AND name LIKE shellstatic() "
  2757. "ORDER BY 1",
  2758. &azResult, &nRow, 0, &zErrMsg
  2759. );
  2760. zShellStatic = 0;
  2761. }
  2762. if( zErrMsg ){
  2763. fprintf(stderr,"Error: %s\n", zErrMsg);
  2764. sqlite3_free(zErrMsg);
  2765. rc = 1;
  2766. }else if( rc != SQLITE_OK ){
  2767. fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
  2768. rc = 1;
  2769. }else{
  2770. int len, maxlen = 0;
  2771. int i, j;
  2772. int nPrintCol, nPrintRow;
  2773. for(i=1; i<=nRow; i++){
  2774. if( azResult[i]==0 ) continue;
  2775. len = strlen30(azResult[i]);
  2776. if( len>maxlen ) maxlen = len;
  2777. }
  2778. nPrintCol = 80/(maxlen+2);
  2779. if( nPrintCol<1 ) nPrintCol = 1;
  2780. nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  2781. for(i=0; i<nPrintRow; i++){
  2782. for(j=i+1; j<=nRow; j+=nPrintRow){
  2783. char *zSp = j<=nPrintRow ? "" : " ";
  2784. printf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : "");
  2785. }
  2786. printf("\n");
  2787. }
  2788. }
  2789. sqlite3_free_table(azResult);
  2790. }else
  2791. if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg==2 ){
  2792. open_db(p);
  2793. sqlite3_busy_timeout(p->db, atoi(azArg[1]));
  2794. }else
  2795. if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 && nArg==2 ){
  2796. enableTimer = booleanValue(azArg[1]);
  2797. }else
  2798. if( c=='w' && strncmp(azArg[0], "width", n)==0 && nArg>1 ){
  2799. int j;
  2800. assert( nArg<=ArraySize(azArg) );
  2801. for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
  2802. p->colWidth[j-1] = atoi(azArg[j]);
  2803. }
  2804. }else
  2805. {
  2806. fprintf(stderr, "Error: unknown command or invalid arguments: "
  2807. " \"%s\". Enter \".help\" for help\n", azArg[0]);
  2808. rc = 1;
  2809. }
  2810. return rc;
  2811. }
  2812. /*
  2813. ** Return TRUE if a semicolon occurs anywhere in the first N characters
  2814. ** of string z[].
  2815. */
  2816. static int _contains_semicolon(const char *z, int N){
  2817. int i;
  2818. for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
  2819. return 0;
  2820. }
  2821. /*
  2822. ** Test to see if a line consists entirely of whitespace.
  2823. */
  2824. static int _all_whitespace(const char *z){
  2825. for(; *z; z++){
  2826. if( isspace(*(unsigned char*)z) ) continue;
  2827. if( *z=='/' && z[1]=='*' ){
  2828. z += 2;
  2829. while( *z && (*z!='*' || z[1]!='/') ){ z++; }
  2830. if( *z==0 ) return 0;
  2831. z++;
  2832. continue;
  2833. }
  2834. if( *z=='-' && z[1]=='-' ){
  2835. z += 2;
  2836. while( *z && *z!='\n' ){ z++; }
  2837. if( *z==0 ) return 1;
  2838. continue;
  2839. }
  2840. return 0;
  2841. }
  2842. return 1;
  2843. }
  2844. /*
  2845. ** Return TRUE if the line typed in is an SQL command terminator other
  2846. ** than a semi-colon. The SQL Server style "go" command is understood
  2847. ** as is the Oracle "/".
  2848. */
  2849. static int _is_command_terminator(const char *zLine){
  2850. while( isspace(*(unsigned char*)zLine) ){ zLine++; };
  2851. if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
  2852. return 1; /* Oracle */
  2853. }
  2854. if( tolower(zLine[0])=='g' && tolower(zLine[1])=='o'
  2855. && _all_whitespace(&zLine[2]) ){
  2856. return 1; /* SQL Server */
  2857. }
  2858. return 0;
  2859. }
  2860. /*
  2861. ** Return true if zSql is a complete SQL statement. Return false if it
  2862. ** ends in the middle of a string literal or C-style comment.
  2863. */
  2864. static int _is_complete(char *zSql, int nSql){
  2865. int rc;
  2866. if( zSql==0 ) return 1;
  2867. zSql[nSql] = ';';
  2868. zSql[nSql+1] = 0;
  2869. rc = sqlite3_complete(zSql);
  2870. zSql[nSql] = 0;
  2871. return rc;
  2872. }
  2873. /*
  2874. ** Read input from *in and process it. If *in==0 then input
  2875. ** is interactive - the user is typing it it. Otherwise, input
  2876. ** is coming from a file or device. A prompt is issued and history
  2877. ** is saved only if input is interactive. An interrupt signal will
  2878. ** cause this routine to exit immediately, unless input is interactive.
  2879. **
  2880. ** Return the number of errors.
  2881. */
  2882. static int process_input(struct callback_data *p, FILE *in){
  2883. char *zLine = 0;
  2884. char *zSql = 0;
  2885. int nSql = 0;
  2886. int nSqlPrior = 0;
  2887. char *zErrMsg;
  2888. int rc;
  2889. int errCnt = 0;
  2890. int lineno = 0;
  2891. int startline = 0;
  2892. while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
  2893. fflush(p->out);
  2894. free(zLine);
  2895. zLine = one_input_line(zSql, in);
  2896. if( zLine==0 ){
  2897. break; /* We have reached EOF */
  2898. }
  2899. if( seenInterrupt ){
  2900. if( in!=0 ) break;
  2901. seenInterrupt = 0;
  2902. }
  2903. lineno++;
  2904. if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue;
  2905. if( zLine && zLine[0]=='.' && nSql==0 ){
  2906. if( p->echoOn ) printf("%s\n", zLine);
  2907. rc = do_meta_command(zLine, p);
  2908. if( rc==2 ){ /* exit requested */
  2909. break;
  2910. }else if( rc ){
  2911. errCnt++;
  2912. }
  2913. continue;
  2914. }
  2915. if( _is_command_terminator(zLine) && _is_complete(zSql, nSql) ){
  2916. memcpy(zLine,";",2);
  2917. }
  2918. nSqlPrior = nSql;
  2919. if( zSql==0 ){
  2920. int i;
  2921. for(i=0; zLine[i] && isspace((unsigned char)zLine[i]); i++){}
  2922. if( zLine[i]!=0 ){
  2923. nSql = strlen30(zLine);
  2924. zSql = malloc( nSql+3 );
  2925. if( zSql==0 ){
  2926. fprintf(stderr, "Error: out of memory\n");
  2927. exit(1);
  2928. }
  2929. memcpy(zSql, zLine, nSql+1);
  2930. startline = lineno;
  2931. }
  2932. }else{
  2933. int len = strlen30(zLine);
  2934. zSql = realloc( zSql, nSql + len + 4 );
  2935. if( zSql==0 ){
  2936. fprintf(stderr,"Error: out of memory\n");
  2937. exit(1);
  2938. }
  2939. zSql[nSql++] = '\n';
  2940. memcpy(&zSql[nSql], zLine, len+1);
  2941. nSql += len;
  2942. }
  2943. if( zSql && _contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  2944. && sqlite3_complete(zSql) ){
  2945. p->cnt = 0;
  2946. open_db(p);
  2947. BEGIN_TIMER;
  2948. rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
  2949. END_TIMER;
  2950. if( rc || zErrMsg ){
  2951. char zPrefix[100];
  2952. if( in!=0 || !stdin_is_interactive ){
  2953. sqlite3_snprintf(sizeof(zPrefix), zPrefix,
  2954. "Error: near line %d:", startline);
  2955. }else{
  2956. sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
  2957. }
  2958. if( zErrMsg!=0 ){
  2959. fprintf(stderr, "%s %s\n", zPrefix, zErrMsg);
  2960. sqlite3_free(zErrMsg);
  2961. zErrMsg = 0;
  2962. }else{
  2963. fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
  2964. }
  2965. errCnt++;
  2966. }
  2967. free(zSql);
  2968. zSql = 0;
  2969. nSql = 0;
  2970. }
  2971. }
  2972. if( zSql ){
  2973. if( !_all_whitespace(zSql) ) fprintf(stderr, "Error: incomplete SQL: %s\n", zSql);
  2974. free(zSql);
  2975. }
  2976. free(zLine);
  2977. return errCnt;
  2978. }
  2979. /*
  2980. ** Return a pathname which is the user's home directory. A
  2981. ** 0 return indicates an error of some kind. Space to hold the
  2982. ** resulting string is obtained from malloc(). The calling
  2983. ** function should free the result.
  2984. */
  2985. static char *find_home_dir(void){
  2986. char *home_dir = NULL;
  2987. #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(_WIN32_WCE) && !defined(__RTP__) && !defined(_WRS_KERNEL)
  2988. struct passwd *pwent;
  2989. uid_t uid = getuid();
  2990. if( (pwent=getpwuid(uid)) != NULL) {
  2991. home_dir = pwent->pw_dir;
  2992. }
  2993. #endif
  2994. #if defined(_WIN32_WCE)
  2995. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  2996. */
  2997. home_dir = strdup("/");
  2998. #else
  2999. #if defined(_WIN32) || defined(WIN32) || defined(__OS2__)
  3000. if (!home_dir) {
  3001. home_dir = getenv("USERPROFILE");
  3002. }
  3003. #endif
  3004. if (!home_dir) {
  3005. home_dir = getenv("HOME");
  3006. }
  3007. #if defined(_WIN32) || defined(WIN32) || defined(__OS2__)
  3008. if (!home_dir) {
  3009. char *zDrive, *zPath;
  3010. int n;
  3011. zDrive = getenv("HOMEDRIVE");
  3012. zPath = getenv("HOMEPATH");
  3013. if( zDrive && zPath ){
  3014. n = strlen30(zDrive) + strlen30(zPath) + 1;
  3015. home_dir = malloc( n );
  3016. if( home_dir==0 ) return 0;
  3017. sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  3018. return home_dir;
  3019. }
  3020. home_dir = "c:\\";
  3021. }
  3022. #endif
  3023. #endif /* !_WIN32_WCE */
  3024. if( home_dir ){
  3025. int n = strlen30(home_dir) + 1;
  3026. char *z = malloc( n );
  3027. if( z ) memcpy(z, home_dir, n);
  3028. home_dir = z;
  3029. }
  3030. return home_dir;
  3031. }
  3032. /*
  3033. ** Read input from the file given by sqliterc_override. Or if that
  3034. ** parameter is NULL, take input from ~/.sqliterc
  3035. **
  3036. ** Returns the number of errors.
  3037. */
  3038. static int process_sqliterc(
  3039. struct callback_data *p, /* Configuration data */
  3040. const char *sqliterc_override /* Name of config file. NULL to use default */
  3041. ){
  3042. char *home_dir = NULL;
  3043. const char *sqliterc = sqliterc_override;
  3044. char *zBuf = 0;
  3045. FILE *in = NULL;
  3046. int nBuf;
  3047. int rc = 0;
  3048. if (sqliterc == NULL) {
  3049. home_dir = find_home_dir();
  3050. if( home_dir==0 ){
  3051. #if !defined(__RTP__) && !defined(_WRS_KERNEL)
  3052. fprintf(stderr,"%s: Error: cannot locate your home directory\n", Argv0);
  3053. #endif
  3054. return 1;
  3055. }
  3056. nBuf = strlen30(home_dir) + 16;
  3057. zBuf = malloc( nBuf );
  3058. if( zBuf==0 ){
  3059. fprintf(stderr,"%s: Error: out of memory\n",Argv0);
  3060. return 1;
  3061. }
  3062. sqlite3_snprintf(nBuf, zBuf,"%s/.sqliterc",home_dir);
  3063. free(home_dir);
  3064. sqliterc = (const char*)zBuf;
  3065. }
  3066. in = fopen(sqliterc,"rb");
  3067. if( in ){
  3068. if( stdin_is_interactive ){
  3069. fprintf(stderr,"-- Loading resources from %s\n",sqliterc);
  3070. }
  3071. rc = process_input(p,in);
  3072. fclose(in);
  3073. }
  3074. free(zBuf);
  3075. return rc;
  3076. }
  3077. /*
  3078. ** Show available command line options
  3079. */
  3080. static const char zOptions[] =
  3081. " -help show this message\n"
  3082. " -init filename read/process named file\n"
  3083. " -echo print commands before execution\n"
  3084. " -[no]header turn headers on or off\n"
  3085. " -bail stop after hitting an error\n"
  3086. " -interactive force interactive I/O\n"
  3087. " -batch force batch I/O\n"
  3088. " -column set output mode to 'column'\n"
  3089. " -csv set output mode to 'csv'\n"
  3090. " -html set output mode to HTML\n"
  3091. " -line set output mode to 'line'\n"
  3092. " -list set output mode to 'list'\n"
  3093. " -separator 'x' set output field separator (|)\n"
  3094. " -nullvalue 'text' set text string for NULL values\n"
  3095. " -version show SQLite version\n"
  3096. ;
  3097. static void usage(int showDetail){
  3098. fprintf(stderr,
  3099. "Usage: %s [OPTIONS] FILENAME [SQL]\n"
  3100. "FILENAME is the name of an SQLite database. A new database is created\n"
  3101. "if the file does not previously exist.\n", Argv0);
  3102. if( showDetail ){
  3103. fprintf(stderr, "OPTIONS include:\n%s", zOptions);
  3104. }else{
  3105. fprintf(stderr, "Use the -help option for additional information\n");
  3106. }
  3107. exit(1);
  3108. }
  3109. /*
  3110. ** Initialize the state information in data
  3111. */
  3112. static void main_init(struct callback_data *data) {
  3113. memset(data, 0, sizeof(*data));
  3114. data->mode = MODE_List;
  3115. memcpy(data->separator,"|", 2);
  3116. data->showHeader = 0;
  3117. sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
  3118. sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  3119. sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
  3120. }
  3121. int main(int argc, char **argv){
  3122. char *zErrMsg = 0;
  3123. struct callback_data data;
  3124. const char *zInitFile = 0;
  3125. char *zFirstCmd = 0;
  3126. int i;
  3127. int rc = 0;
  3128. Argv0 = argv[0];
  3129. main_init(&data);
  3130. stdin_is_interactive = isatty(0);
  3131. /* Make sure we have a valid signal handler early, before anything
  3132. ** else is done.
  3133. */
  3134. #ifdef SIGINT
  3135. signal(SIGINT, interrupt_handler);
  3136. #endif
  3137. /* Do an initial pass through the command-line argument to locate
  3138. ** the name of the database file, the name of the initialization file,
  3139. ** and the first command to execute.
  3140. */
  3141. for(i=1; i<argc-1; i++){
  3142. char *z;
  3143. if( argv[i][0]!='-' ) break;
  3144. z = argv[i];
  3145. if( z[0]=='-' && z[1]=='-' ) z++;
  3146. if( strcmp(argv[i],"-separator")==0 || strcmp(argv[i],"-nullvalue")==0 ){
  3147. i++;
  3148. }else if( strcmp(argv[i],"-init")==0 ){
  3149. i++;
  3150. zInitFile = argv[i];
  3151. /* Need to check for batch mode here to so we can avoid printing
  3152. ** informational messages (like from process_sqliterc) before
  3153. ** we do the actual processing of arguments later in a second pass.
  3154. */
  3155. }else if( strcmp(argv[i],"-batch")==0 ){
  3156. stdin_is_interactive = 0;
  3157. }
  3158. }
  3159. if( i<argc ){
  3160. #if defined(SQLITE_OS_OS2) && SQLITE_OS_OS2
  3161. data.zDbFilename = (const char *)convertCpPathToUtf8( argv[i++] );
  3162. #else
  3163. data.zDbFilename = argv[i++];
  3164. #endif
  3165. }else{
  3166. #ifndef SQLITE_OMIT_MEMORYDB
  3167. data.zDbFilename = ":memory:";
  3168. #else
  3169. data.zDbFilename = 0;
  3170. #endif
  3171. }
  3172. if( i<argc ){
  3173. zFirstCmd = argv[i++];
  3174. }
  3175. if( i<argc ){
  3176. fprintf(stderr,"%s: Error: too many options: \"%s\"\n", Argv0, argv[i]);
  3177. fprintf(stderr,"Use -help for a list of options.\n");
  3178. return 1;
  3179. }
  3180. data.out = stdout;
  3181. #ifdef SQLITE_OMIT_MEMORYDB
  3182. if( data.zDbFilename==0 ){
  3183. fprintf(stderr,"%s: Error: no database filename specified\n", Argv0);
  3184. return 1;
  3185. }
  3186. #endif
  3187. /* Go ahead and open the database file if it already exists. If the
  3188. ** file does not exist, delay opening it. This prevents empty database
  3189. ** files from being created if a user mistypes the database name argument
  3190. ** to the sqlite command-line tool.
  3191. */
  3192. if( access(data.zDbFilename, 0)==0 ){
  3193. open_db(&data);
  3194. }
  3195. /* Process the initialization file if there is one. If no -init option
  3196. ** is given on the command line, look for a file named ~/.sqliterc and
  3197. ** try to process it.
  3198. */
  3199. rc = process_sqliterc(&data,zInitFile);
  3200. if( rc>0 ){
  3201. return rc;
  3202. }
  3203. /* Make a second pass through the command-line argument and set
  3204. ** options. This second pass is delayed until after the initialization
  3205. ** file is processed so that the command-line arguments will override
  3206. ** settings in the initialization file.
  3207. */
  3208. for(i=1; i<argc && argv[i][0]=='-'; i++){
  3209. char *z = argv[i];
  3210. if( z[1]=='-' ){ z++; }
  3211. if( strcmp(z,"-init")==0 ){
  3212. i++;
  3213. }else if( strcmp(z,"-html")==0 ){
  3214. data.mode = MODE_Html;
  3215. }else if( strcmp(z,"-list")==0 ){
  3216. data.mode = MODE_List;
  3217. }else if( strcmp(z,"-line")==0 ){
  3218. data.mode = MODE_Line;
  3219. }else if( strcmp(z,"-column")==0 ){
  3220. data.mode = MODE_Column;
  3221. }else if( strcmp(z,"-csv")==0 ){
  3222. data.mode = MODE_Csv;
  3223. memcpy(data.separator,",",2);
  3224. }else if( strcmp(z,"-separator")==0 ){
  3225. i++;
  3226. if(i>=argc){
  3227. fprintf(stderr,"%s: Error: missing argument for option: %s\n", Argv0, z);
  3228. fprintf(stderr,"Use -help for a list of options.\n");
  3229. return 1;
  3230. }
  3231. sqlite3_snprintf(sizeof(data.separator), data.separator,
  3232. "%.*s",(int)sizeof(data.separator)-1,argv[i]);
  3233. }else if( strcmp(z,"-nullvalue")==0 ){
  3234. i++;
  3235. if(i>=argc){
  3236. fprintf(stderr,"%s: Error: missing argument for option: %s\n", Argv0, z);
  3237. fprintf(stderr,"Use -help for a list of options.\n");
  3238. return 1;
  3239. }
  3240. sqlite3_snprintf(sizeof(data.nullvalue), data.nullvalue,
  3241. "%.*s",(int)sizeof(data.nullvalue)-1,argv[i]);
  3242. }else if( strcmp(z,"-header")==0 ){
  3243. data.showHeader = 1;
  3244. }else if( strcmp(z,"-noheader")==0 ){
  3245. data.showHeader = 0;
  3246. }else if( strcmp(z,"-echo")==0 ){
  3247. data.echoOn = 1;
  3248. }else if( strcmp(z,"-bail")==0 ){
  3249. bail_on_error = 1;
  3250. }else if( strcmp(z,"-version")==0 ){
  3251. printf("%s\n", sqlite3_libversion());
  3252. return 0;
  3253. }else if( strcmp(z,"-interactive")==0 ){
  3254. stdin_is_interactive = 1;
  3255. }else if( strcmp(z,"-batch")==0 ){
  3256. stdin_is_interactive = 0;
  3257. }else if( strcmp(z,"-help")==0 || strcmp(z, "--help")==0 ){
  3258. usage(1);
  3259. }else{
  3260. fprintf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
  3261. fprintf(stderr,"Use -help for a list of options.\n");
  3262. return 1;
  3263. }
  3264. }
  3265. if( zFirstCmd ){
  3266. /* Run just the command that follows the database name
  3267. */
  3268. if( zFirstCmd[0]=='.' ){
  3269. rc = do_meta_command(zFirstCmd, &data);
  3270. return rc;
  3271. }else{
  3272. open_db(&data);
  3273. rc = shell_exec(data.db, zFirstCmd, shell_callback, &data, &zErrMsg);
  3274. if( zErrMsg!=0 ){
  3275. fprintf(stderr,"Error: %s\n", zErrMsg);
  3276. return rc!=0 ? rc : 1;
  3277. }else if( rc!=0 ){
  3278. fprintf(stderr,"Error: unable to process SQL \"%s\"\n", zFirstCmd);
  3279. return rc;
  3280. }
  3281. }
  3282. }else{
  3283. /* Run commands received from standard input
  3284. */
  3285. if( stdin_is_interactive ){
  3286. char *zHome;
  3287. char *zHistory = 0;
  3288. int nHistory;
  3289. printf(
  3290. "SQLite version %s\n"
  3291. "Enter \".help\" for instructions\n"
  3292. "Enter SQL statements terminated with a \";\"\n",
  3293. sqlite3_libversion()
  3294. );
  3295. zHome = find_home_dir();
  3296. if( zHome ){
  3297. nHistory = strlen30(zHome) + 20;
  3298. if( (zHistory = malloc(nHistory))!=0 ){
  3299. sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  3300. }
  3301. }
  3302. #if defined(HAVE_READLINE) && HAVE_READLINE==1
  3303. if( zHistory ) read_history(zHistory);
  3304. #endif
  3305. rc = process_input(&data, 0);
  3306. if( zHistory ){
  3307. stifle_history(100);
  3308. write_history(zHistory);
  3309. free(zHistory);
  3310. }
  3311. free(zHome);
  3312. }else{
  3313. rc = process_input(&data, stdin);
  3314. }
  3315. }
  3316. set_table_name(&data, 0);
  3317. if( db ){
  3318. if( sqlite3_close(db)!=SQLITE_OK ){
  3319. fprintf(stderr,"Error: cannot close database \"%s\"\n", sqlite3_errmsg(db));
  3320. rc++;
  3321. }
  3322. }
  3323. return rc;
  3324. }