interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / misc / dbdump.c

754 lines · 22904 bytes Raw Blame History
1/*
2** 2016-03-13
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
13** This file implements a C-language subroutine that converts the content
14** of an SQLite database into UTF-8 text SQL statements that can be used
15** to exactly recreate the original database. ROWID values are preserved.
16**
17** A prototype of the implemented subroutine is this:
18**
19** int sqlite3_db_dump(
20** sqlite3 *db,
21** const char *zSchema,
22** const char *zTable,
23** void (*xCallback)(void*, const char*),
24** void *pArg
25** );
26**
27** The db parameter is the database connection. zSchema is the schema within
28** that database which is to be dumped. Usually the zSchema is "main" but
29** can also be "temp" or any ATTACH-ed database. If zTable is not NULL, then
30** only the content of that one table is dumped. If zTable is NULL, then all
31** tables are dumped.
32**
33** The generate text is passed to xCallback() in multiple calls. The second
34** argument to xCallback() is a copy of the pArg parameter. The first
35** argument is some of the output text that this routine generates. The
36** signature to xCallback() is designed to make it compatible with fputs().
37**
38** The sqlite3_db_dump() subroutine returns SQLITE_OK on success or some error
39** code if it encounters a problem.
40**
41** If this file is compiled with -DDBDUMP_STANDALONE then a "main()" routine
42** is included so that this routine becomes a command-line utility. The
43** command-line utility takes two or three arguments which are the name
44** of the database file, the schema, and optionally the table, forming the
45** first three arguments of a single call to the library routine.
46*/
47#include "sqlite3.h"
48#include <stdarg.h>
49#include <string.h>
50#include <ctype.h>
51
52/*
53** The state of the dump process.
54*/
55typedef struct DState DState;
56struct DState {
57 sqlite3 *db; /* The database connection */
58 int nErr; /* Number of errors seen so far */
59 int rc; /* Error code */
60 int writableSchema; /* True if in writable_schema mode */
61 int (*xCallback)(const char*,void*); /* Send output here */
62 void *pArg; /* Argument to xCallback() */
63};
64
65/*
66** A variable length string to which one can append text.
67*/
68typedef struct DText DText;
69struct DText {
70 char *z; /* The text */
71 sqlite3_int64 n; /* Number of bytes of content in z[] */
72 sqlite3_int64 nAlloc; /* Number of bytes allocated to z[] */
73};
74
75/*
76** Initialize and destroy a DText object
77*/
78static void initText(DText *p){
79 memset(p, 0, sizeof(*p));
80}
81static void freeText(DText *p){
82 sqlite3_free(p->z);
83 initText(p);
84}
85
86/* zIn is either a pointer to a NULL-terminated string in memory obtained
87** from malloc(), or a NULL pointer. The string pointed to by zAppend is
88** added to zIn, and the result returned in memory obtained from malloc().
89** zIn, if it was not NULL, is freed.
90**
91** If the third argument, quote, is not '\0', then it is used as a
92** quote character for zAppend.
93*/
94static void appendText(DText *p, char const *zAppend, char quote){
95 int len;
96 int i;
97 int nAppend = (int)(strlen(zAppend) & 0x3fffffff);
98
99 len = nAppend+p->n+1;
100 if( quote ){
101 len += 2;
102 for(i=0; i<nAppend; i++){
103 if( zAppend[i]==quote ) len++;
104 }
105 }
106
107 if( p->n+len>=p->nAlloc ){
108 char *zNew;
109 p->nAlloc = p->nAlloc*2 + len + 20;
110 zNew = sqlite3_realloc64(p->z, p->nAlloc);
111 if( zNew==0 ){
112 freeText(p);
113 return;
114 }
115 p->z = zNew;
116 }
117
118 if( quote ){
119 char *zCsr = p->z+p->n;
120 *zCsr++ = quote;
121 for(i=0; i<nAppend; i++){
122 *zCsr++ = zAppend[i];
123 if( zAppend[i]==quote ) *zCsr++ = quote;
124 }
125 *zCsr++ = quote;
126 p->n = (int)(zCsr - p->z);
127 *zCsr = '\0';
128 }else{
129 memcpy(p->z+p->n, zAppend, nAppend);
130 p->n += nAppend;
131 p->z[p->n] = '\0';
132 }
133}
134
135/*
136** Attempt to determine if identifier zName needs to be quoted, either
137** because it contains non-alphanumeric characters, or because it is an
138** SQLite keyword. Be conservative in this estimate: When in doubt assume
139** that quoting is required.
140**
141** Return '"' if quoting is required. Return 0 if no quoting is required.
142*/
143static char quoteChar(const char *zName){
144 int i;
145 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
146 for(i=0; zName[i]; i++){
147 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
148 }
149 return sqlite3_keyword_check(zName, i) ? '"' : 0;
150}
151
152
153/*
154** Release memory previously allocated by tableColumnList().
155*/
156static void freeColumnList(char **azCol){
157 int i;
158 if( azCol==0 ) return;
159 for(i=1; azCol[i]; i++){
160 sqlite3_free(azCol[i]);
161 }
162 /* azCol[0] is a static string */
163 sqlite3_free(azCol);
164}
165
166/*
167** Return a list of pointers to strings which are the names of all
168** columns in table zTab. The memory to hold the names is dynamically
169** allocated and must be released by the caller using a subsequent call
170** to freeColumnList().
171**
172** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
173** value that needs to be preserved, then azCol[0] is filled in with the
174** name of the rowid column.
175**
176** The first regular column in the table is azCol[1]. The list is terminated
177** by an entry with azCol[i]==0.
178*/
179static char **tableColumnList(DState *p, const char *zTab){
180 char **azCol = 0;
181 sqlite3_stmt *pStmt = 0;
182 char *zSql;
183 sqlite3_int64 nCol = 0;
184 sqlite3_int64 nAlloc = 0;
185 int nPK = 0; /* Number of PRIMARY KEY columns seen */
186 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
187 int preserveRowid = 1;
188 int rc;
189
190 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
191 if( zSql==0 ) return 0;
192 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
193 sqlite3_free(zSql);
194 if( rc ) return 0;
195 while( sqlite3_step(pStmt)==SQLITE_ROW ){
196 if( nCol>=nAlloc-2 ){
197 char **azNew;
198 nAlloc = nAlloc*2 + nCol + 10;
199 azNew = sqlite3_realloc64(azCol, nAlloc*sizeof(azCol[0]));
200 if( azNew==0 ) goto col_oom;
201 azCol = azNew;
202 azCol[0] = 0;
203 }
204 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
205 if( azCol[nCol]==0 ) goto col_oom;
206 if( sqlite3_column_int(pStmt, 5) ){
207 nPK++;
208 if( nPK==1
209 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
210 "INTEGER")==0
211 ){
212 isIPK = 1;
213 }else{
214 isIPK = 0;
215 }
216 }
217 }
218 sqlite3_finalize(pStmt);
219 pStmt = 0;
220 if( azCol ) azCol[nCol+1] = 0;
221
222 /* The decision of whether or not a rowid really needs to be preserved
223 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
224 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
225 ** rowids on tables where the rowid is inaccessible because there are other
226 ** columns in the table named "rowid", "_rowid_", and "oid".
227 */
228 if( isIPK ){
229 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
230 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
231 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
232 ** ROWID aliases. To distinguish these cases, check to see if
233 ** there is a "pk" entry in "PRAGMA index_list". There will be
234 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
235 */
236 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
237 " WHERE origin='pk'", zTab);
238 if( zSql==0 ) goto col_oom;
239 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
240 sqlite3_free(zSql);
241 if( rc ){
242 freeColumnList(azCol);
243 return 0;
244 }
245 rc = sqlite3_step(pStmt);
246 sqlite3_finalize(pStmt);
247 pStmt = 0;
248 preserveRowid = rc==SQLITE_ROW;
249 }
250 if( preserveRowid ){
251 /* Only preserve the rowid if we can find a name to use for the
252 ** rowid */
253 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
254 int i, j;
255 for(j=0; j<3; j++){
256 for(i=1; i<=nCol; i++){
257 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
258 }
259 if( i>nCol ){
260 /* At this point, we know that azRowid[j] is not the name of any
261 ** ordinary column in the table. Verify that azRowid[j] is a valid
262 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
263 ** tables will fail this last check */
264 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
265 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
266 break;
267 }
268 }
269 }
270 return azCol;
271
272col_oom:
273 sqlite3_finalize(pStmt);
274 freeColumnList(azCol);
275 p->nErr++;
276 p->rc = SQLITE_NOMEM;
277 return 0;
278}
279
280/*
281** Return a copy of the text z, obtained from sqlite3_malloc(), that is safe
282** to embed inside of a C-style comment in a script of SQL statements and
283** dot-commands. Newlines and other control characters are changed to spaces,
284** and any end-of-comment sequence is broken up. Otherwise, text taken from
285** an untrusted database (for example, a table name in an error message)
286** could terminate the comment and put arbitrary SQL, or a line that begins
287** with "." and so is interpreted as a dot-command, into the output.
288*/
289static char *safeCommentText(const char *z){
290 char *zOut = sqlite3_mprintf("%s", z ? z : "");
291 int i;
292 if( zOut==0 ) return 0;
293 for(i=0; zOut[i]; i++){
294 unsigned char c = (unsigned char)zOut[i];
295 if( c<' ' || c==0x7f ){
296 zOut[i] = ' ';
297 }else if( c=='/' && i>0 && zOut[i-1]=='*' ){
298 zOut[i] = ' ';
299 }
300 }
301 return zOut;
302}
303
304/*
305** Send mprintf-formatted content to the output callback.
306*/
307static void output_formatted(DState *p, const char *zFormat, ...){
308 va_list ap;
309 char *z;
310 va_start(ap, zFormat);
311 z = sqlite3_vmprintf(zFormat, ap);
312 va_end(ap);
313 p->xCallback(z, p->pArg);
314 sqlite3_free(z);
315}
316
317/*
318** Find a string that is not found anywhere in z[]. Return a pointer
319** to that string.
320**
321** Try to use zA and zB first. If both of those are already found in z[]
322** then make up some string and store it in the buffer zBuf.
323*/
324static const char *unused_string(
325 const char *z, /* Result must not appear anywhere in z */
326 const char *zA, const char *zB, /* Try these first */
327 char *zBuf /* Space to store a generated string */
328){
329 unsigned i = 0;
330 if( strstr(z, zA)==0 ) return zA;
331 if( strstr(z, zB)==0 ) return zB;
332 do{
333 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
334 }while( strstr(z,zBuf)!=0 );
335 return zBuf;
336}
337
338/*
339** Output the given string as a quoted string using SQL quoting conventions.
340** Additionallly , escape the "\n" and "\r" characters so that they do not
341** get corrupted by end-of-line translation facilities in some operating
342** systems.
343*/
344static void output_quoted_escaped_string(DState *p, const char *z){
345 int i;
346 char c;
347 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
348 if( c==0 ){
349 output_formatted(p,"'%s'",z);
350 }else{
351 const char *zNL = 0;
352 const char *zCR = 0;
353 int nNL = 0;
354 int nCR = 0;
355 char zBuf1[20], zBuf2[20];
356 for(i=0; z[i]; i++){
357 if( z[i]=='\n' ) nNL++;
358 if( z[i]=='\r' ) nCR++;
359 }
360 if( nNL ){
361 p->xCallback("replace(", p->pArg);
362 zNL = unused_string(z, "\\n", "\\012", zBuf1);
363 }
364 if( nCR ){
365 p->xCallback("replace(", p->pArg);
366 zCR = unused_string(z, "\\r", "\\015", zBuf2);
367 }
368 p->xCallback("'", p->pArg);
369 while( *z ){
370 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
371 if( c=='\'' ) i++;
372 if( i ){
373 output_formatted(p, "%.*s", i, z);
374 z += i;
375 }
376 if( c=='\'' ){
377 p->xCallback("'", p->pArg);
378 continue;
379 }
380 if( c==0 ){
381 break;
382 }
383 z++;
384 if( c=='\n' ){
385 p->xCallback(zNL, p->pArg);
386 continue;
387 }
388 p->xCallback(zCR, p->pArg);
389 }
390 p->xCallback("'", p->pArg);
391 if( nCR ){
392 output_formatted(p, ",'%s',char(13))", zCR);
393 }
394 if( nNL ){
395 output_formatted(p, ",'%s',char(10))", zNL);
396 }
397 }
398}
399
400/*
401** This is an sqlite3_exec callback routine used for dumping the database.
402** Each row received by this callback consists of a table name,
403** the table type ("index" or "table") and SQL to create the table.
404** This routine should print text sufficient to recreate the table.
405*/
406static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
407 int rc;
408 const char *zTable;
409 const char *zType;
410 const char *zSql;
411 DState *p = (DState*)pArg;
412 sqlite3_stmt *pStmt;
413
414 (void)azCol;
415 if( nArg!=3 ) return 1;
416 if( azArg==0 ) return 1;
417 zTable = azArg[0];
418 zType = azArg[1];
419 zSql = azArg[2];
420
421 if( strcmp(zTable, "sqlite_sequence")==0 ){
422 p->xCallback("DELETE FROM sqlite_sequence;\n", p->pArg);
423 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
424 p->xCallback("ANALYZE sqlite_schema;\n", p->pArg);
425 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
426 return 0;
427 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
428 if( !p->writableSchema ){
429 p->xCallback("PRAGMA writable_schema=ON;\n", p->pArg);
430 p->writableSchema = 1;
431 }
432 output_formatted(p,
433 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
434 "VALUES('table','%q','%q',0,'%q');",
435 zTable, zTable, zSql);
436 return 0;
437 }else{
438 if( sqlite3_strglob("CREATE TABLE ['\"]*", zSql)==0 ){
439 p->xCallback("CREATE TABLE IF NOT EXISTS ", p->pArg);
440 p->xCallback(zSql+13, p->pArg);
441 }else{
442 p->xCallback(zSql, p->pArg);
443 }
444 p->xCallback(";\n", p->pArg);
445 }
446
447 if( strcmp(zType, "table")==0 ){
448 DText sSelect;
449 DText sTable;
450 char **azTCol;
451 int i;
452 int nCol;
453
454 azTCol = tableColumnList(p, zTable);
455 if( azTCol==0 ) return 0;
456
457 initText(&sTable);
458 appendText(&sTable, "INSERT INTO ", 0);
459
460 /* Always quote the table name, even if it appears to be pure ascii,
461 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
462 appendText(&sTable, zTable, quoteChar(zTable));
463
464 /* If preserving the rowid, add a column list after the table name.
465 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
466 ** instead of the usual "INSERT INTO tab VALUES(...)".
467 */
468 if( azTCol[0] ){
469 appendText(&sTable, "(", 0);
470 appendText(&sTable, azTCol[0], 0);
471 for(i=1; azTCol[i]; i++){
472 appendText(&sTable, ",", 0);
473 appendText(&sTable, azTCol[i], quoteChar(azTCol[i]));
474 }
475 appendText(&sTable, ")", 0);
476 }
477 appendText(&sTable, " VALUES(", 0);
478
479 /* Build an appropriate SELECT statement */
480 initText(&sSelect);
481 appendText(&sSelect, "SELECT ", 0);
482 if( azTCol[0] ){
483 appendText(&sSelect, azTCol[0], 0);
484 appendText(&sSelect, ",", 0);
485 }
486 for(i=1; azTCol[i]; i++){
487 appendText(&sSelect, azTCol[i], quoteChar(azTCol[i]));
488 if( azTCol[i+1] ){
489 appendText(&sSelect, ",", 0);
490 }
491 }
492 nCol = i;
493 if( azTCol[0]==0 ) nCol--;
494 freeColumnList(azTCol);
495 appendText(&sSelect, " FROM ", 0);
496 appendText(&sSelect, zTable, quoteChar(zTable));
497
498 rc = sqlite3_prepare_v2(p->db, sSelect.z, -1, &pStmt, 0);
499 if( rc!=SQLITE_OK ){
500 p->nErr++;
501 if( p->rc==SQLITE_OK ) p->rc = rc;
502 }else{
503 while( SQLITE_ROW==sqlite3_step(pStmt) ){
504 p->xCallback(sTable.z, p->pArg);
505 for(i=0; i<nCol; i++){
506 if( i ) p->xCallback(",", p->pArg);
507 switch( sqlite3_column_type(pStmt,i) ){
508 case SQLITE_INTEGER: {
509 output_formatted(p, "%lld", sqlite3_column_int64(pStmt,i));
510 break;
511 }
512 case SQLITE_FLOAT: {
513 double r = sqlite3_column_double(pStmt,i);
514 sqlite3_uint64 ur;
515 memcpy(&ur,&r,sizeof(r));
516 if( ur==0x7ff0000000000000LL ){
517 p->xCallback("1e999", p->pArg);
518 }else if( ur==0xfff0000000000000LL ){
519 p->xCallback("-1e999", p->pArg);
520 }else{
521 output_formatted(p, "%!.20g", r);
522 }
523 break;
524 }
525 case SQLITE_NULL: {
526 p->xCallback("NULL", p->pArg);
527 break;
528 }
529 case SQLITE_TEXT: {
530 output_quoted_escaped_string(p,
531 (const char*)sqlite3_column_text(pStmt,i));
532 break;
533 }
534 case SQLITE_BLOB: {
535 int nByte = sqlite3_column_bytes(pStmt,i);
536 unsigned char *a = (unsigned char*)sqlite3_column_blob(pStmt,i);
537 int j;
538 p->xCallback("x'", p->pArg);
539 for(j=0; j<nByte; j++){
540 char zWord[3];
541 zWord[0] = "0123456789abcdef"[(a[j]>>4)&15];
542 zWord[1] = "0123456789abcdef"[a[j]&15];
543 zWord[2] = 0;
544 p->xCallback(zWord, p->pArg);
545 }
546 p->xCallback("'", p->pArg);
547 break;
548 }
549 }
550 }
551 p->xCallback(");\n", p->pArg);
552 }
553 }
554 sqlite3_finalize(pStmt);
555 freeText(&sTable);
556 freeText(&sSelect);
557 }
558 return 0;
559}
560
561
562/*
563** Execute a query statement that will generate SQL output. Print
564** the result columns, comma-separated, on a line and then add a
565** semicolon terminator to the end of that line.
566**
567** If the number of columns is 1 and that column contains text "--"
568** then write the semicolon on a separate line. That way, if a
569** "--" comment occurs at the end of the statement, the comment
570** won't consume the semicolon terminator.
571*/
572static void output_sql_from_query(
573 DState *p, /* Query context */
574 const char *zSelect, /* SELECT statement to extract content */
575 ...
576){
577 sqlite3_stmt *pSelect;
578 int rc;
579 int nResult;
580 int i;
581 const char *z;
582 char *zSql;
583 va_list ap;
584 va_start(ap, zSelect);
585 zSql = sqlite3_vmprintf(zSelect, ap);
586 va_end(ap);
587 if( zSql==0 ){
588 p->rc = SQLITE_NOMEM;
589 p->nErr++;
590 return;
591 }
592 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pSelect, 0);
593 sqlite3_free(zSql);
594 if( rc!=SQLITE_OK || !pSelect ){
595 char *zMsg = safeCommentText(sqlite3_errmsg(p->db));
596 output_formatted(p, "/**** ERROR: (%d) %s *****/\n", rc, zMsg);
597 sqlite3_free(zMsg);
598 p->nErr++;
599 return;
600 }
601 rc = sqlite3_step(pSelect);
602 nResult = sqlite3_column_count(pSelect);
603 while( rc==SQLITE_ROW ){
604 z = (const char*)sqlite3_column_text(pSelect, 0);
605 p->xCallback(z, p->pArg);
606 for(i=1; i<nResult; i++){
607 p->xCallback(",", p->pArg);
608 p->xCallback((const char*)sqlite3_column_text(pSelect,i), p->pArg);
609 }
610 if( z==0 ) z = "";
611 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
612 if( z[0] ){
613 p->xCallback("\n;\n", p->pArg);
614 }else{
615 p->xCallback(";\n", p->pArg);
616 }
617 rc = sqlite3_step(pSelect);
618 }
619 rc = sqlite3_finalize(pSelect);
620 if( rc!=SQLITE_OK ){
621 char *zMsg = safeCommentText(sqlite3_errmsg(p->db));
622 output_formatted(p, "/**** ERROR: (%d) %s *****/\n", rc, zMsg);
623 sqlite3_free(zMsg);
624 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
625 }
626}
627
628/*
629** Run zQuery. Use dump_callback() as the callback routine so that
630** the contents of the query are output as SQL statements.
631**
632** If we get a SQLITE_CORRUPT error, rerun the query after appending
633** "ORDER BY rowid DESC" to the end.
634*/
635static void run_schema_dump_query(
636 DState *p,
637 const char *zQuery,
638 ...
639){
640 char *zErr = 0;
641 char *z;
642 va_list ap;
643 va_start(ap, zQuery);
644 z = sqlite3_vmprintf(zQuery, ap);
645 va_end(ap);
646 sqlite3_exec(p->db, z, dump_callback, p, &zErr);
647 sqlite3_free(z);
648 if( zErr ){
649 char *zMsg = safeCommentText(zErr);
650 output_formatted(p, "/****** %s ******/\n", zMsg);
651 sqlite3_free(zMsg);
652 sqlite3_free(zErr);
653 p->nErr++;
654 zErr = 0;
655 }
656}
657
658/*
659** Convert an SQLite database into SQL statements that will recreate that
660** database.
661*/
662int sqlite3_db_dump(
663 sqlite3 *db, /* The database connection */
664 const char *zSchema, /* Which schema to dump. Usually "main". */
665 const char *zTable, /* Which table to dump. NULL means everything. */
666 int (*xCallback)(const char*,void*), /* Output sent to this callback */
667 void *pArg /* Second argument of the callback */
668){
669 DState x;
670 memset(&x, 0, sizeof(x));
671 x.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
672 if( x.rc ) return x.rc;
673 x.db = db;
674 x.xCallback = xCallback;
675 x.pArg = pArg;
676 xCallback("PRAGMA foreign_keys=OFF;\nBEGIN TRANSACTION;\n", pArg);
677 if( zTable==0 ){
678 run_schema_dump_query(&x,
679 "SELECT name, type, sql FROM \"%w\".sqlite_schema "
680 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'",
681 zSchema
682 );
683 run_schema_dump_query(&x,
684 "SELECT name, type, sql FROM \"%w\".sqlite_schema "
685 "WHERE name=='sqlite_sequence'", zSchema
686 );
687 output_sql_from_query(&x,
688 "SELECT sql FROM sqlite_schema "
689 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
690 );
691 }else{
692 run_schema_dump_query(&x,
693 "SELECT name, type, sql FROM \"%w\".sqlite_schema "
694 "WHERE tbl_name=%Q COLLATE nocase AND type=='table'"
695 " AND sql NOT NULL",
696 zSchema, zTable
697 );
698 output_sql_from_query(&x,
699 "SELECT sql FROM \"%w\".sqlite_schema "
700 "WHERE sql NOT NULL"
701 " AND type IN ('index','trigger','view')"
702 " AND tbl_name=%Q COLLATE nocase",
703 zSchema, zTable
704 );
705 }
706 if( x.writableSchema ){
707 xCallback("PRAGMA writable_schema=OFF;\n", pArg);
708 }
709 xCallback(x.nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n", pArg);
710 sqlite3_exec(db, "COMMIT", 0, 0, 0);
711 return x.rc;
712}
713
714
715
716/* The generic subroutine is above. The code the follows implements
717** the command-line interface.
718*/
719#ifdef DBDUMP_STANDALONE
720#include <stdio.h>
721
722/*
723** Command-line interface
724*/
725int main(int argc, char **argv){
726 sqlite3 *db;
727 const char *zDb;
728 const char *zSchema;
729 const char *zTable = 0;
730 int rc;
731
732 if( argc<2 || argc>4 ){
733 fprintf(stderr, "Usage: %s DATABASE ?SCHEMA? ?TABLE?\n", argv[0]);
734 return 1;
735 }
736 zDb = argv[1];
737 zSchema = argc>=3 ? argv[2] : "main";
738 zTable = argc==4 ? argv[3] : 0;
739
740 rc = sqlite3_open(zDb, &db);
741 if( rc ){
742 fprintf(stderr, "Cannot open \"%s\": %s\n", zDb, sqlite3_errmsg(db));
743 sqlite3_close(db);
744 return 1;
745 }
746 rc = sqlite3_db_dump(db, zSchema, zTable,
747 (int(*)(const char*,void*))fputs, (void*)stdout);
748 if( rc ){
749 fprintf(stderr, "Error: sqlite3_db_dump() returns %d\n", rc);
750 }
751 sqlite3_close(db);
752 return rc!=SQLITE_OK;
753}
754#endif /* DBDUMP_STANDALONE */