/python-build/sqlite3/shell.c
C | 3569 lines | 2889 code | 227 blank | 453 comment | 587 complexity | 58856190d8e975d76e3605bc1504c6f9 MD5 | raw file
Possible License(s): GPL-3.0, 0BSD, GPL-2.0, Apache-2.0, LGPL-3.0, AGPL-1.0, BSD-3-Clause
Large files files are truncated, but you can click here to view the full file
- /*
- ** 2001 September 15
- **
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
- **
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
- **
- *************************************************************************
- ** This file contains code to implement the "sqlite" command line
- ** utility for accessing SQLite databases.
- */
- #if defined(_WIN32) || defined(WIN32)
- /* This needs to come before any includes for MSVC compiler */
- #define _CRT_SECURE_NO_WARNINGS
- #endif
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- #include <assert.h>
- #include "sqlite3.h"
- #include <ctype.h>
- #include <stdarg.h>
- #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__)
- # include <signal.h>
- # if !defined(__RTP__) && !defined(_WRS_KERNEL)
- # include <pwd.h>
- # endif
- # include <unistd.h>
- # include <sys/types.h>
- #endif
- #ifdef __OS2__
- # include <unistd.h>
- #endif
- #if defined(HAVE_READLINE) && HAVE_READLINE==1
- # include <readline/readline.h>
- # include <readline/history.h>
- #else
- # define readline(p) local_getline(p,stdin)
- # define add_history(X)
- # define read_history(X)
- # define write_history(X)
- # define stifle_history(X)
- #endif
- #if defined(_WIN32) || defined(WIN32)
- # include <io.h>
- #define isatty(h) _isatty(h)
- #define access(f,m) _access((f),(m))
- #else
- /* Make sure isatty() has a prototype.
- */
- extern int isatty();
- #endif
- #if defined(_WIN32_WCE)
- /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
- * thus we always assume that we have a console. That can be
- * overridden with the -batch command line option.
- */
- #define isatty(x) 1
- #endif
- #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(__RTP__) && !defined(_WRS_KERNEL)
- #include <sys/time.h>
- #include <sys/resource.h>
- /* Saved resource information for the beginning of an operation */
- static struct rusage sBegin;
- /* True if the timer is enabled */
- static int enableTimer = 0;
- /*
- ** Begin timing an operation
- */
- static void beginTimer(void){
- if( enableTimer ){
- getrusage(RUSAGE_SELF, &sBegin);
- }
- }
- /* Return the difference of two time_structs in seconds */
- static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
- return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
- (double)(pEnd->tv_sec - pStart->tv_sec);
- }
- /*
- ** Print the timing results.
- */
- static void endTimer(void){
- if( enableTimer ){
- struct rusage sEnd;
- getrusage(RUSAGE_SELF, &sEnd);
- printf("CPU Time: user %f sys %f\n",
- timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
- timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
- }
- }
- #define BEGIN_TIMER beginTimer()
- #define END_TIMER endTimer()
- #define HAS_TIMER 1
- #elif (defined(_WIN32) || defined(WIN32))
- #include <windows.h>
- /* Saved resource information for the beginning of an operation */
- static HANDLE hProcess;
- static FILETIME ftKernelBegin;
- static FILETIME ftUserBegin;
- typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME);
- static GETPROCTIMES getProcessTimesAddr = NULL;
- /* True if the timer is enabled */
- static int enableTimer = 0;
- /*
- ** Check to see if we have timer support. Return 1 if necessary
- ** support found (or found previously).
- */
- static int hasTimer(void){
- if( getProcessTimesAddr ){
- return 1;
- } else {
- /* GetProcessTimes() isn't supported in WIN95 and some other Windows versions.
- ** See if the version we are running on has it, and if it does, save off
- ** a pointer to it and the current process handle.
- */
- hProcess = GetCurrentProcess();
- if( hProcess ){
- HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
- if( NULL != hinstLib ){
- getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
- if( NULL != getProcessTimesAddr ){
- return 1;
- }
- FreeLibrary(hinstLib);
- }
- }
- }
- return 0;
- }
- /*
- ** Begin timing an operation
- */
- static void beginTimer(void){
- if( enableTimer && getProcessTimesAddr ){
- FILETIME ftCreation, ftExit;
- getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin);
- }
- }
- /* Return the difference of two FILETIME structs in seconds */
- static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
- sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
- sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
- return (double) ((i64End - i64Start) / 10000000.0);
- }
- /*
- ** Print the timing results.
- */
- static void endTimer(void){
- if( enableTimer && getProcessTimesAddr){
- FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
- getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd);
- printf("CPU Time: user %f sys %f\n",
- timeDiff(&ftUserBegin, &ftUserEnd),
- timeDiff(&ftKernelBegin, &ftKernelEnd));
- }
- }
- #define BEGIN_TIMER beginTimer()
- #define END_TIMER endTimer()
- #define HAS_TIMER hasTimer()
- #else
- #define BEGIN_TIMER
- #define END_TIMER
- #define HAS_TIMER 0
- #endif
- /*
- ** Used to prevent warnings about unused parameters
- */
- #define UNUSED_PARAMETER(x) (void)(x)
- /**************************************************************************
- ***************************************************************************
- ** Begin genfkey logic.
- */
- #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined SQLITE_OMIT_SUBQUERY
- #define GENFKEY_ERROR 1
- #define GENFKEY_DROPTRIGGER 2
- #define GENFKEY_CREATETRIGGER 3
- static int genfkey_create_triggers(sqlite3 *, const char *, void *,
- int (*)(void *, int, const char *)
- );
- struct GenfkeyCb {
- void *pCtx;
- int eType;
- int (*xData)(void *, int, const char *);
- };
- typedef struct GenfkeyCb GenfkeyCb;
- /* The code in this file defines a sqlite3 virtual-table module that
- ** provides a read-only view of the current database schema. There is one
- ** row in the schema table for each column in the database schema.
- */
- #define SCHEMA \
- "CREATE TABLE x(" \
- "database," /* Name of database (i.e. main, temp etc.) */ \
- "tablename," /* Name of table */ \
- "cid," /* Column number (from left-to-right, 0 upward) */ \
- "name," /* Column name */ \
- "type," /* Specified type (i.e. VARCHAR(32)) */ \
- "not_null," /* Boolean. True if NOT NULL was specified */ \
- "dflt_value," /* Default value for this column */ \
- "pk" /* True if this column is part of the primary key */ \
- ")"
- #define SCHEMA2 \
- "CREATE TABLE x(" \
- "database," /* Name of database (i.e. main, temp etc.) */ \
- "from_tbl," /* Name of table */ \
- "fkid," \
- "seq," \
- "to_tbl," \
- "from_col," \
- "to_col," \
- "on_update," \
- "on_delete," \
- "match" \
- ")"
- #define SCHEMA3 \
- "CREATE TABLE x(" \
- "database," /* Name of database (i.e. main, temp etc.) */ \
- "tablename," /* Name of table */ \
- "seq," \
- "name," \
- "isunique" \
- ")"
- #define SCHEMA4 \
- "CREATE TABLE x(" \
- "database," /* Name of database (i.e. main, temp etc.) */ \
- "indexname," /* Name of table */ \
- "seqno," \
- "cid," \
- "name" \
- ")"
- #define SCHEMA5 \
- "CREATE TABLE x(" \
- "database," /* Name of database (i.e. main, temp etc.) */ \
- "triggername," /* Name of trigger */ \
- "dummy" /* Unused */ \
- ")"
- typedef struct SchemaTable SchemaTable;
- static struct SchemaTable {
- const char *zName;
- const char *zObject;
- const char *zPragma;
- const char *zSchema;
- } aSchemaTable[] = {
- { "table_info", "table", "PRAGMA %Q.table_info(%Q)", SCHEMA },
- { "foreign_key_list", "table", "PRAGMA %Q.foreign_key_list(%Q)", SCHEMA2 },
- { "index_list", "table", "PRAGMA %Q.index_list(%Q)", SCHEMA3 },
- { "index_info", "index", "PRAGMA %Q.index_info(%Q)", SCHEMA4 },
- { "trigger_list", "trigger", "SELECT 1", SCHEMA5 },
- { 0, 0, 0, 0 }
- };
- typedef struct schema_vtab schema_vtab;
- typedef struct schema_cursor schema_cursor;
- /* A schema table object */
- struct schema_vtab {
- sqlite3_vtab base;
- sqlite3 *db;
- SchemaTable *pType;
- };
- /* A schema table cursor object */
- struct schema_cursor {
- sqlite3_vtab_cursor base;
- sqlite3_stmt *pDbList;
- sqlite3_stmt *pTableList;
- sqlite3_stmt *pColumnList;
- int rowid;
- };
- /*
- ** Table destructor for the schema module.
- */
- static int schemaDestroy(sqlite3_vtab *pVtab){
- sqlite3_free(pVtab);
- return 0;
- }
- /*
- ** Table constructor for the schema module.
- */
- static int schemaCreate(
- sqlite3 *db,
- void *pAux,
- int argc, const char *const*argv,
- sqlite3_vtab **ppVtab,
- char **pzErr
- ){
- int rc = SQLITE_NOMEM;
- schema_vtab *pVtab;
- SchemaTable *pType = &aSchemaTable[0];
- UNUSED_PARAMETER(pzErr);
- if( argc>3 ){
- int i;
- pType = 0;
- for(i=0; aSchemaTable[i].zName; i++){
- if( 0==strcmp(argv[3], aSchemaTable[i].zName) ){
- pType = &aSchemaTable[i];
- }
- }
- if( !pType ){
- return SQLITE_ERROR;
- }
- }
- pVtab = sqlite3_malloc(sizeof(schema_vtab));
- if( pVtab ){
- memset(pVtab, 0, sizeof(schema_vtab));
- pVtab->db = (sqlite3 *)pAux;
- pVtab->pType = pType;
- rc = sqlite3_declare_vtab(db, pType->zSchema);
- }
- *ppVtab = (sqlite3_vtab *)pVtab;
- return rc;
- }
- /*
- ** Open a new cursor on the schema table.
- */
- static int schemaOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
- int rc = SQLITE_NOMEM;
- schema_cursor *pCur;
- UNUSED_PARAMETER(pVTab);
- pCur = sqlite3_malloc(sizeof(schema_cursor));
- if( pCur ){
- memset(pCur, 0, sizeof(schema_cursor));
- *ppCursor = (sqlite3_vtab_cursor *)pCur;
- rc = SQLITE_OK;
- }
- return rc;
- }
- /*
- ** Close a schema table cursor.
- */
- static int schemaClose(sqlite3_vtab_cursor *cur){
- schema_cursor *pCur = (schema_cursor *)cur;
- sqlite3_finalize(pCur->pDbList);
- sqlite3_finalize(pCur->pTableList);
- sqlite3_finalize(pCur->pColumnList);
- sqlite3_free(pCur);
- return SQLITE_OK;
- }
- static void columnToResult(sqlite3_context *ctx, sqlite3_stmt *pStmt, int iCol){
- switch( sqlite3_column_type(pStmt, iCol) ){
- case SQLITE_NULL:
- sqlite3_result_null(ctx);
- break;
- case SQLITE_INTEGER:
- sqlite3_result_int64(ctx, sqlite3_column_int64(pStmt, iCol));
- break;
- case SQLITE_FLOAT:
- sqlite3_result_double(ctx, sqlite3_column_double(pStmt, iCol));
- break;
- case SQLITE_TEXT: {
- const char *z = (const char *)sqlite3_column_text(pStmt, iCol);
- sqlite3_result_text(ctx, z, -1, SQLITE_TRANSIENT);
- break;
- }
- }
- }
- /*
- ** Retrieve a column of data.
- */
- static int schemaColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
- schema_cursor *pCur = (schema_cursor *)cur;
- switch( i ){
- case 0:
- columnToResult(ctx, pCur->pDbList, 1);
- break;
- case 1:
- columnToResult(ctx, pCur->pTableList, 0);
- break;
- default:
- columnToResult(ctx, pCur->pColumnList, i-2);
- break;
- }
- return SQLITE_OK;
- }
- /*
- ** Retrieve the current rowid.
- */
- static int schemaRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
- schema_cursor *pCur = (schema_cursor *)cur;
- *pRowid = pCur->rowid;
- return SQLITE_OK;
- }
- static int finalize(sqlite3_stmt **ppStmt){
- int rc = sqlite3_finalize(*ppStmt);
- *ppStmt = 0;
- return rc;
- }
- static int schemaEof(sqlite3_vtab_cursor *cur){
- schema_cursor *pCur = (schema_cursor *)cur;
- return (pCur->pDbList ? 0 : 1);
- }
- /*
- ** Advance the cursor to the next row.
- */
- static int schemaNext(sqlite3_vtab_cursor *cur){
- int rc = SQLITE_OK;
- schema_cursor *pCur = (schema_cursor *)cur;
- schema_vtab *pVtab = (schema_vtab *)(cur->pVtab);
- char *zSql = 0;
- while( !pCur->pColumnList || SQLITE_ROW!=sqlite3_step(pCur->pColumnList) ){
- if( SQLITE_OK!=(rc = finalize(&pCur->pColumnList)) ) goto next_exit;
- while( !pCur->pTableList || SQLITE_ROW!=sqlite3_step(pCur->pTableList) ){
- if( SQLITE_OK!=(rc = finalize(&pCur->pTableList)) ) goto next_exit;
- assert(pCur->pDbList);
- while( SQLITE_ROW!=sqlite3_step(pCur->pDbList) ){
- rc = finalize(&pCur->pDbList);
- goto next_exit;
- }
- /* Set zSql to the SQL to pull the list of tables from the
- ** sqlite_master (or sqlite_temp_master) table of the database
- ** identfied by the row pointed to by the SQL statement pCur->pDbList
- ** (iterating through a "PRAGMA database_list;" statement).
- */
- if( sqlite3_column_int(pCur->pDbList, 0)==1 ){
- zSql = sqlite3_mprintf(
- "SELECT name FROM sqlite_temp_master WHERE type=%Q",
- pVtab->pType->zObject
- );
- }else{
- sqlite3_stmt *pDbList = pCur->pDbList;
- zSql = sqlite3_mprintf(
- "SELECT name FROM %Q.sqlite_master WHERE type=%Q",
- sqlite3_column_text(pDbList, 1), pVtab->pType->zObject
- );
- }
- if( !zSql ){
- rc = SQLITE_NOMEM;
- goto next_exit;
- }
- rc = sqlite3_prepare(pVtab->db, zSql, -1, &pCur->pTableList, 0);
- sqlite3_free(zSql);
- if( rc!=SQLITE_OK ) goto next_exit;
- }
- /* Set zSql to the SQL to the table_info pragma for the table currently
- ** identified by the rows pointed to by statements pCur->pDbList and
- ** pCur->pTableList.
- */
- zSql = sqlite3_mprintf(pVtab->pType->zPragma,
- sqlite3_column_text(pCur->pDbList, 1),
- sqlite3_column_text(pCur->pTableList, 0)
- );
- if( !zSql ){
- rc = SQLITE_NOMEM;
- goto next_exit;
- }
- rc = sqlite3_prepare(pVtab->db, zSql, -1, &pCur->pColumnList, 0);
- sqlite3_free(zSql);
- if( rc!=SQLITE_OK ) goto next_exit;
- }
- pCur->rowid++;
- next_exit:
- /* TODO: Handle rc */
- return rc;
- }
- /*
- ** Reset a schema table cursor.
- */
- static int schemaFilter(
- sqlite3_vtab_cursor *pVtabCursor,
- int idxNum, const char *idxStr,
- int argc, sqlite3_value **argv
- ){
- int rc;
- schema_vtab *pVtab = (schema_vtab *)(pVtabCursor->pVtab);
- schema_cursor *pCur = (schema_cursor *)pVtabCursor;
- UNUSED_PARAMETER(idxNum);
- UNUSED_PARAMETER(idxStr);
- UNUSED_PARAMETER(argc);
- UNUSED_PARAMETER(argv);
- pCur->rowid = 0;
- finalize(&pCur->pTableList);
- finalize(&pCur->pColumnList);
- finalize(&pCur->pDbList);
- rc = sqlite3_prepare(pVtab->db,"SELECT 0, 'main'", -1, &pCur->pDbList, 0);
- return (rc==SQLITE_OK ? schemaNext(pVtabCursor) : rc);
- }
- /*
- ** Analyse the WHERE condition.
- */
- static int schemaBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
- UNUSED_PARAMETER(tab);
- UNUSED_PARAMETER(pIdxInfo);
- return SQLITE_OK;
- }
- /*
- ** A virtual table module that merely echos method calls into TCL
- ** variables.
- */
- static sqlite3_module schemaModule = {
- 0, /* iVersion */
- schemaCreate,
- schemaCreate,
- schemaBestIndex,
- schemaDestroy,
- schemaDestroy,
- schemaOpen, /* xOpen - open a cursor */
- schemaClose, /* xClose - close a cursor */
- schemaFilter, /* xFilter - configure scan constraints */
- schemaNext, /* xNext - advance a cursor */
- schemaEof, /* xEof */
- schemaColumn, /* xColumn - read data */
- schemaRowid, /* xRowid - read data */
- 0, /* xUpdate */
- 0, /* xBegin */
- 0, /* xSync */
- 0, /* xCommit */
- 0, /* xRollback */
- 0, /* xFindMethod */
- 0, /* xRename */
- };
- /*
- ** Extension load function.
- */
- static int installSchemaModule(sqlite3 *db, sqlite3 *sdb){
- sqlite3_create_module(db, "schema", &schemaModule, (void *)sdb);
- return 0;
- }
- /*
- ** sj(zValue, zJoin)
- **
- ** The following block contains the implementation of an aggregate
- ** function that returns a string. Each time the function is stepped,
- ** it appends data to an internal buffer. When the aggregate is finalized,
- ** the contents of the buffer are returned.
- **
- ** The first time the aggregate is stepped the buffer is set to a copy
- ** of the first argument. The second time and subsequent times it is
- ** stepped a copy of the second argument is appended to the buffer, then
- ** a copy of the first.
- **
- ** Example:
- **
- ** INSERT INTO t1(a) VALUES('1');
- ** INSERT INTO t1(a) VALUES('2');
- ** INSERT INTO t1(a) VALUES('3');
- ** SELECT sj(a, ', ') FROM t1;
- **
- ** => "1, 2, 3"
- **
- */
- struct StrBuffer {
- char *zBuf;
- };
- typedef struct StrBuffer StrBuffer;
- static void joinFinalize(sqlite3_context *context){
- StrBuffer *p;
- p = (StrBuffer *)sqlite3_aggregate_context(context, sizeof(StrBuffer));
- sqlite3_result_text(context, p->zBuf, -1, SQLITE_TRANSIENT);
- sqlite3_free(p->zBuf);
- }
- static void joinStep(
- sqlite3_context *context,
- int argc,
- sqlite3_value **argv
- ){
- StrBuffer *p;
- UNUSED_PARAMETER(argc);
- p = (StrBuffer *)sqlite3_aggregate_context(context, sizeof(StrBuffer));
- if( p->zBuf==0 ){
- p->zBuf = sqlite3_mprintf("%s", sqlite3_value_text(argv[0]));
- }else{
- char *zTmp = p->zBuf;
- p->zBuf = sqlite3_mprintf("%s%s%s",
- zTmp, sqlite3_value_text(argv[1]), sqlite3_value_text(argv[0])
- );
- sqlite3_free(zTmp);
- }
- }
- /*
- ** dq(zString)
- **
- ** This scalar function accepts a single argument and interprets it as
- ** a text value. The return value is the argument enclosed in double
- ** quotes. If any double quote characters are present in the argument,
- ** these are escaped.
- **
- ** dq('the raven "Nevermore."') == '"the raven ""Nevermore."""'
- */
- static void doublequote(
- sqlite3_context *context,
- int argc,
- sqlite3_value **argv
- ){
- int ii;
- char *zOut;
- char *zCsr;
- const char *zIn = (const char *)sqlite3_value_text(argv[0]);
- int nIn = sqlite3_value_bytes(argv[0]);
- UNUSED_PARAMETER(argc);
- zOut = sqlite3_malloc(nIn*2+3);
- zCsr = zOut;
- *zCsr++ = '"';
- for(ii=0; ii<nIn; ii++){
- *zCsr++ = zIn[ii];
- if( zIn[ii]=='"' ){
- *zCsr++ = '"';
- }
- }
- *zCsr++ = '"';
- *zCsr++ = '\0';
- sqlite3_result_text(context, zOut, -1, SQLITE_TRANSIENT);
- sqlite3_free(zOut);
- }
- /*
- ** multireplace(zString, zSearch1, zReplace1, ...)
- */
- static void multireplace(
- sqlite3_context *context,
- int argc,
- sqlite3_value **argv
- ){
- int i = 0;
- char *zOut = 0;
- int nOut = 0;
- int nMalloc = 0;
- const char *zIn = (const char *)sqlite3_value_text(argv[0]);
- int nIn = sqlite3_value_bytes(argv[0]);
- while( i<nIn ){
- const char *zCopy = &zIn[i];
- int nCopy = 1;
- int nReplace = 1;
- int j;
- for(j=1; j<(argc-1); j+=2){
- const char *z = (const char *)sqlite3_value_text(argv[j]);
- int n = sqlite3_value_bytes(argv[j]);
- if( n<=(nIn-i) && 0==strncmp(z, zCopy, n) ){
- zCopy = (const char *)sqlite3_value_text(argv[j+1]);
- nCopy = sqlite3_value_bytes(argv[j+1]);
- nReplace = n;
- break;
- }
- }
- if( (nOut+nCopy)>nMalloc ){
- char *zNew;
- nMalloc = 16 + (nOut+nCopy)*2;
- zNew = (char*)sqlite3_realloc(zOut, nMalloc);
- if( zNew==0 ){
- sqlite3_result_error_nomem(context);
- return;
- }else{
- zOut = zNew;
- }
- }
- assert( nMalloc>=(nOut+nCopy) );
- memcpy(&zOut[nOut], zCopy, nCopy);
- i += nReplace;
- nOut += nCopy;
- }
- sqlite3_result_text(context, zOut, nOut, SQLITE_TRANSIENT);
- sqlite3_free(zOut);
- }
- /*
- ** A callback for sqlite3_exec() invokes the callback specified by the
- ** GenfkeyCb structure pointed to by the void* passed as the first argument.
- */
- static int invokeCallback(void *p, int nArg, char **azArg, char **azCol){
- GenfkeyCb *pCb = (GenfkeyCb *)p;
- UNUSED_PARAMETER(nArg);
- UNUSED_PARAMETER(azCol);
- return pCb->xData(pCb->pCtx, pCb->eType, azArg[0]);
- }
- static int detectSchemaProblem(
- sqlite3 *db, /* Database connection */
- const char *zMessage, /* English language error message */
- const char *zSql, /* SQL statement to run */
- GenfkeyCb *pCb
- ){
- sqlite3_stmt *pStmt;
- int rc;
- rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
- if( rc!=SQLITE_OK ){
- return rc;
- }
- while( SQLITE_ROW==sqlite3_step(pStmt) ){
- char *zDel;
- int iFk = sqlite3_column_int(pStmt, 0);
- const char *zTab = (const char *)sqlite3_column_text(pStmt, 1);
- zDel = sqlite3_mprintf("Error in table %s: %s", zTab, zMessage);
- rc = pCb->xData(pCb->pCtx, pCb->eType, zDel);
- sqlite3_free(zDel);
- if( rc!=SQLITE_OK ) return rc;
- zDel = sqlite3_mprintf(
- "DELETE FROM temp.fkey WHERE from_tbl = %Q AND fkid = %d"
- , zTab, iFk
- );
- sqlite3_exec(db, zDel, 0, 0, 0);
- sqlite3_free(zDel);
- }
- sqlite3_finalize(pStmt);
- return SQLITE_OK;
- }
- /*
- ** Create and populate temporary table "fkey".
- */
- static int populateTempTable(sqlite3 *db, GenfkeyCb *pCallback){
- int rc;
-
- rc = sqlite3_exec(db,
- "CREATE VIRTUAL TABLE temp.v_fkey USING schema(foreign_key_list);"
- "CREATE VIRTUAL TABLE temp.v_col USING schema(table_info);"
- "CREATE VIRTUAL TABLE temp.v_idxlist USING schema(index_list);"
- "CREATE VIRTUAL TABLE temp.v_idxinfo USING schema(index_info);"
- "CREATE VIRTUAL TABLE temp.v_triggers USING schema(trigger_list);"
- "CREATE TABLE temp.fkey AS "
- "SELECT from_tbl, to_tbl, fkid, from_col, to_col, on_update, on_delete "
- "FROM temp.v_fkey WHERE database = 'main';"
- , 0, 0, 0
- );
- if( rc!=SQLITE_OK ) return rc;
- rc = detectSchemaProblem(db, "foreign key columns do not exist",
- "SELECT fkid, from_tbl "
- "FROM temp.fkey "
- "WHERE to_col IS NOT NULL AND NOT EXISTS (SELECT 1 "
- "FROM temp.v_col WHERE tablename=to_tbl AND name==to_col"
- ")", pCallback
- );
- if( rc!=SQLITE_OK ) return rc;
- /* At this point the temp.fkey table is mostly populated. If any foreign
- ** keys were specified so that they implicitly refer to they primary
- ** key of the parent table, the "to_col" values of the temp.fkey rows
- ** are still set to NULL.
- **
- ** This is easily fixed for single column primary keys, but not for
- ** composites. With a composite primary key, there is no way to reliably
- ** query sqlite for the order in which the columns that make up the
- ** composite key were declared i.e. there is no way to tell if the
- ** schema actually contains "PRIMARY KEY(a, b)" or "PRIMARY KEY(b, a)".
- ** Therefore, this case is not handled. The following function call
- ** detects instances of this case.
- */
- rc = detectSchemaProblem(db, "implicit mapping to composite primary key",
- "SELECT fkid, from_tbl "
- "FROM temp.fkey "
- "WHERE to_col IS NULL "
- "GROUP BY fkid, from_tbl HAVING count(*) > 1", pCallback
- );
- if( rc!=SQLITE_OK ) return rc;
- /* Detect attempts to implicitly map to the primary key of a table
- ** that has no primary key column.
- */
- rc = detectSchemaProblem(db, "implicit mapping to non-existant primary key",
- "SELECT fkid, from_tbl "
- "FROM temp.fkey "
- "WHERE to_col IS NULL AND NOT EXISTS "
- "(SELECT 1 FROM temp.v_col WHERE pk AND tablename = temp.fkey.to_tbl)"
- , pCallback
- );
- if( rc!=SQLITE_OK ) return rc;
- /* Fix all the implicit primary key mappings in the temp.fkey table. */
- rc = sqlite3_exec(db,
- "UPDATE temp.fkey SET to_col = "
- "(SELECT name FROM temp.v_col WHERE pk AND tablename=temp.fkey.to_tbl)"
- " WHERE to_col IS NULL;"
- , 0, 0, 0
- );
- if( rc!=SQLITE_OK ) return rc;
- /* Now check that all all parent keys are either primary keys or
- ** subject to a unique constraint.
- */
- rc = sqlite3_exec(db,
- "CREATE TABLE temp.idx2 AS SELECT "
- "il.tablename AS tablename,"
- "ii.indexname AS indexname,"
- "ii.name AS col "
- "FROM temp.v_idxlist AS il, temp.v_idxinfo AS ii "
- "WHERE il.isunique AND il.database='main' AND ii.indexname = il.name;"
- "INSERT INTO temp.idx2 "
- "SELECT tablename, 'pk', name FROM temp.v_col WHERE pk;"
- "CREATE TABLE temp.idx AS SELECT "
- "tablename, indexname, sj(dq(col),',') AS cols "
- "FROM (SELECT * FROM temp.idx2 ORDER BY col) "
- "GROUP BY tablename, indexname;"
- "CREATE TABLE temp.fkey2 AS SELECT "
- "fkid, from_tbl, to_tbl, sj(dq(to_col),',') AS cols "
- "FROM (SELECT * FROM temp.fkey ORDER BY to_col) "
- "GROUP BY fkid, from_tbl;"
- "CREATE TABLE temp.triggers AS SELECT "
- "triggername FROM temp.v_triggers WHERE database='main' AND "
- "triggername LIKE 'genfkey%';"
- , 0, 0, 0
- );
- if( rc!=SQLITE_OK ) return rc;
- rc = detectSchemaProblem(db, "foreign key is not unique",
- "SELECT fkid, from_tbl "
- "FROM temp.fkey2 "
- "WHERE NOT EXISTS (SELECT 1 "
- "FROM temp.idx WHERE tablename=to_tbl AND fkey2.cols==idx.cols"
- ")", pCallback
- );
- if( rc!=SQLITE_OK ) return rc;
- return rc;
- }
- #define GENFKEY_ERROR 1
- #define GENFKEY_DROPTRIGGER 2
- #define GENFKEY_CREATETRIGGER 3
- static int genfkey_create_triggers(
- sqlite3 *sdb, /* Connection to read schema from */
- const char *zDb, /* Name of db to read ("main", "temp") */
- void *pCtx, /* Context pointer to pass to xData */
- int (*xData)(void *, int, const char *)
- ){
- const char *zSql =
- "SELECT multireplace('"
- "-- Triggers for foreign key mapping:\n"
- "--\n"
- "-- /from_readable/ REFERENCES /to_readable/\n"
- "-- on delete /on_delete/\n"
- "-- on update /on_update/\n"
- "--\n"
- /* The "BEFORE INSERT ON <referencing>" trigger. This trigger's job is to
- ** throw an exception if the user tries to insert a row into the
- ** referencing table for which there is no corresponding row in
- ** the referenced table.
- */
- "CREATE TRIGGER /name/_insert_referencing BEFORE INSERT ON /tbl/ WHEN \n"
- " /key_notnull/ AND NOT EXISTS (SELECT 1 FROM /ref/ WHERE /cond1/)\n"
- "BEGIN\n"
- " SELECT RAISE(ABORT, ''constraint failed'');\n"
- "END;\n"
- /* The "BEFORE UPDATE ON <referencing>" trigger. This trigger's job
- ** is to throw an exception if the user tries to update a row in the
- ** referencing table causing it to correspond to no row in the
- ** referenced table.
- */
- "CREATE TRIGGER /name/_update_referencing BEFORE\n"
- " UPDATE OF /rkey_list/ ON /tbl/ WHEN \n"
- " /key_notnull/ AND \n"
- " NOT EXISTS (SELECT 1 FROM /ref/ WHERE /cond1/)\n"
- "BEGIN\n"
- " SELECT RAISE(ABORT, ''constraint failed'');\n"
- "END;\n"
- /* The "BEFORE DELETE ON <referenced>" trigger. This trigger's job
- ** is to detect when a row is deleted from the referenced table to
- ** which rows in the referencing table correspond. The action taken
- ** depends on the value of the 'ON DELETE' clause.
- */
- "CREATE TRIGGER /name/_delete_referenced BEFORE DELETE ON /ref/ WHEN\n"
- " EXISTS (SELECT 1 FROM /tbl/ WHERE /cond2/)\n"
- "BEGIN\n"
- " /delete_action/\n"
- "END;\n"
- /* The "AFTER UPDATE ON <referenced>" trigger. This trigger's job
- ** is to detect when the key columns of a row in the referenced table
- ** to which one or more rows in the referencing table correspond are
- ** updated. The action taken depends on the value of the 'ON UPDATE'
- ** clause.
- */
- "CREATE TRIGGER /name/_update_referenced AFTER\n"
- " UPDATE OF /fkey_list/ ON /ref/ WHEN \n"
- " EXISTS (SELECT 1 FROM /tbl/ WHERE /cond2/)\n"
- "BEGIN\n"
- " /update_action/\n"
- "END;\n"
- "'"
- /* These are used in the SQL comment written above each set of triggers */
- ", '/from_readable/', from_tbl || '(' || sj(from_col, ', ') || ')'"
- ", '/to_readable/', to_tbl || '(' || sj(to_col, ', ') || ')'"
- ", '/on_delete/', on_delete"
- ", '/on_update/', on_update"
- ", '/name/', 'genfkey' || min(rowid)"
- ", '/tbl/', dq(from_tbl)"
- ", '/ref/', dq(to_tbl)"
- ", '/key_notnull/', sj('new.' || dq(from_col) || ' IS NOT NULL', ' AND ')"
- ", '/fkey_list/', sj(dq(to_col), ', ')"
- ", '/rkey_list/', sj(dq(from_col), ', ')"
- ", '/cond1/', sj(multireplace('new./from/ == /to/'"
- ", '/from/', dq(from_col)"
- ", '/to/', dq(to_col)"
- "), ' AND ')"
- ", '/cond2/', sj(multireplace('old./to/ == /from/'"
- ", '/from/', dq(from_col)"
- ", '/to/', dq(to_col)"
- "), ' AND ')"
- ", '/update_action/', CASE on_update "
- "WHEN 'SET NULL' THEN "
- "multireplace('UPDATE /tbl/ SET /setlist/ WHERE /where/;' "
- ", '/setlist/', sj(dq(from_col)||' = NULL',', ')"
- ", '/tbl/', dq(from_tbl)"
- ", '/where/', sj(dq(from_col)||' = old.'||dq(to_col),' AND ')"
- ")"
- "WHEN 'CASCADE' THEN "
- "multireplace('UPDATE /tbl/ SET /setlist/ WHERE /where/;' "
- ", '/setlist/', sj(dq(from_col)||' = new.'||dq(to_col),', ')"
- ", '/tbl/', dq(from_tbl)"
- ", '/where/', sj(dq(from_col)||' = old.'||dq(to_col),' AND ')"
- ")"
- "ELSE "
- " 'SELECT RAISE(ABORT, ''constraint failed'');'"
- "END "
- ", '/delete_action/', CASE on_delete "
- "WHEN 'SET NULL' THEN "
- "multireplace('UPDATE /tbl/ SET /setlist/ WHERE /where/;' "
- ", '/setlist/', sj(dq(from_col)||' = NULL',', ')"
- ", '/tbl/', dq(from_tbl)"
- ", '/where/', sj(dq(from_col)||' = old.'||dq(to_col),' AND ')"
- ")"
- "WHEN 'CASCADE' THEN "
- "multireplace('DELETE FROM /tbl/ WHERE /where/;' "
- ", '/tbl/', dq(from_tbl)"
- ", '/where/', sj(dq(from_col)||' = old.'||dq(to_col),' AND ')"
- ")"
- "ELSE "
- " 'SELECT RAISE(ABORT, ''constraint failed'');'"
- "END "
- ") FROM temp.fkey "
- "GROUP BY from_tbl, fkid"
- ;
- int rc;
- const int enc = SQLITE_UTF8;
- sqlite3 *db = 0;
- GenfkeyCb cb;
- cb.xData = xData;
- cb.pCtx = pCtx;
- UNUSED_PARAMETER(zDb);
- /* Open the working database handle. */
- rc = sqlite3_open(":memory:", &db);
- if( rc!=SQLITE_OK ) goto genfkey_exit;
- /* Create the special scalar and aggregate functions used by this program. */
- sqlite3_create_function(db, "dq", 1, enc, 0, doublequote, 0, 0);
- sqlite3_create_function(db, "multireplace", -1, enc, db, multireplace, 0, 0);
- sqlite3_create_function(db, "sj", 2, enc, 0, 0, joinStep, joinFinalize);
- /* Install the "schema" virtual table module */
- installSchemaModule(db, sdb);
- /* Create and populate a temp table with the information required to
- ** build the foreign key triggers. See function populateTempTable()
- ** for details.
- */
- cb.eType = GENFKEY_ERROR;
- rc = populateTempTable(db, &cb);
- if( rc!=SQLITE_OK ) goto genfkey_exit;
- /* Unless the --no-drop option was specified, generate DROP TRIGGER
- ** statements to drop any triggers in the database generated by a
- ** previous run of this program.
- */
- cb.eType = GENFKEY_DROPTRIGGER;
- rc = sqlite3_exec(db,
- "SELECT 'DROP TRIGGER main.' || dq(triggername) || ';' FROM triggers"
- ,invokeCallback, (void *)&cb, 0
- );
- if( rc!=SQLITE_OK ) goto genfkey_exit;
- /* Run the main query to create the trigger definitions. */
- cb.eType = GENFKEY_CREATETRIGGER;
- rc = sqlite3_exec(db, zSql, invokeCallback, (void *)&cb, 0);
- if( rc!=SQLITE_OK ) goto genfkey_exit;
- genfkey_exit:
- sqlite3_close(db);
- return rc;
- }
- #endif
- /* End genfkey logic. */
- /*************************************************************************/
- /*************************************************************************/
- /*
- ** If the following flag is set, then command execution stops
- ** at an error if we are not interactive.
- */
- static int bail_on_error = 0;
- /*
- ** Threat stdin as an interactive input if the following variable
- ** is true. Otherwise, assume stdin is connected to a file or pipe.
- */
- static int stdin_is_interactive = 1;
- /*
- ** The following is the open SQLite database. We make a pointer
- ** to this database a static variable so that it can be accessed
- ** by the SIGINT handler to interrupt database processing.
- */
- static sqlite3 *db = 0;
- /*
- ** True if an interrupt (Control-C) has been received.
- */
- static volatile int seenInterrupt = 0;
- /*
- ** This is the name of our program. It is set in main(), used
- ** in a number of other places, mostly for error messages.
- */
- static char *Argv0;
- /*
- ** Prompt strings. Initialized in main. Settable with
- ** .prompt main continue
- */
- static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
- static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
- /*
- ** Write I/O traces to the following stream.
- */
- #ifdef SQLITE_ENABLE_IOTRACE
- static FILE *iotrace = 0;
- #endif
- /*
- ** This routine works like printf in that its first argument is a
- ** format string and subsequent arguments are values to be substituted
- ** in place of % fields. The result of formatting this string
- ** is written to iotrace.
- */
- #ifdef SQLITE_ENABLE_IOTRACE
- static void iotracePrintf(const char *zFormat, ...){
- va_list ap;
- char *z;
- if( iotrace==0 ) return;
- va_start(ap, zFormat);
- z = sqlite3_vmprintf(zFormat, ap);
- va_end(ap);
- fprintf(iotrace, "%s", z);
- sqlite3_free(z);
- }
- #endif
- /*
- ** Determines if a string is a number of not.
- */
- static int isNumber(const char *z, int *realnum){
- if( *z=='-' || *z=='+' ) z++;
- if( !isdigit(*z) ){
- return 0;
- }
- z++;
- if( realnum ) *realnum = 0;
- while( isdigit(*z) ){ z++; }
- if( *z=='.' ){
- z++;
- if( !isdigit(*z) ) return 0;
- while( isdigit(*z) ){ z++; }
- if( realnum ) *realnum = 1;
- }
- if( *z=='e' || *z=='E' ){
- z++;
- if( *z=='+' || *z=='-' ) z++;
- if( !isdigit(*z) ) return 0;
- while( isdigit(*z) ){ z++; }
- if( realnum ) *realnum = 1;
- }
- return *z==0;
- }
- /*
- ** A global char* and an SQL function to access its current value
- ** from within an SQL statement. This program used to use the
- ** sqlite_exec_printf() API to substitue a string into an SQL statement.
- ** The correct way to do this with sqlite3 is to use the bind API, but
- ** since the shell is built around the callback paradigm it would be a lot
- ** of work. Instead just use this hack, which is quite harmless.
- */
- static const char *zShellStatic = 0;
- static void shellstaticFunc(
- sqlite3_context *context,
- int argc,
- sqlite3_value **argv
- ){
- assert( 0==argc );
- assert( zShellStatic );
- UNUSED_PARAMETER(argc);
- UNUSED_PARAMETER(argv);
- sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
- }
- /*
- ** This routine reads a line of text from FILE in, stores
- ** the text in memory obtained from malloc() and returns a pointer
- ** to the text. NULL is returned at end of file, or if malloc()
- ** fails.
- **
- ** The interface is like "readline" but no command-line editing
- ** is done.
- */
- static char *local_getline(char *zPrompt, FILE *in){
- char *zLine;
- int nLine;
- int n;
- int eol;
- if( zPrompt && *zPrompt ){
- printf("%s",zPrompt);
- fflush(stdout);
- }
- nLine = 100;
- zLine = malloc( nLine );
- if( zLine==0 ) return 0;
- n = 0;
- eol = 0;
- while( !eol ){
- if( n+100>nLine ){
- nLine = nLine*2 + 100;
- zLine = realloc(zLine, nLine);
- if( zLine==0 ) return 0;
- }
- if( fgets(&zLine[n], nLine - n, in)==0 ){
- if( n==0 ){
- free(zLine);
- return 0;
- }
- zLine[n] = 0;
- eol = 1;
- break;
- }
- while( zLine[n] ){ n++; }
- if( n>0 && zLine[n-1]=='\n' ){
- n--;
- if( n>0 && zLine[n-1]=='\r' ) n--;
- zLine[n] = 0;
- eol = 1;
- }
- }
- zLine = realloc( zLine, n+1 );
- return zLine;
- }
- /*
- ** Retrieve a single line of input text.
- **
- ** zPrior is a string of prior text retrieved. If not the empty
- ** string, then issue a continuation prompt.
- */
- static char *one_input_line(const char *zPrior, FILE *in){
- char *zPrompt;
- char *zResult;
- if( in!=0 ){
- return local_getline(0, in);
- }
- if( zPrior && zPrior[0] ){
- zPrompt = continuePrompt;
- }else{
- zPrompt = mainPrompt;
- }
- zResult = readline(zPrompt);
- #if defined(HAVE_READLINE) && HAVE_READLINE==1
- if( zResult && *zResult ) add_history(zResult);
- #endif
- return zResult;
- }
- struct previous_mode_data {
- int valid; /* Is there legit data in here? */
- int mode;
- int showHeader;
- int colWidth[100];
- };
- /*
- ** An pointer to an instance of this structure is passed from
- ** the main program to the callback. This is used to communicate
- ** state and mode information.
- */
- struct callback_data {
- sqlite3 *db; /* The database */
- int echoOn; /* True to echo input commands */
- int cnt; /* Number of records displayed so far */
- FILE *out; /* Write results here */
- int mode; /* An output mode setting */
- int writableSchema; /* True if PRAGMA writable_schema=ON */
- int showHeader; /* True to show column names in List or Column mode */
- char *zDestTable; /* Name of destination table when MODE_Insert */
- char separator[20]; /* Separator character for MODE_List */
- int colWidth[100]; /* Requested width of each column when in column mode*/
- int actualWidth[100]; /* Actual width of each column */
- char nullvalue[20]; /* The text to print when a NULL comes back from
- ** the database */
- struct previous_mode_data explainPrev;
- /* Holds the mode information just before
- ** .explain ON */
- char outfile[FILENAME_MAX]; /* Filename for *out */
- const char *zDbFilename; /* name of the database file */
- sqlite3_stmt *pStmt; /* Current statement if any. */
- FILE *pLog; /* Write log output here */
- };
- /*
- ** These are the allowed modes.
- */
- #define MODE_Line 0 /* One column per line. Blank line between records */
- #define MODE_Column 1 /* One record per line in neat columns */
- #define MODE_List 2 /* One record per line with a separator */
- #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
- #define MODE_Html 4 /* Generate an XHTML table */
- #define MODE_Insert 5 /* Generate SQL "insert" statements */
- #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */
- #define MODE_Csv 7 /* Quote strings, numbers are plain */
- #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */
- static const char *modeDescr[] = {
- "line",
- "column",
- "list",
- "semi",
- "html",
- "insert",
- "tcl",
- "csv",
- "explain",
- };
- /*
- ** Number of elements in an array
- */
- #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
- /*
- ** Compute a string length that is limited to what can be stored in
- ** lower 30 bits of a 32-bit signed integer.
- */
- static int strlen30(const char *z){
- const char *z2 = z;
- while( *z2 ){ z2++; }
- return 0x3fffffff & (int)(z2 - z);
- }
- /*
- ** A callback for the sqlite3_log() interface.
- */
- static void shellLog(void *pArg, int iErrCode, const char *zMsg){
- struct callback_data *p = (struct callback_data*)pArg;
- if( p->pLog==0 ) return;
- fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
- fflush(p->pLog);
- }
- /*
- ** Output the given string as a hex-encoded blob (eg. X'1234' )
- */
- static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
- int i;
- char *zBlob = (char *)pBlob;
- fprintf(out,"X'");
- for(i=0; i<nBlob; i++){ fprintf(out,"%02x",zBlob[i]); }
- fprintf(out,"'");
- }
- /*
- ** Output the given string as a quoted string using SQL quoting conventions.
- */
- static void output_quoted_string(FILE *out, const char *z){
- int i;
- int nSingle = 0;
- for(i=0; z[i]; i++){
- if( z[i]=='\'' ) nSingle++;
- }
- if( nSingle==0 ){
- fprintf(out,"'%s'",z);
- }else{
- fprintf(out,"'");
- while( *z ){
- for(i=0; z[i] && z[i]!='\''; i++){}
- if( i==0 ){
- fprintf(out,"''");
- z++;
- }else if( z[i]=='\'' ){
- fprintf(out,"%.*s''",i,z);
- z += i+1;
- }else{
- fprintf(out,"%s",z);
- break;
- }
- }
- fprintf(out,"'");
- }
- }
- /*
- ** Output the given string as a quoted according to C or TCL quoting rules.
- */
- static void output_c_string(FILE *out, const char *z){
- unsigned int c;
- fputc('"', out);
- while( (c = *(z++))!=0 ){
- if( c=='\\' ){
- fputc(c, out);
- fputc(c, out);
- }else if( c=='\t' ){
- fputc('\\', out);
- fputc('t', out);
- }else if( c=='\n' ){
- fputc('\\', out);
- fputc('n', out);
- }else if( c=='\r' ){
- fputc('\\', out);
- fputc('r', out);
- }else if( !isprint(c) ){
- fprintf(out, "\\%03o", c&0xff);
- }else{
- fputc(c, out);
- }
- }
- fputc('"', out);
- }
- /*
- ** Output the given string with characters that are special to
- ** HTML escaped.
- */
- static void output_html_string(FILE *out, const char *z){
- int i;
- while( *z ){
- for(i=0; z[i]
- && z[i]!='<'
- && z[i]!='&'
- && z[i]!='>'
- && z[i]!='\"'
- && z[i]!='\'';
- i++){}
- if( i>0 ){
- fprintf(out,"%.*s",i,z);
- }
- if( z[i]=='<' ){
- fprintf(out,"<");
- }else if( z[i]=='&' ){
- fprintf(out,"&");
- }else if( z[i]=='>' ){
- fprintf(out,">");
- }else if( z[i]=='\"' ){
- fprintf(out,""");
- }else if( z[i]=='\'' ){
- fprintf(out,"'");
- }else{
- break;
- }
- z += i + 1;
- }
- }
- /*
- ** If a field contains any character identified by a 1 in the following
- ** array, then the string must be quoted for CSV.
- */
- static const char needCsvQuote[] = {
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- };
- /*
- ** Output a single term of CSV. Actually, p->separator is used for
- ** the separator, which may or may not be a comma. p->nullvalue is
- ** the null value. Strings are quoted using ANSI-C rules. Numbers
- ** appear outside of quotes.
- */
- static void output_csv(struct callback_data *p, const char *z, int bSep){
- FILE *out = p->out;
- if( z==0 ){
- fprintf(out,"%s",p->nullvalue);
- }else{
- int i;
- int nSep = strlen30(p->separator);
- for(i=0; z[i]; i++){
- if( needCsvQuote[((unsigned char*)z)[i]]
- || (z[i]==p->separator[0] &&
- (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){
- i = 0;
- break;
- }
- }
- if( i==0 ){
- putc('"', out);
- for(i=0; z[i]; i++){
- if( z[i]=='"' ) putc('"', out);
- putc(z[i], out);
- }
- putc('"', out);
- }else{
- fprintf(out, "%s", z);
- }
- }
- if( bSep ){
- fprintf(p->out, "%s", p->separator);
- }
- }
- #ifdef SIGINT
- /*
- ** This routine runs when the user presses Ctrl-C
- */
- static void interrupt_handler(int NotUsed){
- UNUSED_PARAMETER(NotUsed);
- seenInterrupt = 1;
- if( db ) sqlite3_interrupt(db);
- }
- #endif
- /*
- ** This is the callback routine that the shell
- ** invokes for each row of a query result.
- */
- static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType){
- int i;
- struct callback_data *p = (struct callback_data*)pArg;
- if( p->echoOn && p->cnt==0 && p->pStmt){
- printf("%s\n", sqlite3_sql(p->pStmt));
- }
- switch( p->mode ){
- case MODE_Line: {
- int w = 5;
- if( azArg==0 ) break;
- for(i=0; i<nArg; i++){
- int len = strlen30(azCol[i] ? azCol[i] : "");
- if( len>w ) w = len;
- }
- if( p->cnt++>0 ) fprintf(p->out,"\n");
- for(i=0; i<nArg; i++){
- fprintf(p->out,"%*s = %s\n", w, azCol[i],
- azArg[i] ? azArg[i] : p->nullvalue);
- }
- break;
- }
- case MODE_Explain:
- case MODE_Column: {
- if( p->cnt++==0 ){
- for(i=0; i<nArg; i++){
- int w, n;
- if( i<ArraySize(p->colWidth) ){
- w = p->colWidth[i];
- }else{
- w = 0;
- }
- if( w<=0 ){
- w = strlen30(azCol[i] ? azCol[i] : "");
- if( w<10 ) w = 10;
- n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullvalue);
- if( w<n ) w = n;
- }
- if( i<ArraySize(p->actualWidth) ){
- p->actualWidth[i] = w;
- }
- if( p->showHeader ){
- fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": " ");
- }
- }
- if( p->showHeader ){
- for(i=0; i<nArg; i++){
- int w;
- if( i<ArraySize(p->actualWidth) ){
- w = p->actualWidth[i];
- }else{
- w = 10;
- }
- fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------"
- "----------------------------------------------------------",
- i==nArg-1 ? "\n": " ");
- }
- }
- }
- if( azArg==0 ) break;
- for(i=0; i<nArg; i++){
- int w;
- if( i<ArraySize(p->actualWidth) ){
- w = p->actualWidth[i];
- }else{
- w = 10;
- }
- if( p->mode==MODE_Explain && azArg[i] &&
- strlen30(azArg[i])>w ){
- w = strlen30(azArg[i]);
- }
- fprintf(p->out,"%-*.*s%s",w,w,
- azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " ");
- }
- break;
- }
- case MODE_Semi:
- case MODE_List: {
- if( p->cnt++==0 && p->showHeader ){
- for(i=0; i<nArg; i++){
- fprintf(p->out,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator);
- }
- }
- if( azArg==0 ) break;
- for(i=0; i<nArg; i++){
- char *z = azArg[i];
- if( z==0 ) z = p->nullvalue;
- fprintf(p->out, "%s", z);
- if( i<nArg-1 ){
- fprintf(p->out, "%s", p->separator);
- }else if( p->mode==MODE_Semi ){
- fprintf(p->out, ";\n");
- }else{
- fprintf(p->out, "\n");
- }
- }
- break;
- }
- case MODE_Html: {
- if( p->cnt++==0 && p->showHeader ){
- fprintf(p->out,"<TR>");
- for(i=0; i<nArg; i++){
- fprintf(p->out,"<TH>");
- output_html_string(p->out, azCol[i]);
- fprintf(p->out,"</TH>\n");
- }
- fprintf(p->out,"</TR>\n");
- }
- if( azArg==0 ) break;
- fprintf(p->out,"<TR>");
- for(i=0; i<nArg; i++){
- fprintf(p->out,"<TD>");
- output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
- fprintf(p->out,"</TD>\n");
- }
- fprintf(p->out,"</TR>\n");
- break;
- }
- case MODE_Tcl: {
- if( p->cnt++==0 && p->showHeader ){
- for(i=0; i<nArg; i++){
- output_c_string(p->out,azCol[i] ? azCol[i] : "");
- fprintf(p->out, "%s", p->separator);
- }
- fprintf(p->out,"\n");
- }
- if( azArg==0 ) break;
- for(i=0; i<nArg; i++){
- output_c_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
- fprintf(p->out, "%s", p->separator);
- }
- fprintf(p->out,"\n");
- break;
- }
- case MODE_Csv: {
- if( p->cnt++==0 && p->showHeader ){
- for(i=0; i<nArg; i++){
- output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
- }
- fprintf(p->out,"\n");
- }
- if( azArg==0 ) break;
- for(i=0; i<nArg; i++){
- output_csv(p, azArg[i], i<nArg-1);
- }
- fprintf(p->out,"\n");
- break;
- }
- case MODE_Insert: {
- p->cnt++;
- if( azArg==0 ) break;
- fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
- for(i=0; i<nArg; i++){
- char *zSep = i>0 ? ",": "";
- if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
- fprintf(p->out,"%sNULL",zSep);
- }else if( aiType && aiType[i]==SQLITE_TEXT ){
- if( zSep[0] ) fprintf(p->out,"%s",zSep);
- output_quoted_string(p->out, azArg[i]);
- }else if( aiType && (aiType[i]==SQLITE_INTEGER || aiType[i]==SQLITE_FLOAT) ){
- fprintf(p->out,"%s%s",zSep, azArg[i]);
- }else if( aiType && aiType[i]==…
Large files files are truncated, but you can click here to view the full file