/modules/SQL/Community.CsharpSqlite.shell/src/shell.cs
C# | 4244 lines | 3465 code | 172 blank | 607 comment | 813 complexity | 0ec7fe9f92b91852c8649a6ec6aeded5 MD5 | raw file
Possible License(s): LGPL-2.1, LGPL-3.0, GPL-2.0, GPL-3.0, LGPL-2.0
Large files files are truncated, but you can click here to view the full file
- using System;
- using System.Diagnostics;
- using System.IO;
- using System.Runtime.InteropServices;
- using System.Text;
- using FILE = System.IO.TextWriter;
- using GETPROCTIMES = System.IntPtr;
- using HANDLE = System.IntPtr;
- using HINSTANCE = System.IntPtr;
- using sqlite3_int64 = System.Int64;
- using u32 = System.UInt32;
- using va_list = System.Object;
- using Community.CsharpSqlite;
- namespace SQL
- {
- using dxCallback = Sqlite3.dxCallback;
- using FILETIME = Sqlite3.FILETIME;
- using sqlite3 = Sqlite3.sqlite3;
- using sqlite3_stmt = Sqlite3.Vdbe;
- using sqlite3_value = Sqlite3.Mem;
- public class Shell
- {
- /*
- ** 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.
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- *************************************************************************
- */
- //#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 <Debug.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
- //#if __OS2__
- //# include <unistd.h>
- //#endif
- //#if HAVE_EDITLINE
- //# include <editline/editline.h>
- //#endif
- //#if defined(HAVE_READLINE) && HAVE_READLINE==1
- //# include <readline/readline.h>
- //# include <readline/history.h>
- //#endif
- #if !(HAVE_EDITLINE) //&& (!(HAVE_READLINE) || HAVE_READLINE!=1)
- //# define readline(p) local_getline(p,stdin)
- static string readline(string p)
- {
- return local_getline(p, stdin);
- }
- //# define add_history(X)
- static void add_history(object p) { }
- //# define read_history(X)
- static void read_history(object p) { }
- //# define write_history(X)
- static void write_history(object p) { }
- //# define stifle_history(X)
- static void stifle_history(object p) { }
- #endif
- #if (_WIN32) || (WIN32)
- //# include <io.h>
- //#define isatty(h) _isatty(h)
- static bool isatty(object h) { return stdin.Equals(Console.In); }
- //#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
- /* True if the timer is enabled */
- static bool enableTimer = false;
- #if FALSE//!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;
- ///*
- //** Begin timing an operation
- //*/
- //static void beginTimer(){
- // if( enableTimer ){
- // getrusage(RUSAGE_SELF, sBegin);
- // }
- //}
- ///* Return the difference of two time_structs in seconds */
- //static double timeDiff(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(){
- // 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 ((_WIN32) || (WIN32))
- //#include <windows.h>
- /* Saved resource information for the beginning of an operation */
- static Process hProcess;
- //static FILETIME ftKernelBegin;
- //static FILETIME ftUserBegin;
- static TimeSpan tsUserBegin;
- static TimeSpan tsKernelBegin;
- //typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME);
- /*
- ** Check to see if we have timer support. Return 1 if necessary
- ** support found (or found previously).
- */
- //static bool has_timer()
- //{
- // if (getProcessTimesAddr != IntPtr.Zero)
- // {
- // return true;
- // }
- // 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 = Process.GetCurrentProcess();
- // if (hProcess != null)
- // {
- // HINSTANCE hinstLib = LoadLibrary("Kernel32.dll");
- // if (null != hinstLib)
- // {
- // getProcessTimesAddr = (GETPROCTIMES)GetProcAddress(hinstLib, "GetProcessTimes");
- // if (null != getProcessTimesAddr)
- // {
- // return true;
- // }
- // FreeLibrary(hinstLib);
- // }
- // }
- // }
- // return true;
- //}
- /*
- ** Begin timing an operation
- */
- static void beginTimer()
- {
- if (enableTimer)//&& getProcessTimesAddr != IntPtr.Zero)
- {
- //FILETIME ftCreation, ftExit;
- //getProcessTimesAddr(hProcess, ftCreation, ftExit, ftKernelBegin, ftUserBegin);
- tsUserBegin = Process.GetCurrentProcess().UserProcessorTime;
- tsKernelBegin = Process.GetCurrentProcess().TotalProcessorTime - Process.GetCurrentProcess().UserProcessorTime;
- }
- }
- /* Return the difference of two TimeSpan structs in seconds */
- static double timeDiff(TimeSpan pStart, TimeSpan pEnd)
- {
- //sqlite3_int64 i64Start = ((sqlite3_int64)pStart.dwLowDateTime);
- //sqlite3_int64 i64End = ((sqlite3_int64)pEnd.dwLowDateTime);
- //return (double)((i64End - i64Start) / 10000000.0);
- return timeDiff(pStart, pEnd) / 10000000.0;
- }
- /*
- ** Print the timing results.
- */
- static void endTimer()
- {
- if (enableTimer)// && getProcessTimesAddr != IntPtr.Zero)
- {
- //FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
- //getProcessTimesAddr(hProcess, ftCreation, ftExit, ftKernelEnd, ftUserEnd);
- TimeSpan tsKernelEnd, tsUserEnd;
- tsUserEnd = Process.GetCurrentProcess().UserProcessorTime;
- tsKernelEnd = Process.GetCurrentProcess().TotalProcessorTime - Process.GetCurrentProcess().UserProcessorTime;
- printf("CPU Time: user %f sys %f\n",
- timeDiff(tsUserBegin, tsUserEnd),
- timeDiff(tsKernelBegin, tsKernelEnd));
- }
- }
- //#define BEGIN_TIMER beginTimer()
- //#define END_TIMER endTimer()
- //#define HAS_TIMER HAS_TIMER
- static bool HAS_TIMER = true;
- #else
- //#define BEGIN_TIMER
- //#define END_TIMER
- //#define HAS_TIMER 0
- #endif
- /*
- ** Used to prevent warnings about unused parameters
- */
- //#define UNUSED_PARAMETER(x) ()(x)
- static void UNUSED_PARAMETER<T>(T x) { }
- /*
- ** If the following flag is set, then command execution stops
- ** at an error if we are not interactive.
- */
- static bool bail_on_error = false;
- /*
- ** Threat stdin as an interactive input if the following variable
- ** is true. Otherwise, assume stdin is connected to a file or pipe.
- */
- static bool stdin_is_interactive = true;
- /*
- ** 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 = null;
- /*
- ** True if an interrupt (Control-C) has been received.
- */
- static bool seenInterrupt = false;
- /*
- ** This is the name of our program. It is set in main(), used
- ** in a number of other places, mostly for error messages.
- */
- static string Argv0;
- /*
- ** Prompt strings. Initialized in main. Settable with
- ** .prompt main continue
- */
- static string mainPrompt; /* First line prompt. default: "sqlite> "*/
- static string continuePrompt; /* Continuation prompt. default: " ...> " */
- /*
- ** Write I/O traces to the following stream.
- */
- #if SQLITE_ENABLE_IOTRACE
- static FILE iotrace = null;
- #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.
- */
- #if SQLITE_ENABLE_IOTRACE
- static void iotracePrintf(string zFormat, ...){
- va_list ap;
- string z;
- if( iotrace== null ) return;
- va_start(ap, zFormat);
- z = Sqlite3.SQLITE_vmprintf(zFormat, ap);
- va_end(ap);
- fprintf(iotrace, "%s", z);
- Sqlite3.sqlite3_free(z);
- }
- #endif
- /*
- ** Determines if a string is a number of not.
- */
- //static int isNumber(string z, ref int realnum){
- // if( *z=='-' || *z=='+' ) z++;
- // if( !isdigit(*z) ){
- // return 0;
- // }
- // z++;
- // //if( realnum ) *realnum = 0;
- // realnum = 0;
- // while( isdigit(*z) ){ z++; }
- // if( *z=='.' ){
- // z++;
- // if( !isdigit(*z) ) return 0;
- // while( isdigit(*z) ){ z++; }
- // //if( realnum ) *realnum = 1;
- // 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;
- // realnum = 1;
- // }
- // return *z== null;
- //}
- static bool isNumber(string z)
- {
- int i = 0;
- return isNumber(z, ref i);
- }
- static bool isNumber(string z, int i)
- {
- return isNumber(z, ref i);
- }
- static bool isNumber(string z, ref int realnum)
- {
- int zIdx = 0;
- if (z[zIdx] == '-' || z[zIdx] == '+')
- zIdx++;
- if (zIdx == z.Length || !isdigit(z[zIdx]))
- {
- return false;
- }
- zIdx++;
- realnum = 0;
- while (zIdx < z.Length && isdigit(z[zIdx]))
- {
- zIdx++;
- }
- if (z[zIdx] == '.')
- {
- zIdx++;
- if (zIdx < z.Length && !isdigit(z[zIdx]))
- return false;
- while (zIdx < z.Length && isdigit(z[zIdx]))
- {
- zIdx++;
- }
- realnum = 1;
- }
- if (z[zIdx] == 'e' || z[zIdx] == 'E')
- {
- zIdx++;
- if (zIdx < z.Length && (z[zIdx] == '+' || z[zIdx] == '-'))
- zIdx++;
- if (zIdx == z.Length || !isdigit(z[zIdx]))
- return false;
- while (zIdx < z.Length && isdigit(z[zIdx]))
- {
- zIdx++;
- }
- realnum = 1;
- }
- return zIdx == z.Length;
- }
- /*
- ** A global char* and an SQL function to access its current value
- ** from within an SQL statement. This program used to use the
- ** Sqlite3.sqlite3_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 string zShellStatic = "";
- static void shellstaticFunc(
- Sqlite3.sqlite3_context context,
- int argc,
- sqlite3_value[] argv
- )
- {
- Debug.Assert(0 == argc);
- Debug.Assert(String.IsNullOrEmpty(zShellStatic));
- UNUSED_PARAMETER(argc);
- UNUSED_PARAMETER(argv);
- Sqlite3.sqlite3_result_text(context, zShellStatic, -1, Sqlite3.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 string local_getline(string zPrompt, TextReader In)
- {
- StringBuilder zIn = new StringBuilder();
- StringBuilder zLine;
- int nLine;
- int n;
- bool eol;
- if (zPrompt != null)
- {
- printf("%s", zPrompt);
- fflush(stdout);
- }
- nLine = 100;
- zLine = new StringBuilder(nLine);//malloc( nLine );
- //if( zLine== null ) return 0;
- n = 0;
- eol = false;
- while (!eol)
- {
- if (n + 100 > nLine)
- {
- nLine = nLine * 2 + 100;
- zLine.Capacity = (nLine);//= realloc(zLine, nLine);
- //if (zLine == null)
- // return null;
- }
- if (fgets(zIn, nLine - n, In) == 0)
- {
- if (zLine.Length == 0)
- {
- zLine = null;//free(zLine);
- return null;
- }
- //zLine[n] = 0;
- eol = true;
- break;
- }
- n = 0;
- while (n < zLine.Length && zLine[n] != '\0') { n++; }
- n = zIn.Length - 1;
- if (zIn[n] == '\n')
- {
- n--;
- if (n > 0 && zIn[n - 1] == '\r')
- n--;
- zIn.Length = n + 1;
- eol = true;
- }
- zLine.Append(zIn);
- }
- //zLine = realloc( zLine, n+1 );
- return zLine.ToString();
- }
- /*
- ** 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 string one_input_line(string zPrior, TextReader In)
- {
- string zPrompt;
- string zResult;
- if (In != null)
- {
- return local_getline("", In).ToString();
- }
- if (zPrior != null && zPrior.Length > 0)
- {
- zPrompt = continuePrompt;
- }
- else
- {
- zPrompt = mainPrompt;
- }
- zResult = readline(zPrompt);
- #if (HAVE_READLINE) //&& HAVE_READLINE==1
- if( zResult && *zResult ) add_history(zResult);
- #endif
- return zResult;
- }
- public class previous_mode_data
- {
- public bool valid; /* Is there legit data in here? */
- public int mode;
- public bool showHeader;
- public int[] colWidth = new int[200];
- };
- /*
- ** 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.
- */
- public class callback_data
- {
- public sqlite3 db; /* The database */
- public bool echoOn; /* True to echo input commands */
- public bool statsOn; /* True to display memory stats before each finalize */
- public int cnt; /* Number of records displayed so far */
- public FILE Out; /* Write results here */
- public int mode; /* An output mode setting */
- public bool writableSchema; /* True if PRAGMA writable_schema=ON */
- public bool showHeader; /* True to show column names in List or Column mode */
- public string zDestTable; /* Name of destination table when MODE_Insert */
- public string separator = ""; /* Separator character for MODE_List */
- public int[] colWidth = new int[200]; /* Requested width of each column when in column mode*/
- public int[] actualWidth = new int[200]; /* Actual width of each column */
- public string nullvalue = "NULL"; /* The text to print when a null comes back from
- ** the database */
- public previous_mode_data explainPrev = new previous_mode_data();
- /* Holds the mode information just before
- ** .explain ON */
- public StringBuilder outfile = new StringBuilder(260); /* Filename for Out */
- public string zDbFilename; /* name of the database file */
- public string zVfs; /* Name of VFS to use */
- public sqlite3_stmt pStmt; /* Current statement if any. */
- public FILE pLog; /* Write log output here */
- internal callback_data Copy()
- {
- return (callback_data)this.MemberwiseClone();
- }
- };
- // Store callback data variant
- class callback_data_extra
- {
- public string[] azCols; //(string *)pData; /* Names of result columns */
- public string[] azVals;//azCols[nCol]; /* Results */
- public int[] aiTypes; //(int *)&azVals[nCol]; /* Result types */
- }
- /*
- ** 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 */
- const int MODE_Line = 0;
- const int MODE_Column = 1;
- const int MODE_List = 2;
- const int MODE_Semi = 3;
- const int MODE_Html = 4;
- const int MODE_Insert = 5;
- const int MODE_Tcl = 6;
- const int MODE_Csv = 7;
- const int MODE_Explain = 8;
- static string[] modeDescr = new string[] {
- "line",
- "column",
- "list",
- "semi",
- "html",
- "insert",
- "tcl",
- "csv",
- "explain",
- };
- /*
- ** Number of elements in an array
- */
- //#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
- static int ArraySize<T>(T[] X) { return X.Length; }
- /*
- ** 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(StringBuilder z)
- {
- //string z2 = z;
- //while( *z2 ){ z2++; }
- return 0x3fffffff & z.Length;//(int)(z2 - z);
- }
- static int strlen30(string z)
- {
- //string z2 = z;
- //while( *z2 ){ z2++; }
- return 0x3fffffff & z.Length;//(int)(z2 - z);
- }
- /*
- ** A callback for the Sqlite3.SQLITE_log() interface.
- */
- static void shellLog(object pArg, int iErrCode, string zMsg)
- {
- callback_data p = (callback_data)pArg;
- if (p.pLog == null)
- 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, byte[] pBlob, int nBlob)
- {
- int i;
- //string zBlob = (string )pBlob;
- fprintf(Out, "X'");
- for (i = 0; i < nBlob; i++) { fprintf(Out, "%02x", pBlob[i]); }
- fprintf(Out, "'");
- }
- /*
- ** Output the given string as a quoted string using SQL quoting conventions.
- */
- static void output_quoted_string(TextWriter Out, string z)
- {
- int i;
- int nSingle = 0;
- for (i = 0; z[i] != '\0'; i++)
- {
- if (z[i] == '\'')
- nSingle++;
- }
- if (nSingle == 0)
- {
- fprintf(Out, "'%s'", z);
- }
- else
- {
- fprintf(Out, "'");
- while (z != "")
- {
- for (i = 0; i < z.Length && 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(TextWriter Out, string z)
- {
- char c;
- fputc('"', Out);
- int zIdx = 0;
- while (zIdx < z.Length && (c = z[zIdx++]) != '\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(TextWriter Out, string z)
- {
- int i;
- while (z != "")
- {
- for (i = 0; i < z.Length && z[i] != '<' && z[i] != '&'; i++)
- {
- }
- if (i > 0)
- {
- fprintf(Out, "%.*s", i, z);
- }
- if (i < z.Length && z[i] == '<')
- {
- fprintf(Out, "<");
- }
- else if (i < z.Length && z[i] == '&')
- {
- fprintf(Out, "&");
- }
- else if (i < z.Length && z[i] == '\"')
- {
- fprintf(Out, """);
- }
- else if (i < z.Length && 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 byte[] needCsvQuote = new byte[] {
- 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(callback_data p, string z, bool bSep)
- {
- TextWriter Out = p.Out;
- if (z == null)
- {
- fprintf(Out, "%s", p.nullvalue);
- }
- else
- {
- int i;
- int nSep = strlen30(p.separator);
- for (i = 0; i < z.Length; i++)
- {
- if (needCsvQuote[z[i]] != 0
- || (z[i] == p.separator[0] &&
- (nSep == 1 || z == p.separator)))
- {
- i = 0;
- break;
- }
- }
- if (i == 0)
- {
- putc('"', Out);
- for (i = 0; i < z.Length; 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);
- }
- }
- #if SIGINT
- /*
- ** This routine runs when the user presses Ctrl-C
- */
- static void interrupt_handler(int NotUsed){
- UNUSED_PARAMETER(NotUsed);
- seenInterrupt = 1;
- if( db ) Sqlite3.SQLITE_interrupt(db);
- }
- #endif
- /*
- ** This is the callback routine that the shell
- ** invokes for each row of a query result.
- */
- static int shell_callback(object pArg, sqlite3_int64 nArg, object p2, object p3)
- {
- int i;
- callback_data p = (callback_data)pArg;
- //Unpack
- string[] azArg = ((callback_data_extra)p2).azVals;
- string[] azCol = ((callback_data_extra)p2).azCols;
- int[] aiType = ((callback_data_extra)p2).aiTypes;
- switch (p.mode)
- {
- case MODE_Line:
- {
- int w = 5;
- if (azArg == null)
- break;
- for (i = 0; i < nArg; i++)
- {
- int len = strlen30(azCol[i] != null ? 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] != null ? 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] != null ? azCol[i] : "");
- if (w < 10)
- w = 10;
- n = strlen30(azArg != null && azArg[i] != null ? 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 == null)
- 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] != null &&
- strlen30(azArg[i]) > w)
- {
- w = strlen30(azArg[i]);
- }
- fprintf(p.Out, "%-*.*s%s", w, w,
- azArg[i] != null ? azArg[i] : p.nullvalue, i == nArg - 1 ? "\n" : " ");
- }
- break;
- }
- case MODE_Semi:
- case MODE_List:
- {
- if (p.cnt++ == null && p.showHeader)
- {
- for (i = 0; i < nArg; i++)
- {
- fprintf(p.Out, "%s%s", azCol[i], i == nArg - 1 ? "\n" : p.separator);
- }
- }
- if (azArg == null)
- break;
- for (i = 0; i < nArg; i++)
- {
- string z = azArg[i];
- if (z == null)
- 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++ == null && 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 == null)
- break;
- fprintf(p.Out, "<TR>");
- for (i = 0; i < nArg; i++)
- {
- fprintf(p.Out, "<TD>");
- output_html_string(p.Out, azArg[i] != null ? azArg[i] : p.nullvalue);
- fprintf(p.Out, "</TD>\n");
- }
- fprintf(p.Out, "</TR>\n");
- break;
- }
- case MODE_Tcl:
- {
- if (p.cnt++ == null && p.showHeader)
- {
- for (i = 0; i < nArg; i++)
- {
- output_c_string(p.Out, azCol[i] != null ? azCol[i] : "");
- fprintf(p.Out, "%s", p.separator);
- }
- fprintf(p.Out, "\n");
- }
- if (azArg == null)
- break;
- for (i = 0; i < nArg; i++)
- {
- output_c_string(p.Out, azArg[i] != null ? azArg[i] : p.nullvalue);
- fprintf(p.Out, "%s", p.separator);
- }
- fprintf(p.Out, "\n");
- break;
- }
- case MODE_Csv:
- {
- if (p.cnt++ == null && p.showHeader)
- {
- for (i = 0; i < nArg; i++)
- {
- output_csv(p, azCol[i] != null ? azCol[i] : "", i < nArg - 1);
- }
- fprintf(p.Out, "\n");
- }
- if (azArg == null)
- 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 == null)
- break;
- fprintf(p.Out, "INSERT INTO %s VALUES(", p.zDestTable);
- for (i = 0; i < nArg; i++)
- {
- string zSep = i > 0 ? "," : "";
- if ((azArg[i] == null) || (aiType != null && i < aiType.Length && aiType[i] == Sqlite3.SQLITE_NULL))
- {
- fprintf(p.Out, "%snull", zSep);
- }
- else if (aiType != null && aiType[i] == Sqlite3.SQLITE_TEXT)
- {
- if (!String.IsNullOrEmpty(zSep))
- fprintf(p.Out, "%s", zSep);
- output_quoted_string(p.Out, azArg[i]);
- }
- else if (aiType != null && (aiType[i] == Sqlite3.SQLITE_INTEGER || aiType[i] == Sqlite3.SQLITE_FLOAT))
- {
- fprintf(p.Out, "%s%s", zSep, azArg[i]);
- }
- else if (aiType != null && aiType[i] == Sqlite3.SQLITE_BLOB && p.pStmt != null)
- {
- byte[] pBlob = Sqlite3.sqlite3_column_blob(p.pStmt, i);
- int nBlob = Sqlite3.sqlite3_column_bytes(p.pStmt, i);
- if (!String.IsNullOrEmpty(zSep))
- fprintf(p.Out, "%s", zSep);
- output_hex_blob(p.Out, pBlob, nBlob);
- }
- else if (isNumber(azArg[i], 0))
- {
- fprintf(p.Out, "%s%s", zSep, azArg[i]);
- }
- else
- {
- if (!String.IsNullOrEmpty(zSep))
- fprintf(p.Out, "%s", zSep);
- output_quoted_string(p.Out, azArg[i]);
- }
- }
- fprintf(p.Out, ");\n");
- break;
- }
- }
- return 0;
- }
- /*
- ** This is the callback routine that the SQLite library
- ** invokes for each row of a query result.
- */
- static int callback(object pArg, sqlite3_int64 nArg, object azArg, object azCol)
- {
- /* since we don't have type info, call the shell_callback with a null value */
- callback_data_extra cde = new callback_data_extra();
- cde.azVals = (string[])azArg;
- cde.azCols = (string[])azCol;
- cde.aiTypes = null;
- return shell_callback(pArg, (int)nArg, cde, null);
- }
- /*
- ** Set the destination table field of the callback_data structure to
- ** the name of the table given. Escape any quote characters in the
- ** table name.
- */
- static void set_table_name(callback_data p, string zName)
- {
- int i, n;
- bool needQuote;
- string z = "";
- if (p.zDestTable != null)
- {
- //free(ref p.zDestTable);
- p.zDestTable = null;
- }
- if (zName == null)
- return;
- needQuote = !isalpha(zName[0]) && zName != "_";
- for (i = n = 0; i < zName.Length; i++, n++)
- {
- if (!isalnum(zName[i]) && zName[i] != '_')
- {
- needQuote = true;
- if (zName[i] == '\'')
- n++;
- }
- }
- if (needQuote)
- n += 2;
- //z = p.zDestTable = malloc( n + 1 );
- //if ( z == 0 )
- //{
- // fprintf( stderr, "Out of memory!\n" );
- // exit( 1 );
- //}
- //n = 0;
- if (needQuote)
- z += '\'';
- for (i = 0; i < zName.Length; i++)
- {
- z += zName[i];
- if (zName[i] == '\'')
- z += '\'';
- }
- if (needQuote)
- z += '\'';
- //z[n] = 0;
- p.zDestTable = z;
- }
- /* zIn is either a pointer to a null-terminated string in memory obtained
- ** from malloc(), or a null pointer. The string pointed to by zAppend is
- ** added to zIn, and the result returned in memory obtained from malloc().
- ** zIn, if it was not null, is freed.
- **
- ** If the third argument, quote, is not '\0', then it is used as a
- ** quote character for zAppend.
- */
- static void appendText(StringBuilder zIn, string zAppend, int noQuote)
- { appendText(zIn, zAppend, '\0'); }
- static void appendText(StringBuilder zIn, string zAppend, char quote)
- {
- int len;
- int i;
- int nAppend = strlen30(zAppend);
- int nIn = (zIn != null ? strlen30(zIn) : 0);
- len = nAppend + nIn;
- if (quote != '\0')
- {
- len += 2;
- for (i = 0; i < nAppend; i++)
- {
- if (zAppend[i] == quote)
- len++;
- }
- }
- //zIn = realloc( zIn, len );
- //if ( !zIn )
- //{
- // return 0;
- //}
- if (quote != '\0')
- {
- zIn.Append(quote);
- for (i = 0; i < nAppend; i++)
- {
- zIn.Append(zAppend[i]);
- if (zAppend[i] == quote)
- zIn.Append(quote);
- }
- zIn.Append(quote);
- //zCsr++ = '\0';
- Debug.Assert(zIn.Length == len);
- }
- else
- {
- zIn.Append(zAppend);//memcpy( zIn[nIn], zAppend, nAppend );
- //zIn[len - 1] = '\0';
- }
- }
- /*
- ** Execute a query statement that has a single result column. Print
- ** that result column on a line by itself with a semicolon terminator.
- **
- ** This is used, for example, to show the schema of the database by
- ** querying the Sqlite3.SQLITE_MASTER table.
- */
- static int run_table_dump_query(
- FILE Out, /* Send output here */
- sqlite3 db, /* Database to query */
- StringBuilder zSelect, /* SELECT statement to extract content */
- string zFirstRow /* Print before first row, if not null */
- )
- { return run_table_dump_query(Out, db, zSelect.ToString(), zFirstRow); }
- static int run_table_dump_query(
- FILE Out, /* Send output here */
- sqlite3 db, /* Database to query */
- string zSelect, /* SELECT statement to extract content */
- string zFirstRow /* Print before first row, if not null */
- )
- {
- sqlite3_stmt pSelect = null;
- int rc;
- rc = Sqlite3.sqlite3_prepare(db, zSelect, -1, ref pSelect, 0);
- if (rc != Sqlite3.SQLITE_OK || null == pSelect)
- {
- return rc;
- }
- rc = Sqlite3.sqlite3_step(pSelect);
- while (rc == Sqlite3.SQLITE_ROW)
- {
- if (zFirstRow != null)
- {
- fprintf(Out, "%s", zFirstRow);
- zFirstRow = null;
- }
- fprintf(Out, "%s;\n", Sqlite3.sqlite3_column_text(pSelect, 0));
- rc = Sqlite3.sqlite3_step(pSelect);
- }
- return Sqlite3.sqlite3_finalize(pSelect);
- }
- /*
- ** Allocate space and save off current error string.
- */
- static string save_err_msg(
- sqlite3 db /* Database to query */
- )
- {
- //int nErrMsg = 1 + strlen30(Sqlite3.sqlite3_errmsg(db));
- //string zErrMsg = Sqlite3.sqlite3_malloc(nErrMsg);
- //if (zErrMsg != null)
- //{
- // memcpy(zErrMsg, Sqlite3.sqlite3_errmsg(db), nErrMsg);
- //}
- return Sqlite3.sqlite3_errmsg(db); //zErrMsg;
- }
- /*
- ** Display memory stats.
- */
- static int display_stats(
- sqlite3 db, /* Database to query */
- callback_data pArg, /* Pointer to struct callback_data */
- int bReset /* True to reset the stats */
- )
- {
- int iCur;
- int iHiwtr;
- if (pArg != null && pArg.Out != null)
- {
- iHiwtr = iCur = -1;
- Sqlite3.sqlite3_status(Sqlite3.SQLITE_STATUS_MEMORY_USED, ref iCur, ref iHiwtr, bReset);
- fprintf(pArg.Out, "Memory Used: %d (max %d) bytes\n", iCur, iHiwtr);
- iHiwtr = iCur = -1;
- Sqlite3.sqlite3_status(Sqlite3.SQLITE_STATUS_MALLOC_COUNT, ref iCur, ref iHiwtr, bReset);
- fprintf(pArg.Out, "Number of Outstanding Allocations: %d (max %d)\n", iCur, iHiwtr);
- /*
- ** Not currently used by the CLI.
- ** iHiwtr = iCur = -1;
- ** Sqlite3.SQLITE_status(Sqlite3.SQLITE_STATUS_PAGECACHE_USED,ref iCur,ref iHiwtr, bReset);
- ** fprintf(pArg.Out, "Number of Pcache Pages Used: %d (max %d) pages\n", iCur, iHiwtr);
- */
- iHiwtr = iCur = -1;
- Sqlite3.sqlite3_status(Sqlite3.SQLITE_STATUS_PAGECACHE_OVERFLOW, ref iCur, ref iHiwtr, bReset);
- fprintf(pArg.Out, "Number of Pcache Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr);
- /*
- ** Not currently used by the CLI.
- ** iHiwtr = iCur = -1;
- ** Sqlite3.SQLITE_status(Sqlite3.SQLITE_STATUS_SCRATCH_USED,ref iCur,ref iHiwtr, bReset);
- ** fprintf(pArg.Out, "Number of Scratch Allocations Used: %d (max %d)\n", iCur, iHiwtr);
- */
- iHiwtr = iCur = -1;
- Sqlite3.sqlite3_status(Sqlite3.SQLITE_STATUS_SCRATCH_OVERFLOW, ref iCur, ref iHiwtr, bReset);
- fprintf(pArg.Out, "Number of Scratch Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr);
- iHiwtr = iCur = -1;
- Sqlite3.sqlite3_status(Sqlite3.SQLITE_STATUS_MALLOC_SIZE, ref iCur, ref iHiwtr, bReset);
- fprintf(pArg.Out, "Largest Allocation: %d bytes\n", iHiwtr);
- iHiwtr = iCur = -1;
- Sqlite3.sqlite3_status(Sqlite3.SQLITE_STATUS_PAGECACHE_SIZE, ref iCur, ref iHiwtr, bReset);
- fprintf(pArg.Out, "Largest Pcache Allocation: %d bytes\n", iHiwtr);
- iHiwtr = iCur = -1;
- Sqlite3.sqlite3_status(Sqlite3.SQLITE_STATUS_SCRATCH_SIZE, ref iCur, ref iHiwtr, bReset);
- fprintf(pArg.Out, "Largest Scratch Allocation: %d bytes\n", iHiwtr);
- #if YYTRACKMAXSTACKDEPTH
- iHiwtr = iCur = -1;
- Sqlite3.SQLITE_status(Sqlite3.SQLITE_STATUS_PARSER_STACK,ref iCur,ref iHiwtr, bReset);
- fprintf(pArg.Out, "Deepest Parser Stack: %d (max %d)\n", iCur, iHiwtr);
- #endif
- }
- if (pArg != null && pArg.Out != null && db != null)
- {
- iHiwtr = iCur = -1;
- Sqlite3.sqlite3_db_status(db, Sqlite3.SQLITE_DBSTATUS_LOOKASIDE_USED, ref iCur, ref iHiwtr, bReset);
- fprintf(pArg.Out, "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr);
- Sqlite3.sqlite3_db_status(db, Sqlite3.SQLITE_DBSTATUS_LOOKASIDE_HIT, ref iCur, ref iHiwtr, bReset);
- fprintf(pArg.Out, "Successful lookaside attempts: %d\n", iHiwtr);
- Sqlite3.sqlite3_db_status(db, Sqlite3.SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, ref iCur, ref iHiwtr, bReset);
- fprintf(pArg.Out, "Lookaside failures due to size: %d\n", iHiwtr);…
Large files files are truncated, but you can click here to view the full file