2 * 2005 July 5, Markku Sukanen
3 * - modifying the code for AROS.
7 ** The author disclaims copyright to this source code. In place of
8 ** a legal notice, here is a blessing:
10 ** May you do good and not evil.
11 ** May you find forgiveness for yourself and forgive others.
12 ** May you share freely, never taking more than you give.
14 *************************************************************************
19 * This file contains code to implement the "sqlite" command line utility for
20 * accessing SQLite databases.
27 #include "sqliteInt.h"
30 #if !defined(_WIN32) && !defined(WIN32) && !defined(__MACOS__)
34 # include <sys/types.h>
46 #if defined(HAVE_READLINE) && HAVE_READLINE==1
47 # include <readline/readline.h>
48 # include <readline/history.h>
50 # define readline(p) local_getline(p,stdin)
51 # define add_history(X)
52 # define read_history(X)
53 # define write_history(X)
54 # define stifle_history(X)
58 # define TRACE2(X,Y) sqlite3DebugPrintf(X,Y)
64 * Make sure isatty() has a prototype.
69 * The following is the open SQLite database. We make a pointer to this
70 * database a static variable so that it can be accessed by the SIGINT handler
71 * to interrupt database processing.
73 static sqlite3
*db
= 0;
76 * True if an interrupt (Control-C) has been received.
78 static BOOL seenInterrupt
= FALSE
;
81 * This is the name of our program. It is set in main(), used in a number of
82 * other places, mostly for error messages.
87 * Prompt strings. Initialized in main. Settable with
89 * .prompt main continue
92 static char mainPrompt
[20]; /* First line prompt. default: "sqlite> "*/
93 static char continuePrompt
[20]; /* Continuation prompt. default: " ...> " */
97 * Determines if a string is a number of not.
99 static BOOL
isNumber(const unsigned char *z
, int *realnum
)
101 if( *z
=='-' || *z
=='+' ) z
++;
102 if( !isdigit(*z
) ) return FALSE
;
104 if( realnum
) *realnum
= 0;
105 while( isdigit(*z
) ){ z
++; }
109 if( !isdigit(*z
) ) return FALSE
;
110 while( isdigit(*z
) ){ z
++; }
111 if( realnum
) *realnum
= 1;
113 if( *z
=='e' || *z
=='E' )
116 if( *z
=='+' || *z
=='-' ) z
++;
117 if( !isdigit(*z
) ) return FALSE
;
118 while( isdigit(*z
) ){ z
++; }
119 if( realnum
) *realnum
= 1;
126 * A global char* and an SQL function to access its current value from within
127 * an SQL statement. This program used to use the sqlite_exec_printf() API to
128 * substitue a string into an SQL statement. The correct way to do this with
129 * sqlite3 is to use the bind API, but since the shell is built around the
130 * callback paradigm it would be a lot of work. Instead just use this hack,
131 * which is quite harmless.
133 static CONST_STRPTR zShellStatic
= NULL
;
134 static void shellstaticFunc(
135 sqlite3_context
*context
,
141 assert( zShellStatic
);
142 sqlite3_result_text(context
, zShellStatic
, -1, SQLITE_STATIC
);
147 * This routine reads a line of text from FILE in, stores the text in memory
148 * obtained from malloc() and returns a pointer to the text. NULL is returned
149 * at end of file, or if malloc() fails.
151 * The interface is like "readline" but no command-line editing is done.
153 static STRPTR
local_getline(CONST_STRPTR zPrompt
, FILE *in
)
160 if( zPrompt
&& *zPrompt
!= '\0' )
162 printf("%s",zPrompt
);
166 if( ! (zLine
= malloc( nLine
)))
174 nLine
= nLine
*2 + 100;
175 zLine
= realloc(zLine
, nLine
);
176 if( !zLine
) return NULL
;
178 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 )
189 while( zLine
[n
] ){ n
++; }
190 if( n
>0 && zLine
[n
-1]=='\n' )
197 zLine
= realloc( zLine
, n
+1 );
203 * Retrieve a single line of input text. "isatty" is true if text is coming
204 * from a terminal. In that case, we issue a prompt and attempt to use
205 * "readline" for command-line editing. If "isatty" is false, use
206 * "local_getline" instead of "readline" and issue no prompt.
208 * *zPrior is a string of prior text retrieved. If not the empty string, then
209 * issue a continuation prompt.
211 static STRPTR
one_input_line(CONST_STRPTR zPrior
, FILE *in
)
216 return local_getline(0, in
);
217 if( zPrior
&& zPrior
[0] )
218 zPrompt
= continuePrompt
;
220 zPrompt
= mainPrompt
;
221 zResult
= readline(zPrompt
);
222 #if defined(HAVE_READLINE) && HAVE_READLINE==1
223 if( zResult
) add_history(zResult
);
229 struct previous_mode_data
{
230 int valid
; /* Is there legit data in here? */
238 * An pointer to an instance of this structure is passed from the main program
239 * to the callback. This is used to communicate state and mode information.
241 struct callback_data
{
242 sqlite3
*db
; /* The database */
243 int echoOn
; /* True to echo input commands */
244 int cnt
; /* Number of records displayed so far */
245 FILE *out
; /* Write results here */
246 int mode
; /* An output mode setting */
247 BOOL showHeader
; /* True to show column names in List or Column mode */
248 char *zDestTable
; /* Name of destination table when MODE_Insert */
249 char separator
[20]; /* Separator character for MODE_List */
250 int colWidth
[100]; /* Requested width of each column when in column mode*/
251 int actualWidth
[100];/* Actual width of each column */
252 char nullvalue
[20]; /* The text to print when a NULL comes back from
254 struct previous_mode_data explainPrev
;
255 /* Holds the mode information just before
257 char outfile
[FILENAME_MAX
]; /* Filename for *out */
258 CONST_STRPTR zDbFilename
; /* name of the database file */
259 char *zKey
; /* Encryption key */
264 * These are the allowed modes.
266 #define MODE_Line 0 /* One column per line. Blank line between records */
267 #define MODE_Column 1 /* One record per line in neat columns */
268 #define MODE_List 2 /* One record per line with a separator */
269 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
270 #define MODE_Html 4 /* Generate an XHTML table */
271 #define MODE_Insert 5 /* Generate SQL "insert" statements */
272 #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */
273 #define MODE_Csv 7 /* Quote strings, numbers are plain */
274 #define MODE_NUM_OF 8 /* The number of modes (not a mode itself) */
276 char *modeDescr
[MODE_NUM_OF
] = {
289 * Number of elements in an array.
291 #define ArraySize(X) (sizeof(X)/sizeof(X[0]))
295 * Output the given string as a quoted string using SQL quoting conventions.
297 static void output_quoted_string(FILE *out
, const char *z
)
301 for(i
=0; z
[i
]; i
++){ if( z
[i
]=='\'' ) nSingle
++; }
303 fprintf(out
,"'%s'",z
);
309 for(i
=0; z
[i
] && z
[i
]!='\''; i
++){}
315 else if( z
[i
]=='\'' )
317 fprintf(out
,"%.*s''",i
,z
);
332 * Output the given string as a quoted according to C or TCL quoting rules.
334 static void output_c_string(FILE *out
, const char *z
)
338 while( (c
= *(z
++))!=0 )
360 else if( !isprint(c
) )
361 fprintf(out
, "\\%03o", c
);
370 * Output the given string with characters that are special to HTML escaped.
372 static void output_html_string(FILE *out
, const char *z
)
377 for(i
=0; z
[i
] && z
[i
]!='<' && z
[i
]!='&'; i
++){}
379 fprintf(out
,"%.*s",i
,z
);
383 fprintf(out
,"&");
392 * Output a single term of CSV. Actually, p->separator is used for the
393 * separator, which may or may not be a comma. p->nullvalue is the null value.
394 * Strings are quoted using ANSI-C rules. Numbers appear outside of quotes.
396 static void output_csv(struct callback_data
*p
, const char *z
, int bSep
)
399 fprintf(p
->out
,"%s",p
->nullvalue
);
400 else if( isNumber(z
, 0) )
401 fprintf(p
->out
,"%s",z
);
403 output_c_string(p
->out
, z
);
405 fprintf(p
->out
, p
->separator
);
411 * This routine runs when the user presses Ctrl-C
413 static void interrupt_handler(int NotUsed
)
416 if( db
) sqlite3_interrupt(db
);
422 * This is the callback routine that the SQLite library invokes for each row of
425 static int callback(void *pArg
, int nArg
, char **azArg
, char **azCol
)
428 struct callback_data
*p
= (struct callback_data
*)pArg
;
434 if( azArg
==0 ) break;
435 for(i
=0; i
<nArg
; i
++)
437 int len
= strlen(azCol
[i
]);
440 if( p
->cnt
++>0 ) fprintf(p
->out
,"\n");
441 for(i
=0; i
<nArg
; i
++)
442 fprintf(p
->out
,"%*s = %s\n", w
, azCol
[i
],
443 azArg
[i
] ? azArg
[i
] : p
->nullvalue
);
451 for(i
=0; i
<nArg
; i
++)
454 if( i
<ArraySize(p
->colWidth
) )
459 w
= strlen(azCol
[i
] ? azCol
[i
] : "");
461 n
= strlen(azArg
&& azArg
[i
] ? azArg
[i
]
465 if( i
<ArraySize(p
->actualWidth
) )
466 p
->actualWidth
[i
] = w
;
468 fprintf(p
->out
,"%-*.*s%s",w
,w
,azCol
[i
],
469 i
==nArg
-1 ? "\n": " ");
473 for(i
=0; i
<nArg
; i
++)
476 if( i
<ArraySize(p
->actualWidth
) )
477 w
= p
->actualWidth
[i
];
480 fprintf(p
->out
,"%-*.*s%s",w
,w
,
481 "-----------------------------------"
482 "-----------------------------------"
483 "-----------------------",
484 i
==nArg
-1 ? "\n": " ");
488 if( azArg
==0 ) break;
489 for(i
=0; i
<nArg
; i
++)
492 if( i
<ArraySize(p
->actualWidth
) )
493 w
= p
->actualWidth
[i
];
496 fprintf(p
->out
,"%-*.*s%s",w
,w
,
497 azArg
[i
] ? azArg
[i
] : p
->nullvalue
,
498 i
==nArg
-1 ? "\n": " ");
506 if( p
->cnt
++==0 && p
->showHeader
)
507 for(i
=0; i
<nArg
; i
++)
508 fprintf(p
->out
,"%s%s",azCol
[i
], i
==nArg
-1 ? "\n"
510 if( azArg
==0 ) break;
511 for(i
=0; i
<nArg
; i
++)
514 if( z
==0 ) z
= p
->nullvalue
;
515 fprintf(p
->out
, "%s", z
);
517 fprintf(p
->out
, "%s", p
->separator
);
518 else if( p
->mode
==MODE_Semi
)
519 fprintf(p
->out
, ";\n");
521 fprintf(p
->out
, "\n");
528 if( p
->cnt
++==0 && p
->showHeader
)
530 fprintf(p
->out
,"<TR>");
531 for(i
=0; i
<nArg
; i
++)
532 fprintf(p
->out
,"<TH>%s</TH>",azCol
[i
]);
533 fprintf(p
->out
,"</TR>\n");
535 if( azArg
==0 ) break;
536 fprintf(p
->out
,"<TR>");
537 for(i
=0; i
<nArg
; i
++)
539 fprintf(p
->out
,"<TD>");
540 output_html_string(p
->out
, azArg
[i
] ? azArg
[i
]
542 fprintf(p
->out
,"</TD>\n");
544 fprintf(p
->out
,"</TR>\n");
550 if( p
->cnt
++==0 && p
->showHeader
)
552 for(i
=0; i
<nArg
; i
++)
554 output_c_string(p
->out
,azCol
[i
]);
555 fprintf(p
->out
, "%s", p
->separator
);
557 fprintf(p
->out
,"\n");
559 if( azArg
==0 ) break;
560 for(i
=0; i
<nArg
; i
++)
562 output_c_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullvalue
);
563 fprintf(p
->out
, "%s", p
->separator
);
565 fprintf(p
->out
,"\n");
571 if( p
->cnt
++==0 && p
->showHeader
)
573 for(i
=0; i
<nArg
; i
++)
574 output_csv(p
, azCol
[i
], i
<nArg
-1);
575 fprintf(p
->out
,"\n");
577 if( azArg
==0 ) break;
578 for(i
=0; i
<nArg
; i
++)
579 output_csv(p
, azArg
[i
], i
<nArg
-1);
580 fprintf(p
->out
,"\n");
586 if( azArg
==0 ) break;
587 fprintf(p
->out
,"INSERT INTO %s VALUES(",p
->zDestTable
);
588 for(i
=0; i
<nArg
; i
++)
590 char *zSep
= i
>0 ? ",": "";
592 fprintf(p
->out
,"%sNULL",zSep
);
593 else if( isNumber(azArg
[i
], 0) )
594 fprintf(p
->out
,"%s%s",zSep
, azArg
[i
]);
597 if( zSep
[0] ) fprintf(p
->out
,"%s",zSep
);
598 output_quoted_string(p
->out
, azArg
[i
]);
601 fprintf(p
->out
,");\n");
610 * Set the destination table field of the callback_data structure to the name
611 * of the table given. Escape any quote characters in the table name.
613 static void set_table_name(struct callback_data
*p
, CONST_STRPTR zName
)
622 p
->zDestTable
= NULL
;
625 needQuote
= !isalpha((unsigned char)*zName
) && *zName
!='_';
626 for(i
=n
=0; zName
[i
]; i
++, n
++)
628 if( !isalnum((unsigned char)zName
[i
]) && zName
[i
]!='_' )
631 if( zName
[i
]=='\'' ) n
++;
634 if( needQuote
) n
+= 2;
635 z
= p
->zDestTable
= malloc( n
+1 );
638 fprintf(stderr
,"Out of memory!\n");
642 if( needQuote
) z
[n
++] = '\'';
643 for(i
=0; zName
[i
]; i
++)
646 if( zName
[i
]=='\'' ) z
[n
++] = '\'';
648 if( needQuote
) z
[n
++] = '\'';
654 * zIn is either a pointer to a NULL-terminated string in memory obtained from
655 * malloc(), or a NULL pointer. The string pointed to by zAppend is added to
656 * zIn, and the result returned in memory obtained from malloc(). zIn, if it
657 * was not NULL, is freed.
659 * If the third argument, quote, is not '\0', then it is used as a quote
660 * character for zAppend.
662 static STRPTR
appendText(STRPTR zIn
, CONST_STRPTR zAppend
, char quote
)
666 int nAppend
= strlen(zAppend
);
667 int nIn
= (zIn
?strlen(zIn
):0);
673 for(i
=0; i
<nAppend
; i
++)
674 if( zAppend
[i
]==quote
) len
++;
677 zIn
= (char *)realloc(zIn
, len
);
683 STRPTR zCsr
= &zIn
[nIn
];
685 for(i
=0; i
<nAppend
; i
++)
687 *zCsr
++ = zAppend
[i
];
688 if( zAppend
[i
]==quote
) *zCsr
++ = quote
;
692 assert( (zCsr
-zIn
)==len
);
696 memcpy(&zIn
[nIn
], zAppend
, nAppend
);
705 * Execute a query statement that has a single result column. Print that result
706 * column on a line by itself with a semicolon terminator.
708 static int run_table_dump_query(FILE *out
, sqlite3
*db
, const char *zSelect
)
710 sqlite3_stmt
*pSelect
;
712 rc
= sqlite3_prepare(db
, zSelect
, -1, &pSelect
, 0);
713 if( rc
!=SQLITE_OK
|| !pSelect
)
715 rc
= sqlite3_step(pSelect
);
716 while( rc
==SQLITE_ROW
)
718 fprintf(out
, "%s;\n", sqlite3_column_text(pSelect
, 0));
719 rc
= sqlite3_step(pSelect
);
721 return sqlite3_finalize(pSelect
);
726 * This is a different callback routine used for dumping the database. Each row
727 * received by this callback consists of a table name, the table type ("index"
728 * or "table") and SQL to create the table. This routine should print text
729 * sufficient to recreate the table.
731 static int dump_callback(void *pArg
, int nArg
, char **azArg
, char **azCol
)
737 struct callback_data
*p
= (struct callback_data
*)pArg
;
739 if( nArg
!=3 ) return 1;
744 if( strcmp(zTable
,"sqlite_sequence")!=0 )
745 fprintf(p
->out
, "%s;\n", zSql
);
747 fprintf(p
->out
, "DELETE FROM sqlite_sequence;\n");
749 if( strcmp(zType
, "table")==0 )
751 sqlite3_stmt
*pTableInfo
= NULL
;
752 STRPTR zSelect
= NULL
;
753 STRPTR zTableInfo
= NULL
;
756 zTableInfo
= appendText(zTableInfo
, "PRAGMA table_info(", 0);
757 zTableInfo
= appendText(zTableInfo
, zTable
, '"');
758 zTableInfo
= appendText(zTableInfo
, ");", 0);
760 rc
= sqlite3_prepare(p
->db
, zTableInfo
, -1, &pTableInfo
, 0);
761 if( zTableInfo
) free(zTableInfo
);
762 if( rc
!=SQLITE_OK
|| !pTableInfo
)
767 zSelect
= appendText(zSelect
, "SELECT 'INSERT INTO ' || ", 0);
768 zTmp
= appendText(zTmp
, zTable
, '"');
770 zSelect
= appendText(zSelect
, zTmp
, '\'');
771 zSelect
= appendText(zSelect
, " || ' VALUES(' || ", 0);
772 rc
= sqlite3_step(pTableInfo
);
773 while( rc
==SQLITE_ROW
)
775 zSelect
= appendText(zSelect
, "quote(", 0);
776 zSelect
= appendText(zSelect
, sqlite3_column_text(pTableInfo
, 1),
778 rc
= sqlite3_step(pTableInfo
);
780 zSelect
= appendText(zSelect
, ") || ', ' || ", 0);
782 zSelect
= appendText(zSelect
, ") ", 0);
784 rc
= sqlite3_finalize(pTableInfo
);
787 if( zSelect
) free(zSelect
);
790 zSelect
= appendText(zSelect
, "|| ')' FROM ", 0);
791 zSelect
= appendText(zSelect
, zTable
, '"');
793 rc
= run_table_dump_query(p
->out
, p
->db
, zSelect
);
794 if( rc
==SQLITE_CORRUPT
)
796 zSelect
= appendText(zSelect
, " ORDER BY rowid DESC", 0);
797 rc
= run_table_dump_query(p
->out
, p
->db
, zSelect
);
799 if( zSelect
) free(zSelect
);
808 * Run zQuery. Update dump_callback() as the callback routine. If we get a
809 * SQLITE_CORRUPT error, rerun the query after appending "ORDER BY rowid DESC"
812 static int run_schema_dump_query(
813 struct callback_data
*p
,
819 rc
= sqlite3_exec(p
->db
, zQuery
, dump_callback
, p
, pzErrMsg
);
820 if( rc
==SQLITE_CORRUPT
)
823 int len
= strlen(zQuery
);
824 if( pzErrMsg
) sqlite3_free(*pzErrMsg
);
825 zQ2
= malloc( len
+100 );
826 if( !zQ2
) return rc
;
827 sprintf(zQ2
, "%s ORDER BY rowid DESC", zQuery
);
828 rc
= sqlite3_exec(p
->db
, zQ2
, dump_callback
, p
, pzErrMsg
);
836 * Text of a help message.
838 static char zHelp
[] =
839 ".databases List names and files of attached databases\n"
840 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
841 ".echo ON|OFF Turn command echo on or off\n"
842 ".exit Exit this program\n"
843 ".explain ON|OFF Turn output mode suitable for EXPLAIN on or off.\n"
844 ".header(s) ON|OFF Turn display of headers on or off\n"
845 ".help Show this message\n"
846 ".import FILE TABLE Import data from FILE into TABLE\n"
847 ".indices TABLE Show names of all indices on TABLE\n"
848 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
849 " csv Comma-separated values\n"
850 " column Left-aligned columns. (See .width)\n"
851 " html HTML <table> code\n"
852 " insert SQL insert statements for TABLE\n"
853 " line One value per line\n"
854 " list Values delimited by .separator string\n"
855 " tabs Tab-separated values\n"
856 " tcl TCL list elements\n"
857 ".nullvalue STRING Print STRING in place of NULL values\n"
858 ".output FILENAME Send output to FILENAME\n"
859 ".output stdout Send output to the screen\n"
860 ".prompt MAIN CONTINUE Replace the standard prompts\n"
861 ".quit Exit this program\n"
862 ".read FILENAME Execute SQL in FILENAME\n"
863 #ifdef SQLITE_HAS_CODEC
864 ".rekey OLD NEW NEW Change the encryption key\n"
866 ".schema ?TABLE? Show the CREATE statements\n"
867 ".separator STRING Change separator used by output mode and .import\n"
868 ".show Show the current values for various settings\n"
869 ".tables ?PATTERN? List names of tables matching a LIKE pattern\n"
870 ".timeout MS Try opening locked tables for MS milliseconds\n"
871 ".width NUM NUM ... Set column widths for \"column\" mode\n"
875 /* Forward reference */
876 static void process_input(struct callback_data
*p
, FILE *in
);
880 * Make sure the database is open. If it is not, then open it. If the database
881 * fails to open, print an error message and exit.
883 static void open_db(struct callback_data
*p
)
887 sqlite3_open(p
->zDbFilename
, &p
->db
);
889 #ifdef SQLITE_HAS_CODEC
890 sqlite3_key(p
->db
, p
->zKey
, p
->zKey
? strlen(p
->zKey
) : 0);
892 sqlite3_create_function(db
, "shellstatic", 0, SQLITE_UTF8
, 0,
893 shellstaticFunc
, 0, 0);
894 if( SQLITE_OK
!= sqlite3_errcode(db
) )
896 fprintf(stderr
,"Unable to open database \"%s\": %s\n",
897 p
->zDbFilename
, sqlite3_errmsg(db
));
905 * Do C-language style dequoting.
909 * \r -> carriage return
910 * \NNN -> ascii character NNN in octal
914 static void resolve_backslashes(STRPTR z
)
917 for(i
=j
=0; (c
= z
[i
])!=0; i
++, j
++)
922 if( c
=='n' ) c
= '\n';
923 else if( c
=='t' ) c
= '\t';
924 else if( c
=='r' ) c
= '\r';
925 else if( c
>='0' && c
<='7' )
928 if( z
[i
+1]>='0' && z
[i
+1]<='7' )
931 c
= (c
<<3) + z
[i
] - '0';
932 if( z
[i
+1]>='0' && z
[i
+1]<='7' )
935 c
= (c
<<3) + z
[i
] - '0';
947 * If an input line begins with "." then invoke this routine to process that
950 * Return 1 to exit and 0 to continue.
952 static BOOL
do_meta_command(STRPTR zLine
, struct callback_data
*p
)
960 /* Parse the input line into tokens. */
961 while( zLine
[i
] && nArg
<ArraySize(azArg
) )
963 while( isspace((unsigned char)zLine
[i
]) ){ i
++; }
964 if( zLine
[i
]=='\0' ) break;
965 if( zLine
[i
]=='\'' || zLine
[i
]=='"' )
967 int delim
= zLine
[i
++];
968 azArg
[nArg
++] = &zLine
[i
];
969 while( zLine
[i
] && zLine
[i
]!=delim
){ i
++; }
970 if( zLine
[i
]==delim
)
972 if( delim
=='"' ) resolve_backslashes(azArg
[nArg
-1]);
976 azArg
[nArg
++] = &zLine
[i
];
977 while( zLine
[i
] && !isspace((unsigned char)zLine
[i
]) ){ i
++; }
978 if( zLine
[i
] ) zLine
[i
++] = '\0';
979 resolve_backslashes(azArg
[nArg
-1]);
984 * Process the input line.
986 if( !nArg
) return rc
;
987 n
= strlen(azArg
[0]);
989 if( c
=='d' && n
>1 && strncmp(azArg
[0], "databases", n
)==0 )
991 struct callback_data data
;
992 char *zErrMsg
= NULL
;
994 memcpy(&data
, p
, sizeof(data
));
995 data
.showHeader
= TRUE
;
996 data
.mode
= MODE_Column
;
997 data
.colWidth
[0] = 3;
998 data
.colWidth
[1] = 15;
999 data
.colWidth
[2] = 58;
1001 sqlite3_exec(p
->db
, "PRAGMA database_list; ", callback
,
1005 fprintf(stderr
,"Error: %s\n", zErrMsg
);
1006 sqlite3_free(zErrMsg
);
1009 else if( c
=='d' && strncmp(azArg
[0], "dump", n
)==0 )
1011 STRPTR zErrMsg
= NULL
;
1013 fprintf(p
->out
, "BEGIN TRANSACTION;\n");
1016 run_schema_dump_query(p
,
1017 "SELECT name, type, sql FROM sqlite_master "
1018 "WHERE sql NOT NULL AND type=='table'", 0);
1019 run_schema_dump_query(p
,
1020 "SELECT name, type, sql FROM sqlite_master "
1021 "WHERE sql NOT NULL AND type!='table' AND type!='meta'",
1027 for(i
=1; i
<nArg
; i
++)
1029 zShellStatic
= azArg
[i
];
1030 run_schema_dump_query(p
,
1031 "SELECT name, type, sql FROM sqlite_master "
1032 "WHERE tbl_name LIKE shellstatic() AND type=='table'"
1033 " AND sql NOT NULL", 0);
1034 run_schema_dump_query(p
,
1035 "SELECT name, type, sql FROM sqlite_master "
1036 "WHERE tbl_name LIKE shellstatic() AND type!='table'"
1037 " AND type!='meta' AND sql NOT NULL", 0);
1043 fprintf(stderr
,"Error: %s\n", zErrMsg
);
1044 sqlite3_free(zErrMsg
);
1046 fprintf(p
->out
, "COMMIT;\n");
1048 else if( c
=='e' && strncmp(azArg
[0], "echo", n
)==0 && nArg
>1 )
1052 int val
= atoi(azArg
[1]);
1054 z
[j
] = tolower((unsigned char)z
[j
]);
1055 if( strcmp(z
,"on")==0 )
1057 else if( strcmp(z
,"yes")==0 )
1061 else if( c
=='e' && strncmp(azArg
[0], "exit", n
)==0 )
1063 else if( c
=='e' && strncmp(azArg
[0], "explain", n
)==0 )
1066 static char zOne
[] = "1";
1067 char *z
= nArg
>=2 ? azArg
[1] : zOne
;
1070 z
[j
] = tolower((unsigned char)z
[j
]);
1071 if( strcmp(z
,"on")==0 )
1073 else if( strcmp(z
,"yes")==0 )
1077 if(!p
->explainPrev
.valid
)
1079 p
->explainPrev
.valid
= TRUE
;
1080 p
->explainPrev
.mode
= p
->mode
;
1081 p
->explainPrev
.showHeader
= p
->showHeader
;
1082 memcpy(p
->explainPrev
.colWidth
,p
->colWidth
,sizeof(p
->colWidth
));
1085 * We could put this code under the !p->explainValid condition so
1086 * that it does not execute if we are already in explain mode.
1087 * However, always executing it allows us an easy way to reset to
1088 * explain mode in case the user previously did an .explain
1089 * followed by a .width, .mode or .header command.
1091 p
->mode
= MODE_Column
;
1092 p
->showHeader
= TRUE
;
1093 memset(p
->colWidth
,0,ArraySize(p
->colWidth
));
1095 p
->colWidth
[1] = 12;
1096 p
->colWidth
[2] = 10;
1097 p
->colWidth
[3] = 10;
1098 p
->colWidth
[4] = 35;
1100 else if (p
->explainPrev
.valid
)
1102 p
->explainPrev
.valid
= FALSE
;
1103 p
->mode
= p
->explainPrev
.mode
;
1104 p
->showHeader
= p
->explainPrev
.showHeader
;
1105 memcpy(p
->colWidth
,p
->explainPrev
.colWidth
,sizeof(p
->colWidth
));
1108 else if( c
=='h' && (strncmp(azArg
[0], "header", n
)==0
1109 || strncmp(azArg
[0], "headers", n
)==0 )&& nArg
>1 )
1113 int val
= atoi(azArg
[1]);
1115 z
[j
] = tolower((unsigned char)z
[j
]);
1116 if( strcmp(z
,"on")==0 )
1118 else if( strcmp(z
,"yes")==0 )
1120 p
->showHeader
= val
;
1122 else if( c
=='h' && strncmp(azArg
[0], "help", n
)==0 )
1123 fprintf(stderr
,zHelp
);
1124 else if( c
=='i' && strncmp(azArg
[0], "import", n
)==0 && nArg
>=3 )
1126 char *zTable
= azArg
[2]; /* Insert data into this table */
1127 char *zFile
= azArg
[1]; /* The file from which to extract data */
1128 sqlite3_stmt
*pStmt
; /* A statement */
1129 int rc
; /* Result code */
1130 int nCol
; /* Number of columns in the table */
1131 int nByte
; /* Number of bytes in an SQL string */
1132 int i
, j
; /* Loop counters */
1133 int nSep
; /* Number of bytes in p->separator[] */
1134 STRPTR zSql
; /* An SQL statement */
1135 STRPTR zLine
; /* A single line of input from the file */
1136 char **azCol
; /* zLine[] broken up into columns */
1137 STRPTR zCommit
; /* How to commit changes */
1138 FILE *in
; /* The input file */
1139 int lineno
= 0; /* Line number of input file */
1141 nSep
= strlen(p
->separator
);
1144 fprintf(stderr
, "non-null separator required for import\n");
1147 zSql
= sqlite3_mprintf("SELECT * FROM '%q'", zTable
);
1148 if( !zSql
) return 0;
1149 nByte
= strlen(zSql
);
1150 rc
= sqlite3_prepare(p
->db
, zSql
, 0, &pStmt
, 0);
1154 fprintf(stderr
,"Error: %s\n", sqlite3_errmsg(db
));
1158 nCol
= sqlite3_column_count(pStmt
);
1159 sqlite3_finalize(pStmt
);
1160 if( nCol
==0 ) return 0;
1161 zSql
= malloc( nByte
+ 20 + nCol
*2 );
1162 if( zSql
==0 ) return 0;
1163 sqlite3_snprintf(nByte
+20, zSql
, "INSERT INTO '%q' VALUES(?", zTable
);
1165 for(i
=1; i
<nCol
; i
++)
1172 rc
= sqlite3_prepare(p
->db
, zSql
, 0, &pStmt
, 0);
1176 fprintf(stderr
, "Error: %s\n", sqlite3_errmsg(db
));
1177 sqlite3_finalize(pStmt
);
1180 in
= fopen(zFile
, "rb");
1183 fprintf(stderr
, "cannot open file: %s\n", zFile
);
1184 sqlite3_finalize(pStmt
);
1187 azCol
= malloc( sizeof(azCol
[0])*(nCol
+1) );
1188 if( azCol
==0 ) return 0;
1189 sqlite3_exec(p
->db
, "BEGIN", 0, 0, 0);
1191 while( (zLine
= local_getline(0, in
)))
1197 for(i
=0, z
=zLine
; *z
&& *z
!='\n' && *z
!='\r'; z
++)
1199 if( *z
==p
->separator
[0] && strncmp(z
, p
->separator
, nSep
)==0 )
1205 azCol
[i
] = &z
[nSep
];
1212 fprintf(stderr
, "%s line %d: expected %d columns of data but "
1213 "found %d\n", zFile
, lineno
, nCol
, i
+1);
1214 zCommit
= "ROLLBACK";
1217 for(i
=0; i
<nCol
; i
++)
1218 sqlite3_bind_text(pStmt
, i
+1, azCol
[i
], -1, SQLITE_STATIC
);
1219 sqlite3_step(pStmt
);
1220 rc
= sqlite3_reset(pStmt
);
1224 fprintf(stderr
,"Error: %s\n", sqlite3_errmsg(db
));
1225 zCommit
= "ROLLBACK";
1231 sqlite3_finalize(pStmt
);
1232 sqlite3_exec(p
->db
, zCommit
, 0, 0, 0);
1234 else if( c
=='i' && strncmp(azArg
[0], "indices", n
)==0 && nArg
>1 )
1236 struct callback_data data
;
1237 char* zErrMsg
= NULL
;
1239 memcpy(&data
, p
, sizeof(data
));
1240 data
.showHeader
= FALSE
;
1241 data
.mode
= MODE_List
;
1242 zShellStatic
= azArg
[1];
1244 "SELECT name FROM sqlite_master "
1245 "WHERE type='index' AND tbl_name LIKE shellstatic() "
1247 "SELECT name FROM sqlite_temp_master "
1248 "WHERE type='index' AND tbl_name LIKE shellstatic() "
1250 callback
, &data
, &zErrMsg
);
1251 zShellStatic
= NULL
;
1254 fprintf(stderr
,"Error: %s\n", zErrMsg
);
1255 sqlite3_free(zErrMsg
);
1258 else if( c
=='m' && strncmp(azArg
[0], "mode", n
)==0 && nArg
>=2 )
1260 int n2
= strlen(azArg
[1]);
1261 if( strncmp(azArg
[1],"line",n2
)==0
1262 || strncmp(azArg
[1],"lines",n2
)==0 )
1263 p
->mode
= MODE_Line
;
1264 else if( strncmp(azArg
[1],"column",n2
)==0
1265 || strncmp(azArg
[1],"columns",n2
)==0 )
1266 p
->mode
= MODE_Column
;
1267 else if( strncmp(azArg
[1],"list",n2
)==0 )
1268 p
->mode
= MODE_List
;
1269 else if( strncmp(azArg
[1],"html",n2
)==0 )
1270 p
->mode
= MODE_Html
;
1271 else if( strncmp(azArg
[1],"tcl",n2
)==0 )
1273 else if( strncmp(azArg
[1],"csv",n2
)==0 )
1276 strcpy(p
->separator
, ",");
1278 else if( strncmp(azArg
[1],"tabs",n2
)==0 )
1280 p
->mode
= MODE_List
;
1281 strcpy(p
->separator
, "\t");
1283 else if( strncmp(azArg
[1],"insert",n2
)==0 )
1285 p
->mode
= MODE_Insert
;
1287 set_table_name(p
, azArg
[2]);
1289 set_table_name(p
, "table");
1292 fprintf(stderr
,"mode should be on of: "
1293 "column csv html insert line list tabs tcl\n");
1295 else if( c
=='n' && strncmp(azArg
[0], "nullvalue", n
)==0 && nArg
==2 )
1296 sprintf(p
->nullvalue
, "%.*s", (int)ArraySize(p
->nullvalue
)-1, azArg
[1]);
1297 else if( c
=='o' && strncmp(azArg
[0], "output", n
)==0 && nArg
==2 )
1299 if( p
->out
!=stdout
)
1301 if( strcmp(azArg
[1],"stdout")==0 )
1304 strcpy(p
->outfile
,"stdout");
1308 p
->out
= fopen(azArg
[1], "wb");
1311 fprintf(stderr
,"can't write to \"%s\"\n", azArg
[1]);
1314 else strcpy(p
->outfile
,azArg
[1]);
1317 else if( c
=='p' && strncmp(azArg
[0], "prompt", n
)==0
1318 && (nArg
==2 || nArg
==3))
1321 strncpy(mainPrompt
,azArg
[1],(int)ArraySize(mainPrompt
)-1);
1323 strncpy(continuePrompt
,azArg
[2],(int)ArraySize(continuePrompt
)-1);
1325 else if( c
=='q' && strncmp(azArg
[0], "quit", n
)==0 )
1327 else if( c
=='r' && strncmp(azArg
[0], "read", n
)==0 && nArg
==2 )
1329 FILE *alt
= fopen(azArg
[1], "rb");
1331 fprintf(stderr
,"can't open \"%s\"\n", azArg
[1]);
1334 process_input(p
, alt
);
1339 #ifdef SQLITE_HAS_CODEC
1340 c
=='r' && strncmp(azArg
[0],"rekey", n
)==0 && nArg
==4 )
1342 char *zOld
= p
->zKey
;
1343 if( zOld
==0 ) zOld
= "";
1344 if( strcmp(azArg
[1],zOld
) )
1345 fprintf(stderr
,"old key is incorrect\n");
1346 else if( strcmp(azArg
[2], azArg
[3]) )
1347 fprintf(stderr
,"2nd copy of new key does not match the 1st\n");
1350 sqlite3_free(p
->zKey
);
1351 p
->zKey
= sqlite3_mprintf("%s", azArg
[2]);
1352 sqlite3_rekey(p
->db
, p
->zKey
, strlen(p
->zKey
));
1357 c
=='s' && strncmp(azArg
[0], "schema", n
)==0 )
1359 struct callback_data data
;
1360 char *zErrMsg
= NULL
;
1362 memcpy(&data
, p
, sizeof(data
));
1363 data
.showHeader
= FALSE
;
1364 data
.mode
= MODE_Semi
;
1368 for(i
=0; azArg
[1][i
]; i
++) azArg
[1][i
] = tolower(azArg
[1][i
]);
1369 if( strcmp(azArg
[1],"sqlite_master")==0 )
1371 char *new_argv
[2], *new_colv
[2];
1372 new_argv
[0] = "CREATE TABLE sqlite_master (\n"
1376 " rootpage integer,\n"
1380 new_colv
[0] = "sql";
1382 callback(&data
, 1, new_argv
, new_colv
);
1384 else if( strcmp(azArg
[1],"sqlite_temp_master")==0 )
1386 char *new_argv
[2], *new_colv
[2];
1387 new_argv
[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
1391 " rootpage integer,\n"
1395 new_colv
[0] = "sql";
1397 callback(&data
, 1, new_argv
, new_colv
);
1401 zShellStatic
= azArg
[1];
1404 " (SELECT * FROM sqlite_master UNION ALL"
1405 " SELECT * FROM sqlite_temp_master) "
1406 "WHERE tbl_name LIKE shellstatic() "
1407 "AND type!='meta' AND sql NOTNULL "
1408 "ORDER BY substr(type,2,1), name",
1409 callback
, &data
, &zErrMsg
);
1410 zShellStatic
= NULL
;
1413 else sqlite3_exec(p
->db
,
1415 " (SELECT * FROM sqlite_master UNION ALL"
1416 " SELECT * FROM sqlite_temp_master) "
1417 "WHERE type!='meta' AND sql NOTNULL "
1418 "ORDER BY substr(type,2,1), name",
1419 callback
, &data
, &zErrMsg
);
1423 fprintf(stderr
,"Error: %s\n", zErrMsg
);
1424 sqlite3_free(zErrMsg
);
1427 else if( c
=='s' && strncmp(azArg
[0], "separator", n
)==0 && nArg
==2 )
1428 sprintf(p
->separator
, "%.*s", (int)ArraySize(p
->separator
)-1, azArg
[1]);
1429 else if( c
=='s' && strncmp(azArg
[0], "show", n
)==0)
1432 fprintf(p
->out
,"%9.9s: %s\n","echo", p
->echoOn
? "on" : "off");
1433 fprintf(p
->out
,"%9.9s: %s\n","explain", p
->explainPrev
.valid
1435 fprintf(p
->out
,"%9.9s: %s\n","headers", p
->showHeader
? "on" : "off");
1436 fprintf(p
->out
,"%9.9s: %s\n","mode", modeDescr
[p
->mode
]);
1437 fprintf(p
->out
,"%9.9s: ", "nullvalue");
1438 output_c_string(p
->out
, p
->nullvalue
);
1439 fprintf(p
->out
, "\n");
1440 fprintf(p
->out
,"%9.9s: %s\n","output",
1441 strlen(p
->outfile
) ? p
->outfile
: "stdout");
1442 fprintf(p
->out
,"%9.9s: ", "separator");
1443 output_c_string(p
->out
, p
->separator
);
1444 fprintf(p
->out
, "\n");
1445 fprintf(p
->out
,"%9.9s: ","width");
1446 for (i
=0;i
<(int)ArraySize(p
->colWidth
) && p
->colWidth
[i
] != 0;i
++)
1447 fprintf(p
->out
,"%d ",p
->colWidth
[i
]);
1448 fprintf(p
->out
,"\n");
1450 else if( c
=='t' && n
>1 && strncmp(azArg
[0], "tables", n
)==0 )
1457 rc
= sqlite3_get_table(p
->db
,
1458 "SELECT name FROM sqlite_master "
1459 "WHERE type IN ('table','view') "
1461 "SELECT name FROM sqlite_temp_master "
1462 "WHERE type IN ('table','view') "
1464 &azResult
, &nRow
, 0, &zErrMsg
);
1467 zShellStatic
= azArg
[1];
1468 rc
= sqlite3_get_table(p
->db
,
1469 "SELECT name FROM sqlite_master "
1470 "WHERE type IN ('table','view') "
1471 "AND name LIKE '%'||shellstatic()||'%' "
1473 "SELECT name FROM sqlite_temp_master "
1474 "WHERE type IN ('table','view') "
1475 "AND name LIKE '%'||shellstatic()||'%' "
1477 &azResult
, &nRow
, 0, &zErrMsg
1479 zShellStatic
= NULL
;
1483 fprintf(stderr
,"Error: %s\n", zErrMsg
);
1484 sqlite3_free(zErrMsg
);
1488 int len
, maxlen
= 0;
1490 int nPrintCol
, nPrintRow
;
1491 for(i
=1; i
<=nRow
; i
++)
1493 if( azResult
[i
]==0 ) continue;
1494 len
= strlen(azResult
[i
]);
1495 if( len
>maxlen
) maxlen
= len
;
1497 nPrintCol
= 80/(maxlen
+2);
1498 if( nPrintCol
<1 ) nPrintCol
= 1;
1499 nPrintRow
= (nRow
+ nPrintCol
- 1)/nPrintCol
;
1500 for(i
=0; i
<nPrintRow
; i
++)
1502 for(j
=i
+1; j
<=nRow
; j
+=nPrintRow
)
1504 STRPTR zSp
= j
<=nPrintRow
? "" : " ";
1505 printf("%s%-*s", zSp
, maxlen
,
1506 azResult
[j
] ? azResult
[j
] : "");
1511 sqlite3_free_table(azResult
);
1513 else if( c
=='t' && n
>1 && strncmp(azArg
[0], "timeout", n
)==0 && nArg
>=2 )
1516 sqlite3_busy_timeout(p
->db
, atoi(azArg
[1]));
1518 else if( c
=='w' && strncmp(azArg
[0], "width", n
)==0 )
1521 for(j
=1; j
<nArg
&& j
<ArraySize(p
->colWidth
); j
++)
1522 p
->colWidth
[j
-1] = atoi(azArg
[j
]);
1524 else fprintf(stderr
, "unknown command or invalid arguments: "
1525 " \"%s\". Enter \".help\" for help\n", azArg
[0]);
1532 * Return TRUE if the last non-whitespace character in z[] is a semicolon.
1533 * z[] is N characters long.
1535 static int _ends_with_semicolon(CONST_STRPTR z
, int N
)
1537 while( N
>0 && isspace((unsigned char)z
[N
-1]) ){ N
--; }
1538 return N
>0 && z
[N
-1]==';';
1543 * Test to see if a line consists entirely of whitespace.
1545 static BOOL
_all_whitespace(CONST_STRPTR z
)
1549 if( isspace(*(unsigned char*)z
) ) continue;
1550 if( *z
=='/' && z
[1]=='*' )
1553 while( *z
&& (*z
!='*' || z
[1]!='/') ){ z
++; }
1554 if( *z
=='\0' ) return FALSE
;
1558 if( *z
=='-' && z
[1]=='-' )
1561 while( *z
&& *z
!='\n' ){ z
++; }
1562 if( *z
=='\0' ) return TRUE
;
1572 * Return TRUE if the line typed in is an SQL command terminator other than a
1573 * semi-colon. The SQL Server style "go" command is understood as is the Oracle
1576 static BOOL
_is_command_terminator(const char *zLine
)
1578 while( isspace(*(unsigned char*)zLine
) ){ zLine
++; };
1579 if( zLine
[0]=='/' && _all_whitespace(&zLine
[1]) ) return 1; /* Oracle */
1580 if( tolower(zLine
[0])=='g' && tolower(zLine
[1])=='o'
1581 && _all_whitespace(&zLine
[2]) )
1582 return TRUE
; /* SQL Server */
1588 * Read input from *in and process it. If *in==0 then input is interactive -
1589 * the user is typing it it. Otherwise, input is coming from a file or device.
1590 * A prompt is issued and history is saved only if input is interactive. An
1591 * interrupt signal will cause this routine to exit immediately, unless input
1594 static void process_input(struct callback_data
*p
, FILE *in
)
1602 while( fflush(p
->out
), (zLine
= one_input_line(zSql
, in
))!=0 )
1607 seenInterrupt
= FALSE
;
1609 if( p
->echoOn
) printf("%s\n", zLine
);
1610 if( (zSql
==0 || zSql
[0]==0) && _all_whitespace(zLine
) ) continue;
1611 if( zLine
&& zLine
[0]=='.' && nSql
==0 )
1613 int rc
= do_meta_command(zLine
, p
);
1618 if( _is_command_terminator(zLine
) )
1623 for(i
=0; zLine
[i
] && isspace((unsigned char)zLine
[i
]); i
++){}
1626 nSql
= strlen(zLine
);
1627 zSql
= malloc( nSql
+1 );
1628 strcpy(zSql
, zLine
);
1633 int len
= strlen(zLine
);
1634 zSql
= realloc( zSql
, nSql
+ len
+ 2 );
1637 fprintf(stderr
,"%s: out of memory!\n", Argv0
);
1640 strcpy(&zSql
[nSql
++], "\n");
1641 strcpy(&zSql
[nSql
], zLine
);
1645 if( zSql
&& _ends_with_semicolon(zSql
, nSql
)
1646 && sqlite3_complete(zSql
) )
1650 rc
= sqlite3_exec(p
->db
, zSql
, callback
, p
, &zErrMsg
);
1653 if( in
&& !p
->echoOn
) printf("%s\n",zSql
);
1656 #if defined( SQLITE_DEBUG ) && defined( OS_AROS )
1657 printf("SQL error: %s in %s\n", zErrMsg
, arosErrLoc
);
1660 printf("SQL error: %s\n", zErrMsg
);
1662 sqlite3_free(zErrMsg
);
1667 #if defined( SQLITE_DEBUG ) && defined( OS_AROS )
1668 printf("SQL error: %s in %s\n", zErrMsg
, arosErrLoc
);
1671 printf("SQL error: %s\n", sqlite3_errmsg(p
->db
));
1682 if( !_all_whitespace(zSql
) ) printf("Incomplete SQL: %s\n", zSql
);
1689 * Return a pathname which is the user's home directory. A NULL return
1690 * indicates an error of some kind. Space to hold the resulting string is
1691 * obtained from malloc(). The calling function should free the result.
1693 static STRPTR
find_home_dir(void)
1695 STRPTR home_dir
= NULL
;
1696 #if !defined(_WIN32) && !defined(WIN32) && !defined(__MACOS__)
1697 struct passwd
*pwent
;
1698 uid_t uid
= getuid();
1699 if( (pwent
=getpwuid(uid
)) != NULL
)
1700 home_dir
= pwent
->pw_dir
;
1704 char home_path
[_MAX_PATH
+1];
1705 home_dir
= getcwd(home_path
, _MAX_PATH
);
1710 home_dir
= getenv("HOME");
1712 home_dir
= getenv("HOMEPATH"); /* Windows? */
1715 #if defined(_WIN32) || defined(WIN32)
1719 #if defined(OS_AROS)
1721 home_dir
= "PROGDIR:";
1726 STRPTR z
= malloc( strlen(home_dir
)+1 );
1727 if( z
) strcpy(z
, home_dir
);
1735 * Read input from the file given by sqliterc_override. Or if that parameter is
1736 * NULL, take input from ~/.sqliterc
1738 static void process_sqliterc(
1739 struct callback_data
*p
, /* Configuration data */
1740 CONST_STRPTR sqliterc_override
/* Name of config file.
1741 NULL to use default */
1744 STRPTR home_dir
= NULL
;
1745 CONST_STRPTR sqliterc
= sqliterc_override
;
1749 if (sqliterc
== NULL
)
1751 home_dir
= find_home_dir();
1754 fprintf(stderr
,"%s: cannot locate your home directory!\n", Argv0
);
1757 zBuf
= malloc(strlen(home_dir
) + 15);
1760 fprintf(stderr
,"%s: out of memory!\n", Argv0
);
1763 sprintf(zBuf
,"%s/.sqliterc",home_dir
);
1765 sqliterc
= (CONST_STRPTR
)zBuf
;
1767 in
= fopen(sqliterc
,"rb");
1770 if( isatty(fileno(stdout
)) )
1772 printf("Loading resources from %s\n",sqliterc
);
1774 process_input(p
,in
);
1781 * Show available command line options.
1783 static const char zOptions
[] =
1784 " -init filename read/process named file\n"
1785 " -echo print commands before execution\n"
1786 " -[no]header turn headers on or off\n"
1787 " -column set output mode to 'column'\n"
1788 " -html set output mode to HTML\n"
1789 #ifdef SQLITE_HAS_CODEC
1790 " -key KEY encryption key\n"
1792 " -line set output mode to 'line'\n"
1793 " -list set output mode to 'list'\n"
1794 " -separator 'x' set output field separator (|)\n"
1795 " -nullvalue 'text' set text string for NULL values\n"
1796 " -version show SQLite version\n"
1797 " -help show this text, also show dot-commands\n"
1799 static void usage(BOOL showDetail
)
1801 fprintf(stderr
, "Usage: %s [OPTIONS] FILENAME [SQL]\n", Argv0
);
1803 fprintf(stderr
, "Options are:\n%s", zOptions
);
1805 fprintf(stderr
, "Use the -help option for additional information\n");
1811 * Initialize the state information in data.
1813 void main_init(struct callback_data
*data
)
1815 memset(data
, 0, sizeof(*data
));
1816 data
->mode
= MODE_List
;
1817 strcpy(data
->separator
,"|");
1818 data
->showHeader
= FALSE
;
1819 strcpy(mainPrompt
,"sqlite> ");
1820 strcpy(continuePrompt
," ...> ");
1824 int main(int argc
, char **argv
)
1826 char *zErrMsg
= NULL
;
1827 struct callback_data data
;
1828 CONST_STRPTR zInitFile
= NULL
;
1829 STRPTR zFirstCmd
= NULL
;
1833 argc
= ccommand(&argv
);
1840 * Make sure we have a valid signal handler early, before anything else is
1844 signal(SIGINT
, interrupt_handler
);
1848 * Do an initial pass through the command-line argument to locate the name
1849 * of the database file, the name of the initialization file, and the first
1850 * command to execute.
1852 for(i
=1; i
<argc
-1; i
++)
1854 if( argv
[i
][0]!='-' ) break;
1855 if( strcmp(argv
[i
],"-separator")==0 || strcmp(argv
[i
],"-nullvalue")==0 )
1857 else if( strcmp(argv
[i
],"-init")==0 )
1860 zInitFile
= argv
[i
];
1862 else if( strcmp(argv
[i
],"-key")==0 )
1865 data
.zKey
= sqlite3_mprintf("%s",argv
[i
]);
1869 data
.zDbFilename
= argv
[i
++];
1872 #ifndef SQLITE_OMIT_MEMORYDB
1873 data
.zDbFilename
= ":memory:";
1875 data
.zDbFilename
= NULL
;
1879 zFirstCmd
= argv
[i
++];
1883 * Go ahead and open the database file if it already exists. If the file
1884 * does not exist, delay opening it. This prevents empty database files
1885 * from being created if a user mistypes the database name argument to the
1886 * sqlite command-line tool.
1888 if( access(data
.zDbFilename
, 0)==0 )
1892 * Process the initialization file if there is one. If no -init option is
1893 * given on the command line, look for a file named ~/.sqliterc and try to
1896 process_sqliterc(&data
,zInitFile
);
1899 * Make a second pass through the command-line argument and set options.
1900 * This second pass is delayed until after the initialization file is
1901 * processed so that the command-line arguments will override settings in
1902 * the initialization file.
1904 for(i
=1; i
<argc
&& argv
[i
][0]=='-'; i
++)
1907 if( strcmp(z
,"-init")==0 || strcmp(z
,"-key")==0 )
1909 else if( strcmp(z
,"-html")==0 )
1910 data
.mode
= MODE_Html
;
1911 else if( strcmp(z
,"-list")==0 )
1912 data
.mode
= MODE_List
;
1913 else if( strcmp(z
,"-line")==0 )
1914 data
.mode
= MODE_Line
;
1915 else if( strcmp(z
,"-column")==0 )
1916 data
.mode
= MODE_Column
;
1917 else if( strcmp(z
,"-separator")==0 )
1920 sprintf(data
.separator
,"%.*s",(int)sizeof(data
.separator
)-1,
1923 else if( strcmp(z
,"-nullvalue")==0 )
1926 sprintf(data
.nullvalue
,"%.*s",(int)sizeof(data
.nullvalue
)-1,
1929 else if( strcmp(z
,"-header")==0 )
1930 data
.showHeader
= TRUE
;
1931 else if( strcmp(z
,"-noheader")==0 )
1932 data
.showHeader
= FALSE
;
1933 else if( strcmp(z
,"-echo")==0 )
1935 else if( strcmp(z
,"-version")==0 )
1937 printf("%s\n", sqlite3_libversion());
1940 else if( strcmp(z
,"-help")==0 )
1944 fprintf(stderr
,"%s: unknown option: %s\n", Argv0
, z
);
1945 fprintf(stderr
,"Use -help for a list of options.\n");
1952 /* Run just the command that follows the database name. */
1953 if( zFirstCmd
[0]=='.' )
1955 do_meta_command(zFirstCmd
, &data
);
1962 rc
= sqlite3_exec(data
.db
, zFirstCmd
, callback
, &data
, &zErrMsg
);
1963 if( rc
!=0 && zErrMsg
!=0 )
1965 fprintf(stderr
,"SQL error: %s\n", zErrMsg
);
1972 /* Run commands received from standard input. */
1973 if( isatty(fileno(stdout
)) && isatty(fileno(stdin
)) )
1976 STRPTR zHistory
= NULL
;
1978 "SQLite version %s\n"
1979 "Enter \".help\" for instructions\n",
1980 sqlite3_libversion()
1982 zHome
= find_home_dir();
1983 if( zHome
&& (zHistory
= malloc(strlen(zHome
)+20))!=0 )
1984 sprintf(zHistory
,"%s/.sqlite_history", zHome
);
1985 #if defined(HAVE_READLINE) && HAVE_READLINE==1
1986 if( zHistory
) read_history(zHistory
);
1988 process_input(&data
, 0);
1991 stifle_history(100);
1992 write_history(zHistory
);
1995 else process_input(&data
, stdin
);
1997 set_table_name(&data
, 0);
1998 if( db
) sqlite3_close(db
);