Merge trunk into jni-post-3.44 branch.
[sqlite.git] / tool / sqldiff.c
bloba612566112133ad91caaec207512038a1d0c4285
1 /*
2 ** 2015-04-06
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.
11 *************************************************************************
13 ** This is a utility program that computes the differences in content
14 ** between two SQLite databases.
16 ** To compile, simply link against SQLite.
18 ** See the showHelp() routine below for a brief description of how to
19 ** run the utility.
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <stdarg.h>
24 #include <ctype.h>
25 #include <string.h>
26 #include <assert.h>
27 #include "sqlite3.h"
30 ** All global variables are gathered into the "g" singleton.
32 struct GlobalVars {
33 const char *zArgv0; /* Name of program */
34 int bSchemaOnly; /* Only show schema differences */
35 int bSchemaPK; /* Use the schema-defined PK, not the true PK */
36 int bHandleVtab; /* Handle fts3, fts4, fts5 and rtree vtabs */
37 unsigned fDebug; /* Debug flags */
38 int bSchemaCompare; /* Doing single-table sqlite_schema compare */
39 sqlite3 *db; /* The database connection */
40 } g;
43 ** Allowed values for g.fDebug
45 #define DEBUG_COLUMN_NAMES 0x000001
46 #define DEBUG_DIFF_SQL 0x000002
49 ** Dynamic string object
51 typedef struct Str Str;
52 struct Str {
53 char *z; /* Text of the string */
54 int nAlloc; /* Bytes allocated in z[] */
55 int nUsed; /* Bytes actually used in z[] */
59 ** Initialize a Str object
61 static void strInit(Str *p){
62 p->z = 0;
63 p->nAlloc = 0;
64 p->nUsed = 0;
68 ** Print an error resulting from faulting command-line arguments and
69 ** abort the program.
71 static void cmdlineError(const char *zFormat, ...){
72 va_list ap;
73 fprintf(stderr, "%s: ", g.zArgv0);
74 va_start(ap, zFormat);
75 vfprintf(stderr, zFormat, ap);
76 va_end(ap);
77 fprintf(stderr, "\n\"%s --help\" for more help\n", g.zArgv0);
78 exit(1);
82 ** Print an error message for an error that occurs at runtime, then
83 ** abort the program.
85 static void runtimeError(const char *zFormat, ...){
86 va_list ap;
87 fprintf(stderr, "%s: ", g.zArgv0);
88 va_start(ap, zFormat);
89 vfprintf(stderr, zFormat, ap);
90 va_end(ap);
91 fprintf(stderr, "\n");
92 exit(1);
96 ** Free all memory held by a Str object
98 static void strFree(Str *p){
99 sqlite3_free(p->z);
100 strInit(p);
104 ** Add formatted text to the end of a Str object
106 static void strPrintf(Str *p, const char *zFormat, ...){
107 int nNew;
108 for(;;){
109 if( p->z ){
110 va_list ap;
111 va_start(ap, zFormat);
112 sqlite3_vsnprintf(p->nAlloc-p->nUsed, p->z+p->nUsed, zFormat, ap);
113 va_end(ap);
114 nNew = (int)strlen(p->z + p->nUsed);
115 }else{
116 nNew = p->nAlloc;
118 if( p->nUsed+nNew < p->nAlloc-1 ){
119 p->nUsed += nNew;
120 break;
122 p->nAlloc = p->nAlloc*2 + 1000;
123 p->z = sqlite3_realloc(p->z, p->nAlloc);
124 if( p->z==0 ) runtimeError("out of memory");
130 /* Safely quote an SQL identifier. Use the minimum amount of transformation
131 ** necessary to allow the string to be used with %s.
133 ** Space to hold the returned string is obtained from sqlite3_malloc(). The
134 ** caller is responsible for ensuring this space is freed when no longer
135 ** needed.
137 static char *safeId(const char *zId){
138 int i, x;
139 char c;
140 if( zId[0]==0 ) return sqlite3_mprintf("\"\"");
141 for(i=x=0; (c = zId[i])!=0; i++){
142 if( !isalpha(c) && c!='_' ){
143 if( i>0 && isdigit(c) ){
144 x++;
145 }else{
146 return sqlite3_mprintf("\"%w\"", zId);
150 if( x || !sqlite3_keyword_check(zId,i) ){
151 return sqlite3_mprintf("%s", zId);
153 return sqlite3_mprintf("\"%w\"", zId);
157 ** Prepare a new SQL statement. Print an error and abort if anything
158 ** goes wrong.
160 static sqlite3_stmt *db_vprepare(const char *zFormat, va_list ap){
161 char *zSql;
162 int rc;
163 sqlite3_stmt *pStmt;
165 zSql = sqlite3_vmprintf(zFormat, ap);
166 if( zSql==0 ) runtimeError("out of memory");
167 rc = sqlite3_prepare_v2(g.db, zSql, -1, &pStmt, 0);
168 if( rc ){
169 runtimeError("SQL statement error: %s\n\"%s\"", sqlite3_errmsg(g.db),
170 zSql);
172 sqlite3_free(zSql);
173 return pStmt;
175 static sqlite3_stmt *db_prepare(const char *zFormat, ...){
176 va_list ap;
177 sqlite3_stmt *pStmt;
178 va_start(ap, zFormat);
179 pStmt = db_vprepare(zFormat, ap);
180 va_end(ap);
181 return pStmt;
185 ** Free a list of strings
187 static void namelistFree(char **az){
188 if( az ){
189 int i;
190 for(i=0; az[i]; i++) sqlite3_free(az[i]);
191 sqlite3_free(az);
196 ** Return a list of column names [a] for the table zDb.zTab. Space to
197 ** hold the list is obtained from sqlite3_malloc() and should released
198 ** using namelistFree() when no longer needed.
200 ** Primary key columns are listed first, followed by data columns.
201 ** The number of columns in the primary key is returned in *pnPkey.
203 ** Normally [a], the "primary key" in the previous sentence is the true
204 ** primary key - the rowid or INTEGER PRIMARY KEY for ordinary tables
205 ** or the declared PRIMARY KEY for WITHOUT ROWID tables. However, if
206 ** the g.bSchemaPK flag is set, then the schema-defined PRIMARY KEY is
207 ** used in all cases. In that case, entries that have NULL values in
208 ** any of their primary key fields will be excluded from the analysis.
210 ** If the primary key for a table is the rowid but rowid is inaccessible,
211 ** then this routine returns a NULL pointer.
213 ** [a. If the lone, named table is "sqlite_schema", "rootpage" column is
214 ** omitted and the "type" and "name" columns are made to be the PK.]
216 ** Examples:
217 ** CREATE TABLE t1(a INT UNIQUE, b INTEGER, c TEXT, PRIMARY KEY(c));
218 ** *pnPKey = 1;
219 ** az = { "rowid", "a", "b", "c", 0 } // Normal case
220 ** az = { "c", "a", "b", 0 } // g.bSchemaPK==1
222 ** CREATE TABLE t2(a INT UNIQUE, b INTEGER, c TEXT, PRIMARY KEY(b));
223 ** *pnPKey = 1;
224 ** az = { "b", "a", "c", 0 }
226 ** CREATE TABLE t3(x,y,z,PRIMARY KEY(y,z));
227 ** *pnPKey = 1 // Normal case
228 ** az = { "rowid", "x", "y", "z", 0 } // Normal case
229 ** *pnPKey = 2 // g.bSchemaPK==1
230 ** az = { "y", "x", "z", 0 } // g.bSchemaPK==1
232 ** CREATE TABLE t4(x,y,z,PRIMARY KEY(y,z)) WITHOUT ROWID;
233 ** *pnPKey = 2
234 ** az = { "y", "z", "x", 0 }
236 ** CREATE TABLE t5(rowid,_rowid_,oid);
237 ** az = 0 // The rowid is not accessible
239 static char **columnNames(
240 const char *zDb, /* Database ("main" or "aux") to query */
241 const char *zTab, /* Name of table to return details of */
242 int *pnPKey, /* OUT: Number of PK columns */
243 int *pbRowid /* OUT: True if PK is an implicit rowid */
245 char **az = 0; /* List of column names to be returned */
246 int naz = 0; /* Number of entries in az[] */
247 sqlite3_stmt *pStmt; /* SQL statement being run */
248 char *zPkIdxName = 0; /* Name of the PRIMARY KEY index */
249 int truePk = 0; /* PRAGMA table_info indentifies the PK to use */
250 int nPK = 0; /* Number of PRIMARY KEY columns */
251 int i, j; /* Loop counters */
253 if( g.bSchemaPK==0 ){
254 /* Normal case: Figure out what the true primary key is for the table.
255 ** * For WITHOUT ROWID tables, the true primary key is the same as
256 ** the schema PRIMARY KEY, which is guaranteed to be present.
257 ** * For rowid tables with an INTEGER PRIMARY KEY, the true primary
258 ** key is the INTEGER PRIMARY KEY.
259 ** * For all other rowid tables, the rowid is the true primary key.
261 pStmt = db_prepare("PRAGMA %s.index_list=%Q", zDb, zTab);
262 while( SQLITE_ROW==sqlite3_step(pStmt) ){
263 if( sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,3),"pk")==0 ){
264 zPkIdxName = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
265 break;
268 sqlite3_finalize(pStmt);
269 if( zPkIdxName ){
270 int nKey = 0;
271 int nCol = 0;
272 truePk = 0;
273 pStmt = db_prepare("PRAGMA %s.index_xinfo=%Q", zDb, zPkIdxName);
274 while( SQLITE_ROW==sqlite3_step(pStmt) ){
275 nCol++;
276 if( sqlite3_column_int(pStmt,5) ){ nKey++; continue; }
277 if( sqlite3_column_int(pStmt,1)>=0 ) truePk = 1;
279 if( nCol==nKey ) truePk = 1;
280 if( truePk ){
281 nPK = nKey;
282 }else{
283 nPK = 1;
285 sqlite3_finalize(pStmt);
286 sqlite3_free(zPkIdxName);
287 }else{
288 truePk = 1;
289 nPK = 1;
291 pStmt = db_prepare("PRAGMA %s.table_info=%Q", zDb, zTab);
292 }else{
293 /* The g.bSchemaPK==1 case: Use whatever primary key is declared
294 ** in the schema. The "rowid" will still be used as the primary key
295 ** if the table definition does not contain a PRIMARY KEY.
297 nPK = 0;
298 pStmt = db_prepare("PRAGMA %s.table_info=%Q", zDb, zTab);
299 while( SQLITE_ROW==sqlite3_step(pStmt) ){
300 if( sqlite3_column_int(pStmt,5)>0 ) nPK++;
302 sqlite3_reset(pStmt);
303 if( nPK==0 ) nPK = 1;
304 truePk = 1;
306 if( g.bSchemaCompare ){
307 assert( sqlite3_stricmp(zTab,"sqlite_schema")==0
308 || sqlite3_stricmp(zTab,"sqlite_master")==0 );
309 /* For sqlite_schema, will use type and name as the PK. */
310 nPK = 2;
311 truePk = 0;
313 *pnPKey = nPK;
314 naz = nPK;
315 az = sqlite3_malloc( sizeof(char*)*(nPK+1) );
316 if( az==0 ) runtimeError("out of memory");
317 memset(az, 0, sizeof(char*)*(nPK+1));
318 if( g.bSchemaCompare ){
319 az[0] = sqlite3_mprintf("%s", "type");
320 az[1] = sqlite3_mprintf("%s", "name");
322 while( SQLITE_ROW==sqlite3_step(pStmt) ){
323 char * sid = safeId((char*)sqlite3_column_text(pStmt,1));
324 int iPKey;
325 if( truePk && (iPKey = sqlite3_column_int(pStmt,5))>0 ){
326 az[iPKey-1] = sid;
327 }else{
328 if( !g.bSchemaCompare
329 || !(strcmp(sid,"rootpage")==0
330 ||strcmp(sid,"name")==0
331 ||strcmp(sid,"type")==0)){
332 az = sqlite3_realloc(az, sizeof(char*)*(naz+2) );
333 if( az==0 ) runtimeError("out of memory");
334 az[naz++] = sid;
338 sqlite3_finalize(pStmt);
339 if( az ) az[naz] = 0;
341 /* If it is non-NULL, set *pbRowid to indicate whether or not the PK of
342 ** this table is an implicit rowid (*pbRowid==1) or not (*pbRowid==0). */
343 if( pbRowid ) *pbRowid = (az[0]==0);
345 /* If this table has an implicit rowid for a PK, figure out how to refer
346 ** to it. There are usually three options - "rowid", "_rowid_" and "oid".
347 ** Any of these will work, unless the table has an explicit column of the
348 ** same name or the sqlite_schema tables are to be compared. In the latter
349 ** case, pretend that the "true" primary key is the name column, which
350 ** avoids extraneous diffs against the schemas due to rowid variance. */
351 if( az[0]==0 ){
352 const char *azRowid[] = { "rowid", "_rowid_", "oid" };
353 for(i=0; i<sizeof(azRowid)/sizeof(azRowid[0]); i++){
354 for(j=1; j<naz; j++){
355 if( sqlite3_stricmp(az[j], azRowid[i])==0 ) break;
357 if( j>=naz ){
358 az[0] = sqlite3_mprintf("%s", azRowid[i]);
359 break;
362 if( az[0]==0 ){
363 for(i=1; i<naz; i++) sqlite3_free(az[i]);
364 sqlite3_free(az);
365 az = 0;
368 return az;
372 ** Print the sqlite3_value X as an SQL literal.
374 static void printQuoted(FILE *out, sqlite3_value *X){
375 switch( sqlite3_value_type(X) ){
376 case SQLITE_FLOAT: {
377 double r1;
378 char zBuf[50];
379 r1 = sqlite3_value_double(X);
380 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
381 fprintf(out, "%s", zBuf);
382 break;
384 case SQLITE_INTEGER: {
385 fprintf(out, "%lld", sqlite3_value_int64(X));
386 break;
388 case SQLITE_BLOB: {
389 const unsigned char *zBlob = sqlite3_value_blob(X);
390 int nBlob = sqlite3_value_bytes(X);
391 if( zBlob ){
392 int i;
393 fprintf(out, "x'");
394 for(i=0; i<nBlob; i++){
395 fprintf(out, "%02x", zBlob[i]);
397 fprintf(out, "'");
398 }else{
399 /* Could be an OOM, could be a zero-byte blob */
400 fprintf(out, "X''");
402 break;
404 case SQLITE_TEXT: {
405 const unsigned char *zArg = sqlite3_value_text(X);
407 if( zArg==0 ){
408 fprintf(out, "NULL");
409 }else{
410 int inctl = 0;
411 int i, j;
412 fprintf(out, "'");
413 for(i=j=0; zArg[i]; i++){
414 char c = zArg[i];
415 int ctl = iscntrl(c);
416 if( ctl>inctl ){
417 inctl = ctl;
418 fprintf(out, "%.*s'||X'%02x", i-j, &zArg[j], c);
419 j = i+1;
420 }else if( ctl ){
421 fprintf(out, "%02x", c);
422 j = i+1;
423 }else{
424 if( inctl ){
425 inctl = 0;
426 fprintf(out, "'\n||'");
428 if( c=='\'' ){
429 fprintf(out, "%.*s'", i-j+1, &zArg[j]);
430 j = i+1;
434 fprintf(out, "%s'", &zArg[j]);
436 break;
438 case SQLITE_NULL: {
439 fprintf(out, "NULL");
440 break;
446 ** Output SQL that will recreate the aux.zTab table.
448 static void dump_table(const char *zTab, FILE *out){
449 char *zId = safeId(zTab); /* Name of the table */
450 char **az = 0; /* List of columns */
451 int nPk; /* Number of true primary key columns */
452 int nCol; /* Number of data columns */
453 int i; /* Loop counter */
454 sqlite3_stmt *pStmt; /* SQL statement */
455 const char *zSep; /* Separator string */
456 Str ins; /* Beginning of the INSERT statement */
458 pStmt = db_prepare("SELECT sql FROM aux.sqlite_schema WHERE name=%Q", zTab);
459 if( SQLITE_ROW==sqlite3_step(pStmt) ){
460 fprintf(out, "%s;\n", sqlite3_column_text(pStmt,0));
462 sqlite3_finalize(pStmt);
463 if( !g.bSchemaOnly ){
464 az = columnNames("aux", zTab, &nPk, 0);
465 strInit(&ins);
466 if( az==0 ){
467 pStmt = db_prepare("SELECT * FROM aux.%s", zId);
468 strPrintf(&ins,"INSERT INTO %s VALUES", zId);
469 }else{
470 Str sql;
471 strInit(&sql);
472 zSep = "SELECT";
473 for(i=0; az[i]; i++){
474 strPrintf(&sql, "%s %s", zSep, az[i]);
475 zSep = ",";
477 strPrintf(&sql," FROM aux.%s", zId);
478 zSep = " ORDER BY";
479 for(i=1; i<=nPk; i++){
480 strPrintf(&sql, "%s %d", zSep, i);
481 zSep = ",";
483 pStmt = db_prepare("%s", sql.z);
484 strFree(&sql);
485 strPrintf(&ins, "INSERT INTO %s", zId);
486 zSep = "(";
487 for(i=0; az[i]; i++){
488 strPrintf(&ins, "%s%s", zSep, az[i]);
489 zSep = ",";
491 strPrintf(&ins,") VALUES");
492 namelistFree(az);
494 nCol = sqlite3_column_count(pStmt);
495 while( SQLITE_ROW==sqlite3_step(pStmt) ){
496 fprintf(out, "%s",ins.z);
497 zSep = "(";
498 for(i=0; i<nCol; i++){
499 fprintf(out, "%s",zSep);
500 printQuoted(out, sqlite3_column_value(pStmt,i));
501 zSep = ",";
503 fprintf(out, ");\n");
505 sqlite3_finalize(pStmt);
506 strFree(&ins);
507 } /* endif !g.bSchemaOnly */
508 pStmt = db_prepare("SELECT sql FROM aux.sqlite_schema"
509 " WHERE type='index' AND tbl_name=%Q AND sql IS NOT NULL",
510 zTab);
511 while( SQLITE_ROW==sqlite3_step(pStmt) ){
512 fprintf(out, "%s;\n", sqlite3_column_text(pStmt,0));
514 sqlite3_finalize(pStmt);
515 sqlite3_free(zId);
520 ** Compute all differences for a single table, except if the
521 ** table name is sqlite_schema, ignore the rootpage column.
523 static void diff_one_table(const char *zTab, FILE *out){
524 char *zId = safeId(zTab); /* Name of table (translated for us in SQL) */
525 char **az = 0; /* Columns in main */
526 char **az2 = 0; /* Columns in aux */
527 int nPk; /* Primary key columns in main */
528 int nPk2; /* Primary key columns in aux */
529 int n = 0; /* Number of columns in main */
530 int n2; /* Number of columns in aux */
531 int nQ; /* Number of output columns in the diff query */
532 int i; /* Loop counter */
533 const char *zSep; /* Separator string */
534 Str sql; /* Comparison query */
535 sqlite3_stmt *pStmt; /* Query statement to do the diff */
536 const char *zLead = /* Becomes line-comment for sqlite_schema */
537 (g.bSchemaCompare)? "-- " : "";
539 strInit(&sql);
540 if( g.fDebug==DEBUG_COLUMN_NAMES ){
541 /* Simply run columnNames() on all tables of the origin
542 ** database and show the results. This is used for testing
543 ** and debugging of the columnNames() function.
545 az = columnNames("aux",zTab, &nPk, 0);
546 if( az==0 ){
547 printf("Rowid not accessible for %s\n", zId);
548 }else{
549 printf("%s:", zId);
550 for(i=0; az[i]; i++){
551 printf(" %s", az[i]);
552 if( i+1==nPk ) printf(" *");
554 printf("\n");
556 goto end_diff_one_table;
559 if( sqlite3_table_column_metadata(g.db,"aux",zTab,0,0,0,0,0,0) ){
560 if( !sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
561 /* Table missing from second database. */
562 if( g.bSchemaCompare )
563 fprintf(out, "-- 2nd DB has no %s table\n", zTab);
564 else
565 fprintf(out, "DROP TABLE %s;\n", zId);
567 goto end_diff_one_table;
570 if( sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
571 /* Table missing from source */
572 if( g.bSchemaCompare )
573 fprintf(out, "-- 1st DB has no %s table\n", zTab);
574 else
575 dump_table(zTab, out);
576 goto end_diff_one_table;
579 az = columnNames("main", zTab, &nPk, 0);
580 az2 = columnNames("aux", zTab, &nPk2, 0);
581 if( az && az2 ){
582 for(n=0; az[n] && az2[n]; n++){
583 if( sqlite3_stricmp(az[n],az2[n])!=0 ) break;
586 if( az==0
587 || az2==0
588 || nPk!=nPk2
589 || az[n]
591 /* Schema mismatch */
592 fprintf(out, "%sDROP TABLE %s; -- due to schema mismatch\n", zLead, zId);
593 dump_table(zTab, out);
594 goto end_diff_one_table;
597 /* Build the comparison query */
598 for(n2=n; az2[n2]; n2++){
599 char *zNTab = safeId(az2[n2]);
600 fprintf(out, "ALTER TABLE %s ADD COLUMN %s;\n", zId, zNTab);
601 sqlite3_free(zNTab);
603 nQ = nPk2+1+2*(n2-nPk2);
604 if( n2>nPk2 ){
605 zSep = "SELECT ";
606 for(i=0; i<nPk; i++){
607 strPrintf(&sql, "%sB.%s", zSep, az[i]);
608 zSep = ", ";
610 strPrintf(&sql, ", 1 /* changed row */");
611 while( az[i] ){
612 strPrintf(&sql, ", A.%s IS NOT B.%s, B.%s",
613 az[i], az2[i], az2[i]);
614 i++;
616 while( az2[i] ){
617 strPrintf(&sql, ", B.%s IS NOT NULL, B.%s",
618 az2[i], az2[i]);
619 i++;
621 strPrintf(&sql, "\n FROM main.%s A, aux.%s B\n", zId, zId);
622 zSep = " WHERE";
623 for(i=0; i<nPk; i++){
624 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
625 zSep = " AND";
627 zSep = "\n AND (";
628 while( az[i] ){
629 strPrintf(&sql, "%sA.%s IS NOT B.%s%s\n",
630 zSep, az[i], az2[i], az2[i+1]==0 ? ")" : "");
631 zSep = " OR ";
632 i++;
634 while( az2[i] ){
635 strPrintf(&sql, "%sB.%s IS NOT NULL%s\n",
636 zSep, az2[i], az2[i+1]==0 ? ")" : "");
637 zSep = " OR ";
638 i++;
640 strPrintf(&sql, " UNION ALL\n");
642 zSep = "SELECT ";
643 for(i=0; i<nPk; i++){
644 strPrintf(&sql, "%sA.%s", zSep, az[i]);
645 zSep = ", ";
647 strPrintf(&sql, ", 2 /* deleted row */");
648 while( az2[i] ){
649 strPrintf(&sql, ", NULL, NULL");
650 i++;
652 strPrintf(&sql, "\n FROM main.%s A\n", zId);
653 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B\n", zId);
654 zSep = " WHERE";
655 for(i=0; i<nPk; i++){
656 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
657 zSep = " AND";
659 strPrintf(&sql, ")\n");
660 zSep = " UNION ALL\nSELECT ";
661 for(i=0; i<nPk; i++){
662 strPrintf(&sql, "%sB.%s", zSep, az[i]);
663 zSep = ", ";
665 strPrintf(&sql, ", 3 /* inserted row */");
666 while( az2[i] ){
667 strPrintf(&sql, ", 1, B.%s", az2[i]);
668 i++;
670 strPrintf(&sql, "\n FROM aux.%s B\n", zId);
671 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A\n", zId);
672 zSep = " WHERE";
673 for(i=0; i<nPk; i++){
674 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
675 zSep = " AND";
677 strPrintf(&sql, ")\n ORDER BY");
678 zSep = " ";
679 for(i=1; i<=nPk; i++){
680 strPrintf(&sql, "%s%d", zSep, i);
681 zSep = ", ";
683 strPrintf(&sql, ";\n");
685 if( g.fDebug & DEBUG_DIFF_SQL ){
686 printf("SQL for %s:\n%s\n", zId, sql.z);
687 goto end_diff_one_table;
690 /* Drop indexes that are missing in the destination */
691 pStmt = db_prepare(
692 "SELECT name FROM main.sqlite_schema"
693 " WHERE type='index' AND tbl_name=%Q"
694 " AND sql IS NOT NULL"
695 " AND sql NOT IN (SELECT sql FROM aux.sqlite_schema"
696 " WHERE type='index' AND tbl_name=%Q"
697 " AND sql IS NOT NULL)",
698 zTab, zTab);
699 while( SQLITE_ROW==sqlite3_step(pStmt) ){
700 char *z = safeId((const char*)sqlite3_column_text(pStmt,0));
701 fprintf(out, "DROP INDEX %s;\n", z);
702 sqlite3_free(z);
704 sqlite3_finalize(pStmt);
706 /* Run the query and output differences */
707 if( !g.bSchemaOnly ){
708 pStmt = db_prepare("%s", sql.z);
709 while( SQLITE_ROW==sqlite3_step(pStmt) ){
710 int iType = sqlite3_column_int(pStmt, nPk);
711 if( iType==1 || iType==2 ){
712 if( iType==1 ){ /* Change the content of a row */
713 fprintf(out, "%sUPDATE %s", zLead, zId);
714 zSep = " SET";
715 for(i=nPk+1; i<nQ; i+=2){
716 if( sqlite3_column_int(pStmt,i)==0 ) continue;
717 fprintf(out, "%s %s=", zSep, az2[(i+nPk-1)/2]);
718 zSep = ",";
719 printQuoted(out, sqlite3_column_value(pStmt,i+1));
721 }else{ /* Delete a row */
722 fprintf(out, "%sDELETE FROM %s", zLead, zId);
724 zSep = " WHERE";
725 for(i=0; i<nPk; i++){
726 fprintf(out, "%s %s=", zSep, az2[i]);
727 printQuoted(out, sqlite3_column_value(pStmt,i));
728 zSep = " AND";
730 fprintf(out, ";\n");
731 }else{ /* Insert a row */
732 fprintf(out, "%sINSERT INTO %s(%s", zLead, zId, az2[0]);
733 for(i=1; az2[i]; i++) fprintf(out, ",%s", az2[i]);
734 fprintf(out, ") VALUES");
735 zSep = "(";
736 for(i=0; i<nPk2; i++){
737 fprintf(out, "%s", zSep);
738 zSep = ",";
739 printQuoted(out, sqlite3_column_value(pStmt,i));
741 for(i=nPk2+2; i<nQ; i+=2){
742 fprintf(out, ",");
743 printQuoted(out, sqlite3_column_value(pStmt,i));
745 fprintf(out, ");\n");
748 sqlite3_finalize(pStmt);
749 } /* endif !g.bSchemaOnly */
751 /* Create indexes that are missing in the source */
752 pStmt = db_prepare(
753 "SELECT sql FROM aux.sqlite_schema"
754 " WHERE type='index' AND tbl_name=%Q"
755 " AND sql IS NOT NULL"
756 " AND sql NOT IN (SELECT sql FROM main.sqlite_schema"
757 " WHERE type='index' AND tbl_name=%Q"
758 " AND sql IS NOT NULL)",
759 zTab, zTab);
760 while( SQLITE_ROW==sqlite3_step(pStmt) ){
761 fprintf(out, "%s;\n", sqlite3_column_text(pStmt,0));
763 sqlite3_finalize(pStmt);
765 end_diff_one_table:
766 strFree(&sql);
767 sqlite3_free(zId);
768 namelistFree(az);
769 namelistFree(az2);
770 return;
774 ** Check that table zTab exists and has the same schema in both the "main"
775 ** and "aux" databases currently opened by the global db handle. If they
776 ** do not, output an error message on stderr and exit(1). Otherwise, if
777 ** the schemas do match, return control to the caller.
779 static void checkSchemasMatch(const char *zTab){
780 sqlite3_stmt *pStmt = db_prepare(
781 "SELECT A.sql=B.sql FROM main.sqlite_schema A, aux.sqlite_schema B"
782 " WHERE A.name=%Q AND B.name=%Q", zTab, zTab
784 if( SQLITE_ROW==sqlite3_step(pStmt) ){
785 if( sqlite3_column_int(pStmt,0)==0 ){
786 runtimeError("schema changes for table %s", safeId(zTab));
788 }else{
789 runtimeError("table %s missing from one or both databases", safeId(zTab));
791 sqlite3_finalize(pStmt);
794 /**************************************************************************
795 ** The following code is copied from fossil. It is used to generate the
796 ** fossil delta blobs sometimes used in RBU update records.
799 typedef unsigned short u16;
800 typedef unsigned int u32;
801 typedef unsigned char u8;
804 ** The width of a hash window in bytes. The algorithm only works if this
805 ** is a power of 2.
807 #define NHASH 16
810 ** The current state of the rolling hash.
812 ** z[] holds the values that have been hashed. z[] is a circular buffer.
813 ** z[i] is the first entry and z[(i+NHASH-1)%NHASH] is the last entry of
814 ** the window.
816 ** Hash.a is the sum of all elements of hash.z[]. Hash.b is a weighted
817 ** sum. Hash.b is z[i]*NHASH + z[i+1]*(NHASH-1) + ... + z[i+NHASH-1]*1.
818 ** (Each index for z[] should be module NHASH, of course. The %NHASH operator
819 ** is omitted in the prior expression for brevity.)
821 typedef struct hash hash;
822 struct hash {
823 u16 a, b; /* Hash values */
824 u16 i; /* Start of the hash window */
825 char z[NHASH]; /* The values that have been hashed */
829 ** Initialize the rolling hash using the first NHASH characters of z[]
831 static void hash_init(hash *pHash, const char *z){
832 u16 a, b, i;
833 a = b = 0;
834 for(i=0; i<NHASH; i++){
835 a += z[i];
836 b += (NHASH-i)*z[i];
837 pHash->z[i] = z[i];
839 pHash->a = a & 0xffff;
840 pHash->b = b & 0xffff;
841 pHash->i = 0;
845 ** Advance the rolling hash by a single character "c"
847 static void hash_next(hash *pHash, int c){
848 u16 old = pHash->z[pHash->i];
849 pHash->z[pHash->i] = (char)c;
850 pHash->i = (pHash->i+1)&(NHASH-1);
851 pHash->a = pHash->a - old + (char)c;
852 pHash->b = pHash->b - NHASH*old + pHash->a;
856 ** Return a 32-bit hash value
858 static u32 hash_32bit(hash *pHash){
859 return (pHash->a & 0xffff) | (((u32)(pHash->b & 0xffff))<<16);
863 ** Write an base-64 integer into the given buffer.
865 static void putInt(unsigned int v, char **pz){
866 static const char zDigits[] =
867 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~";
868 /* 123456789 123456789 123456789 123456789 123456789 123456789 123 */
869 int i, j;
870 char zBuf[20];
871 if( v==0 ){
872 *(*pz)++ = '0';
873 return;
875 for(i=0; v>0; i++, v>>=6){
876 zBuf[i] = zDigits[v&0x3f];
878 for(j=i-1; j>=0; j--){
879 *(*pz)++ = zBuf[j];
884 ** Return the number digits in the base-64 representation of a positive integer
886 static int digit_count(int v){
887 unsigned int i, x;
888 for(i=1, x=64; (unsigned int)v>=x; i++, x <<= 6){}
889 return i;
893 ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
895 static unsigned int checksum(const char *zIn, size_t N){
896 const unsigned char *z = (const unsigned char *)zIn;
897 unsigned sum0 = 0;
898 unsigned sum1 = 0;
899 unsigned sum2 = 0;
900 unsigned sum3 = 0;
901 while(N >= 16){
902 sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
903 sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
904 sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
905 sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
906 z += 16;
907 N -= 16;
909 while(N >= 4){
910 sum0 += z[0];
911 sum1 += z[1];
912 sum2 += z[2];
913 sum3 += z[3];
914 z += 4;
915 N -= 4;
917 sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
918 switch(N){
919 case 3: sum3 += (z[2] << 8);
920 case 2: sum3 += (z[1] << 16);
921 case 1: sum3 += (z[0] << 24);
922 default: ;
924 return sum3;
928 ** Create a new delta.
930 ** The delta is written into a preallocated buffer, zDelta, which
931 ** should be at least 60 bytes longer than the target file, zOut.
932 ** The delta string will be NUL-terminated, but it might also contain
933 ** embedded NUL characters if either the zSrc or zOut files are
934 ** binary. This function returns the length of the delta string
935 ** in bytes, excluding the final NUL terminator character.
937 ** Output Format:
939 ** The delta begins with a base64 number followed by a newline. This
940 ** number is the number of bytes in the TARGET file. Thus, given a
941 ** delta file z, a program can compute the size of the output file
942 ** simply by reading the first line and decoding the base-64 number
943 ** found there. The delta_output_size() routine does exactly this.
945 ** After the initial size number, the delta consists of a series of
946 ** literal text segments and commands to copy from the SOURCE file.
947 ** A copy command looks like this:
949 ** NNN@MMM,
951 ** where NNN is the number of bytes to be copied and MMM is the offset
952 ** into the source file of the first byte (both base-64). If NNN is 0
953 ** it means copy the rest of the input file. Literal text is like this:
955 ** NNN:TTTTT
957 ** where NNN is the number of bytes of text (base-64) and TTTTT is the text.
959 ** The last term is of the form
961 ** NNN;
963 ** In this case, NNN is a 32-bit bigendian checksum of the output file
964 ** that can be used to verify that the delta applied correctly. All
965 ** numbers are in base-64.
967 ** Pure text files generate a pure text delta. Binary files generate a
968 ** delta that may contain some binary data.
970 ** Algorithm:
972 ** The encoder first builds a hash table to help it find matching
973 ** patterns in the source file. 16-byte chunks of the source file
974 ** sampled at evenly spaced intervals are used to populate the hash
975 ** table.
977 ** Next we begin scanning the target file using a sliding 16-byte
978 ** window. The hash of the 16-byte window in the target is used to
979 ** search for a matching section in the source file. When a match
980 ** is found, a copy command is added to the delta. An effort is
981 ** made to extend the matching section to regions that come before
982 ** and after the 16-byte hash window. A copy command is only issued
983 ** if the result would use less space that just quoting the text
984 ** literally. Literal text is added to the delta for sections that
985 ** do not match or which can not be encoded efficiently using copy
986 ** commands.
988 static int rbuDeltaCreate(
989 const char *zSrc, /* The source or pattern file */
990 unsigned int lenSrc, /* Length of the source file */
991 const char *zOut, /* The target file */
992 unsigned int lenOut, /* Length of the target file */
993 char *zDelta /* Write the delta into this buffer */
995 unsigned int i, base;
996 char *zOrigDelta = zDelta;
997 hash h;
998 int nHash; /* Number of hash table entries */
999 int *landmark; /* Primary hash table */
1000 int *collide; /* Collision chain */
1001 int lastRead = -1; /* Last byte of zSrc read by a COPY command */
1003 /* Add the target file size to the beginning of the delta
1005 putInt(lenOut, &zDelta);
1006 *(zDelta++) = '\n';
1008 /* If the source file is very small, it means that we have no
1009 ** chance of ever doing a copy command. Just output a single
1010 ** literal segment for the entire target and exit.
1012 if( lenSrc<=NHASH ){
1013 putInt(lenOut, &zDelta);
1014 *(zDelta++) = ':';
1015 memcpy(zDelta, zOut, lenOut);
1016 zDelta += lenOut;
1017 putInt(checksum(zOut, lenOut), &zDelta);
1018 *(zDelta++) = ';';
1019 return (int)(zDelta - zOrigDelta);
1022 /* Compute the hash table used to locate matching sections in the
1023 ** source file.
1025 nHash = lenSrc/NHASH;
1026 collide = sqlite3_malloc( nHash*2*sizeof(int) );
1027 landmark = &collide[nHash];
1028 memset(landmark, -1, nHash*sizeof(int));
1029 memset(collide, -1, nHash*sizeof(int));
1030 for(i=0; i<lenSrc-NHASH; i+=NHASH){
1031 int hv;
1032 hash_init(&h, &zSrc[i]);
1033 hv = hash_32bit(&h) % nHash;
1034 collide[i/NHASH] = landmark[hv];
1035 landmark[hv] = i/NHASH;
1038 /* Begin scanning the target file and generating copy commands and
1039 ** literal sections of the delta.
1041 base = 0; /* We have already generated everything before zOut[base] */
1042 while( base+NHASH<lenOut ){
1043 int iSrc, iBlock;
1044 int bestCnt, bestOfst=0, bestLitsz=0;
1045 hash_init(&h, &zOut[base]);
1046 i = 0; /* Trying to match a landmark against zOut[base+i] */
1047 bestCnt = 0;
1048 while( 1 ){
1049 int hv;
1050 int limit = 250;
1052 hv = hash_32bit(&h) % nHash;
1053 iBlock = landmark[hv];
1054 while( iBlock>=0 && (limit--)>0 ){
1056 ** The hash window has identified a potential match against
1057 ** landmark block iBlock. But we need to investigate further.
1059 ** Look for a region in zOut that matches zSrc. Anchor the search
1060 ** at zSrc[iSrc] and zOut[base+i]. Do not include anything prior to
1061 ** zOut[base] or after zOut[outLen] nor anything after zSrc[srcLen].
1063 ** Set cnt equal to the length of the match and set ofst so that
1064 ** zSrc[ofst] is the first element of the match. litsz is the number
1065 ** of characters between zOut[base] and the beginning of the match.
1066 ** sz will be the overhead (in bytes) needed to encode the copy
1067 ** command. Only generate copy command if the overhead of the
1068 ** copy command is less than the amount of literal text to be copied.
1070 int cnt, ofst, litsz;
1071 int j, k, x, y;
1072 int sz;
1074 /* Beginning at iSrc, match forwards as far as we can. j counts
1075 ** the number of characters that match */
1076 iSrc = iBlock*NHASH;
1077 for(
1078 j=0, x=iSrc, y=base+i;
1079 (unsigned int)x<lenSrc && (unsigned int)y<lenOut;
1080 j++, x++, y++
1082 if( zSrc[x]!=zOut[y] ) break;
1084 j--;
1086 /* Beginning at iSrc-1, match backwards as far as we can. k counts
1087 ** the number of characters that match */
1088 for(k=1; k<iSrc && (unsigned int)k<=i; k++){
1089 if( zSrc[iSrc-k]!=zOut[base+i-k] ) break;
1091 k--;
1093 /* Compute the offset and size of the matching region */
1094 ofst = iSrc-k;
1095 cnt = j+k+1;
1096 litsz = i-k; /* Number of bytes of literal text before the copy */
1097 /* sz will hold the number of bytes needed to encode the "insert"
1098 ** command and the copy command, not counting the "insert" text */
1099 sz = digit_count(i-k)+digit_count(cnt)+digit_count(ofst)+3;
1100 if( cnt>=sz && cnt>bestCnt ){
1101 /* Remember this match only if it is the best so far and it
1102 ** does not increase the file size */
1103 bestCnt = cnt;
1104 bestOfst = iSrc-k;
1105 bestLitsz = litsz;
1108 /* Check the next matching block */
1109 iBlock = collide[iBlock];
1112 /* We have a copy command that does not cause the delta to be larger
1113 ** than a literal insert. So add the copy command to the delta.
1115 if( bestCnt>0 ){
1116 if( bestLitsz>0 ){
1117 /* Add an insert command before the copy */
1118 putInt(bestLitsz,&zDelta);
1119 *(zDelta++) = ':';
1120 memcpy(zDelta, &zOut[base], bestLitsz);
1121 zDelta += bestLitsz;
1122 base += bestLitsz;
1124 base += bestCnt;
1125 putInt(bestCnt, &zDelta);
1126 *(zDelta++) = '@';
1127 putInt(bestOfst, &zDelta);
1128 *(zDelta++) = ',';
1129 if( bestOfst + bestCnt -1 > lastRead ){
1130 lastRead = bestOfst + bestCnt - 1;
1132 bestCnt = 0;
1133 break;
1136 /* If we reach this point, it means no match is found so far */
1137 if( base+i+NHASH>=lenOut ){
1138 /* We have reached the end of the file and have not found any
1139 ** matches. Do an "insert" for everything that does not match */
1140 putInt(lenOut-base, &zDelta);
1141 *(zDelta++) = ':';
1142 memcpy(zDelta, &zOut[base], lenOut-base);
1143 zDelta += lenOut-base;
1144 base = lenOut;
1145 break;
1148 /* Advance the hash by one character. Keep looking for a match */
1149 hash_next(&h, zOut[base+i+NHASH]);
1150 i++;
1153 /* Output a final "insert" record to get all the text at the end of
1154 ** the file that does not match anything in the source file.
1156 if( base<lenOut ){
1157 putInt(lenOut-base, &zDelta);
1158 *(zDelta++) = ':';
1159 memcpy(zDelta, &zOut[base], lenOut-base);
1160 zDelta += lenOut-base;
1162 /* Output the final checksum record. */
1163 putInt(checksum(zOut, lenOut), &zDelta);
1164 *(zDelta++) = ';';
1165 sqlite3_free(collide);
1166 return (int)(zDelta - zOrigDelta);
1170 ** End of code copied from fossil.
1171 **************************************************************************/
1173 static void strPrintfArray(
1174 Str *pStr, /* String object to append to */
1175 const char *zSep, /* Separator string */
1176 const char *zFmt, /* Format for each entry */
1177 char **az, int n /* Array of strings & its size (or -1) */
1179 int i;
1180 for(i=0; az[i] && (i<n || n<0); i++){
1181 if( i!=0 ) strPrintf(pStr, "%s", zSep);
1182 strPrintf(pStr, zFmt, az[i], az[i], az[i]);
1186 static void getRbudiffQuery(
1187 const char *zTab,
1188 char **azCol,
1189 int nPK,
1190 int bOtaRowid,
1191 Str *pSql
1193 int i;
1195 /* First the newly inserted rows: **/
1196 strPrintf(pSql, "SELECT ");
1197 strPrintfArray(pSql, ", ", "%s", azCol, -1);
1198 strPrintf(pSql, ", 0, "); /* Set ota_control to 0 for an insert */
1199 strPrintfArray(pSql, ", ", "NULL", azCol, -1);
1200 strPrintf(pSql, " FROM aux.%Q AS n WHERE NOT EXISTS (\n", zTab);
1201 strPrintf(pSql, " SELECT 1 FROM ", zTab);
1202 strPrintf(pSql, " main.%Q AS o WHERE ", zTab);
1203 strPrintfArray(pSql, " AND ", "(n.%Q = o.%Q)", azCol, nPK);
1204 strPrintf(pSql, "\n) AND ");
1205 strPrintfArray(pSql, " AND ", "(n.%Q IS NOT NULL)", azCol, nPK);
1207 /* Deleted rows: */
1208 strPrintf(pSql, "\nUNION ALL\nSELECT ");
1209 strPrintfArray(pSql, ", ", "%s", azCol, nPK);
1210 if( azCol[nPK] ){
1211 strPrintf(pSql, ", ");
1212 strPrintfArray(pSql, ", ", "NULL", &azCol[nPK], -1);
1214 strPrintf(pSql, ", 1, "); /* Set ota_control to 1 for a delete */
1215 strPrintfArray(pSql, ", ", "NULL", azCol, -1);
1216 strPrintf(pSql, " FROM main.%Q AS n WHERE NOT EXISTS (\n", zTab);
1217 strPrintf(pSql, " SELECT 1 FROM ", zTab);
1218 strPrintf(pSql, " aux.%Q AS o WHERE ", zTab);
1219 strPrintfArray(pSql, " AND ", "(n.%Q = o.%Q)", azCol, nPK);
1220 strPrintf(pSql, "\n) AND ");
1221 strPrintfArray(pSql, " AND ", "(n.%Q IS NOT NULL)", azCol, nPK);
1223 /* Updated rows. If all table columns are part of the primary key, there
1224 ** can be no updates. In this case this part of the compound SELECT can
1225 ** be omitted altogether. */
1226 if( azCol[nPK] ){
1227 strPrintf(pSql, "\nUNION ALL\nSELECT ");
1228 strPrintfArray(pSql, ", ", "n.%s", azCol, nPK);
1229 strPrintf(pSql, ",\n");
1230 strPrintfArray(pSql, " ,\n",
1231 " CASE WHEN n.%s IS o.%s THEN NULL ELSE n.%s END", &azCol[nPK], -1
1234 if( bOtaRowid==0 ){
1235 strPrintf(pSql, ", '");
1236 strPrintfArray(pSql, "", ".", azCol, nPK);
1237 strPrintf(pSql, "' ||\n");
1238 }else{
1239 strPrintf(pSql, ",\n");
1241 strPrintfArray(pSql, " ||\n",
1242 " CASE WHEN n.%s IS o.%s THEN '.' ELSE 'x' END", &azCol[nPK], -1
1244 strPrintf(pSql, "\nAS ota_control, ");
1245 strPrintfArray(pSql, ", ", "NULL", azCol, nPK);
1246 strPrintf(pSql, ",\n");
1247 strPrintfArray(pSql, " ,\n",
1248 " CASE WHEN n.%s IS o.%s THEN NULL ELSE o.%s END", &azCol[nPK], -1
1251 strPrintf(pSql, "\nFROM main.%Q AS o, aux.%Q AS n\nWHERE ", zTab, zTab);
1252 strPrintfArray(pSql, " AND ", "(n.%Q = o.%Q)", azCol, nPK);
1253 strPrintf(pSql, " AND ota_control LIKE '%%x%%'");
1256 /* Now add an ORDER BY clause to sort everything by PK. */
1257 strPrintf(pSql, "\nORDER BY ");
1258 for(i=1; i<=nPK; i++) strPrintf(pSql, "%s%d", ((i>1)?", ":""), i);
1261 static void rbudiff_one_table(const char *zTab, FILE *out){
1262 int bOtaRowid; /* True to use an ota_rowid column */
1263 int nPK; /* Number of primary key columns in table */
1264 char **azCol; /* NULL terminated array of col names */
1265 int i;
1266 int nCol;
1267 Str ct = {0, 0, 0}; /* The "CREATE TABLE data_xxx" statement */
1268 Str sql = {0, 0, 0}; /* Query to find differences */
1269 Str insert = {0, 0, 0}; /* First part of output INSERT statement */
1270 sqlite3_stmt *pStmt = 0;
1271 int nRow = 0; /* Total rows in data_xxx table */
1273 /* --rbu mode must use real primary keys. */
1274 g.bSchemaPK = 1;
1276 /* Check that the schemas of the two tables match. Exit early otherwise. */
1277 checkSchemasMatch(zTab);
1279 /* Grab the column names and PK details for the table(s). If no usable PK
1280 ** columns are found, bail out early. */
1281 azCol = columnNames("main", zTab, &nPK, &bOtaRowid);
1282 if( azCol==0 ){
1283 runtimeError("table %s has no usable PK columns", zTab);
1285 for(nCol=0; azCol[nCol]; nCol++);
1287 /* Build and output the CREATE TABLE statement for the data_xxx table */
1288 strPrintf(&ct, "CREATE TABLE IF NOT EXISTS 'data_%q'(", zTab);
1289 if( bOtaRowid ) strPrintf(&ct, "rbu_rowid, ");
1290 strPrintfArray(&ct, ", ", "%s", &azCol[bOtaRowid], -1);
1291 strPrintf(&ct, ", rbu_control);");
1293 /* Get the SQL for the query to retrieve data from the two databases */
1294 getRbudiffQuery(zTab, azCol, nPK, bOtaRowid, &sql);
1296 /* Build the first part of the INSERT statement output for each row
1297 ** in the data_xxx table. */
1298 strPrintf(&insert, "INSERT INTO 'data_%q' (", zTab);
1299 if( bOtaRowid ) strPrintf(&insert, "rbu_rowid, ");
1300 strPrintfArray(&insert, ", ", "%s", &azCol[bOtaRowid], -1);
1301 strPrintf(&insert, ", rbu_control) VALUES(");
1303 pStmt = db_prepare("%s", sql.z);
1305 while( sqlite3_step(pStmt)==SQLITE_ROW ){
1307 /* If this is the first row output, print out the CREATE TABLE
1308 ** statement first. And then set ct.z to NULL so that it is not
1309 ** printed again. */
1310 if( ct.z ){
1311 fprintf(out, "%s\n", ct.z);
1312 strFree(&ct);
1315 /* Output the first part of the INSERT statement */
1316 fprintf(out, "%s", insert.z);
1317 nRow++;
1319 if( sqlite3_column_type(pStmt, nCol)==SQLITE_INTEGER ){
1320 for(i=0; i<=nCol; i++){
1321 if( i>0 ) fprintf(out, ", ");
1322 printQuoted(out, sqlite3_column_value(pStmt, i));
1324 }else{
1325 char *zOtaControl;
1326 int nOtaControl = sqlite3_column_bytes(pStmt, nCol);
1328 zOtaControl = (char*)sqlite3_malloc(nOtaControl+1);
1329 memcpy(zOtaControl, sqlite3_column_text(pStmt, nCol), nOtaControl+1);
1331 for(i=0; i<nCol; i++){
1332 int bDone = 0;
1333 if( i>=nPK
1334 && sqlite3_column_type(pStmt, i)==SQLITE_BLOB
1335 && sqlite3_column_type(pStmt, nCol+1+i)==SQLITE_BLOB
1337 const char *aSrc = sqlite3_column_blob(pStmt, nCol+1+i);
1338 int nSrc = sqlite3_column_bytes(pStmt, nCol+1+i);
1339 const char *aFinal = sqlite3_column_blob(pStmt, i);
1340 int nFinal = sqlite3_column_bytes(pStmt, i);
1341 char *aDelta;
1342 int nDelta;
1344 aDelta = sqlite3_malloc(nFinal + 60);
1345 nDelta = rbuDeltaCreate(aSrc, nSrc, aFinal, nFinal, aDelta);
1346 if( nDelta<nFinal ){
1347 int j;
1348 fprintf(out, "x'");
1349 for(j=0; j<nDelta; j++) fprintf(out, "%02x", (u8)aDelta[j]);
1350 fprintf(out, "'");
1351 zOtaControl[i-bOtaRowid] = 'f';
1352 bDone = 1;
1354 sqlite3_free(aDelta);
1357 if( bDone==0 ){
1358 printQuoted(out, sqlite3_column_value(pStmt, i));
1360 fprintf(out, ", ");
1362 fprintf(out, "'%s'", zOtaControl);
1363 sqlite3_free(zOtaControl);
1366 /* And the closing bracket of the insert statement */
1367 fprintf(out, ");\n");
1370 sqlite3_finalize(pStmt);
1371 if( nRow>0 ){
1372 Str cnt = {0, 0, 0};
1373 strPrintf(&cnt, "INSERT INTO rbu_count VALUES('data_%q', %d);", zTab, nRow);
1374 fprintf(out, "%s\n", cnt.z);
1375 strFree(&cnt);
1378 strFree(&ct);
1379 strFree(&sql);
1380 strFree(&insert);
1384 ** Display a summary of differences between two versions of the same
1385 ** table table.
1387 ** * Number of rows changed
1388 ** * Number of rows added
1389 ** * Number of rows deleted
1390 ** * Number of identical rows
1392 static void summarize_one_table(const char *zTab, FILE *out){
1393 char *zId = safeId(zTab); /* Name of table (translated for us in SQL) */
1394 char **az = 0; /* Columns in main */
1395 char **az2 = 0; /* Columns in aux */
1396 int nPk; /* Primary key columns in main */
1397 int nPk2; /* Primary key columns in aux */
1398 int n = 0; /* Number of columns in main */
1399 int n2; /* Number of columns in aux */
1400 int i; /* Loop counter */
1401 const char *zSep; /* Separator string */
1402 Str sql; /* Comparison query */
1403 sqlite3_stmt *pStmt; /* Query statement to do the diff */
1404 sqlite3_int64 nUpdate; /* Number of updated rows */
1405 sqlite3_int64 nUnchanged; /* Number of unmodified rows */
1406 sqlite3_int64 nDelete; /* Number of deleted rows */
1407 sqlite3_int64 nInsert; /* Number of inserted rows */
1409 strInit(&sql);
1410 if( sqlite3_table_column_metadata(g.db,"aux",zTab,0,0,0,0,0,0) ){
1411 if( !sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
1412 /* Table missing from second database. */
1413 fprintf(out, "%s: missing from second database\n", zTab);
1415 goto end_summarize_one_table;
1418 if( sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
1419 /* Table missing from source */
1420 fprintf(out, "%s: missing from first database\n", zTab);
1421 goto end_summarize_one_table;
1424 az = columnNames("main", zTab, &nPk, 0);
1425 az2 = columnNames("aux", zTab, &nPk2, 0);
1426 if( az && az2 ){
1427 for(n=0; az[n]; n++){
1428 if( sqlite3_stricmp(az[n],az2[n])!=0 ) break;
1431 if( az==0
1432 || az2==0
1433 || nPk!=nPk2
1434 || az[n]
1436 /* Schema mismatch */
1437 fprintf(out, "%s: incompatible schema\n", zTab);
1438 goto end_summarize_one_table;
1441 /* Build the comparison query */
1442 for(n2=n; az[n2]; n2++){}
1443 strPrintf(&sql, "SELECT 1, count(*)");
1444 if( n2==nPk2 ){
1445 strPrintf(&sql, ", 0\n");
1446 }else{
1447 zSep = ", sum(";
1448 for(i=nPk; az[i]; i++){
1449 strPrintf(&sql, "%sA.%s IS NOT B.%s", zSep, az[i], az[i]);
1450 zSep = " OR ";
1452 strPrintf(&sql, ")\n");
1454 strPrintf(&sql, " FROM main.%s A, aux.%s B\n", zId, zId);
1455 zSep = " WHERE";
1456 for(i=0; i<nPk; i++){
1457 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1458 zSep = " AND";
1460 strPrintf(&sql, " UNION ALL\n");
1461 strPrintf(&sql, "SELECT 2, count(*), 0\n");
1462 strPrintf(&sql, " FROM main.%s A\n", zId);
1463 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B ", zId);
1464 zSep = "WHERE";
1465 for(i=0; i<nPk; i++){
1466 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1467 zSep = " AND";
1469 strPrintf(&sql, ")\n");
1470 strPrintf(&sql, " UNION ALL\n");
1471 strPrintf(&sql, "SELECT 3, count(*), 0\n");
1472 strPrintf(&sql, " FROM aux.%s B\n", zId);
1473 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A ", zId);
1474 zSep = "WHERE";
1475 for(i=0; i<nPk; i++){
1476 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1477 zSep = " AND";
1479 strPrintf(&sql, ")\n ORDER BY 1;\n");
1481 if( (g.fDebug & DEBUG_DIFF_SQL)!=0 ){
1482 printf("SQL for %s:\n%s\n", zId, sql.z);
1483 goto end_summarize_one_table;
1486 /* Run the query and output difference summary */
1487 pStmt = db_prepare("%s", sql.z);
1488 nUpdate = 0;
1489 nInsert = 0;
1490 nDelete = 0;
1491 nUnchanged = 0;
1492 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1493 switch( sqlite3_column_int(pStmt,0) ){
1494 case 1:
1495 nUpdate = sqlite3_column_int64(pStmt,2);
1496 nUnchanged = sqlite3_column_int64(pStmt,1) - nUpdate;
1497 break;
1498 case 2:
1499 nDelete = sqlite3_column_int64(pStmt,1);
1500 break;
1501 case 3:
1502 nInsert = sqlite3_column_int64(pStmt,1);
1503 break;
1506 sqlite3_finalize(pStmt);
1507 fprintf(out, "%s: %lld changes, %lld inserts, %lld deletes, %lld unchanged\n",
1508 zTab, nUpdate, nInsert, nDelete, nUnchanged);
1510 end_summarize_one_table:
1511 strFree(&sql);
1512 sqlite3_free(zId);
1513 namelistFree(az);
1514 namelistFree(az2);
1515 return;
1519 ** Write a 64-bit signed integer as a varint onto out
1521 static void putsVarint(FILE *out, sqlite3_uint64 v){
1522 int i, n;
1523 unsigned char p[12];
1524 if( v & (((sqlite3_uint64)0xff000000)<<32) ){
1525 p[8] = (unsigned char)v;
1526 v >>= 8;
1527 for(i=7; i>=0; i--){
1528 p[i] = (unsigned char)((v & 0x7f) | 0x80);
1529 v >>= 7;
1531 fwrite(p, 8, 1, out);
1532 }else{
1533 n = 9;
1535 p[n--] = (unsigned char)((v & 0x7f) | 0x80);
1536 v >>= 7;
1537 }while( v!=0 );
1538 p[9] &= 0x7f;
1539 fwrite(p+n+1, 9-n, 1, out);
1544 ** Write an SQLite value onto out.
1546 static void putValue(FILE *out, sqlite3_stmt *pStmt, int k){
1547 int iDType = sqlite3_column_type(pStmt, k);
1548 sqlite3_int64 iX;
1549 double rX;
1550 sqlite3_uint64 uX;
1551 int j;
1553 putc(iDType, out);
1554 switch( iDType ){
1555 case SQLITE_INTEGER:
1556 iX = sqlite3_column_int64(pStmt, k);
1557 memcpy(&uX, &iX, 8);
1558 for(j=56; j>=0; j-=8) putc((uX>>j)&0xff, out);
1559 break;
1560 case SQLITE_FLOAT:
1561 rX = sqlite3_column_double(pStmt, k);
1562 memcpy(&uX, &rX, 8);
1563 for(j=56; j>=0; j-=8) putc((uX>>j)&0xff, out);
1564 break;
1565 case SQLITE_TEXT:
1566 iX = sqlite3_column_bytes(pStmt, k);
1567 putsVarint(out, (sqlite3_uint64)iX);
1568 fwrite(sqlite3_column_text(pStmt, k),1,(size_t)iX,out);
1569 break;
1570 case SQLITE_BLOB:
1571 iX = sqlite3_column_bytes(pStmt, k);
1572 putsVarint(out, (sqlite3_uint64)iX);
1573 fwrite(sqlite3_column_blob(pStmt, k),1,(size_t)iX,out);
1574 break;
1575 case SQLITE_NULL:
1576 break;
1581 ** Generate a CHANGESET for all differences from main.zTab to aux.zTab.
1583 static void changeset_one_table(const char *zTab, FILE *out){
1584 sqlite3_stmt *pStmt; /* SQL statment */
1585 char *zId = safeId(zTab); /* Escaped name of the table */
1586 char **azCol = 0; /* List of escaped column names */
1587 int nCol = 0; /* Number of columns */
1588 int *aiFlg = 0; /* 0 if column is not part of PK */
1589 int *aiPk = 0; /* Column numbers for each PK column */
1590 int nPk = 0; /* Number of PRIMARY KEY columns */
1591 Str sql; /* SQL for the diff query */
1592 int i, k; /* Loop counters */
1593 const char *zSep; /* List separator */
1595 /* Check that the schemas of the two tables match. Exit early otherwise. */
1596 checkSchemasMatch(zTab);
1597 strInit(&sql);
1599 pStmt = db_prepare("PRAGMA main.table_info=%Q", zTab);
1600 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1601 nCol++;
1602 azCol = sqlite3_realloc(azCol, sizeof(char*)*nCol);
1603 if( azCol==0 ) runtimeError("out of memory");
1604 aiFlg = sqlite3_realloc(aiFlg, sizeof(int)*nCol);
1605 if( aiFlg==0 ) runtimeError("out of memory");
1606 azCol[nCol-1] = safeId((const char*)sqlite3_column_text(pStmt,1));
1607 aiFlg[nCol-1] = i = sqlite3_column_int(pStmt,5);
1608 if( i>0 ){
1609 if( i>nPk ){
1610 nPk = i;
1611 aiPk = sqlite3_realloc(aiPk, sizeof(int)*nPk);
1612 if( aiPk==0 ) runtimeError("out of memory");
1614 aiPk[i-1] = nCol-1;
1617 sqlite3_finalize(pStmt);
1618 if( nPk==0 ) goto end_changeset_one_table;
1619 if( nCol>nPk ){
1620 strPrintf(&sql, "SELECT %d", SQLITE_UPDATE);
1621 for(i=0; i<nCol; i++){
1622 if( aiFlg[i] ){
1623 strPrintf(&sql, ",\n A.%s", azCol[i]);
1624 }else{
1625 strPrintf(&sql, ",\n A.%s IS NOT B.%s, A.%s, B.%s",
1626 azCol[i], azCol[i], azCol[i], azCol[i]);
1629 strPrintf(&sql,"\n FROM main.%s A, aux.%s B\n", zId, zId);
1630 zSep = " WHERE";
1631 for(i=0; i<nPk; i++){
1632 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1633 zSep = " AND";
1635 zSep = "\n AND (";
1636 for(i=0; i<nCol; i++){
1637 if( aiFlg[i] ) continue;
1638 strPrintf(&sql, "%sA.%s IS NOT B.%s", zSep, azCol[i], azCol[i]);
1639 zSep = " OR\n ";
1641 strPrintf(&sql,")\n UNION ALL\n");
1643 strPrintf(&sql, "SELECT %d", SQLITE_DELETE);
1644 for(i=0; i<nCol; i++){
1645 if( aiFlg[i] ){
1646 strPrintf(&sql, ",\n A.%s", azCol[i]);
1647 }else{
1648 strPrintf(&sql, ",\n 1, A.%s, NULL", azCol[i]);
1651 strPrintf(&sql, "\n FROM main.%s A\n", zId);
1652 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B\n", zId);
1653 zSep = " WHERE";
1654 for(i=0; i<nPk; i++){
1655 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1656 zSep = " AND";
1658 strPrintf(&sql, ")\n UNION ALL\n");
1659 strPrintf(&sql, "SELECT %d", SQLITE_INSERT);
1660 for(i=0; i<nCol; i++){
1661 if( aiFlg[i] ){
1662 strPrintf(&sql, ",\n B.%s", azCol[i]);
1663 }else{
1664 strPrintf(&sql, ",\n 1, NULL, B.%s", azCol[i]);
1667 strPrintf(&sql, "\n FROM aux.%s B\n", zId);
1668 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A\n", zId);
1669 zSep = " WHERE";
1670 for(i=0; i<nPk; i++){
1671 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1672 zSep = " AND";
1674 strPrintf(&sql, ")\n");
1675 strPrintf(&sql, " ORDER BY");
1676 zSep = " ";
1677 for(i=0; i<nPk; i++){
1678 strPrintf(&sql, "%s %d", zSep, aiPk[i]+2);
1679 zSep = ",";
1681 strPrintf(&sql, ";\n");
1683 if( g.fDebug & DEBUG_DIFF_SQL ){
1684 printf("SQL for %s:\n%s\n", zId, sql.z);
1685 goto end_changeset_one_table;
1688 putc('T', out);
1689 putsVarint(out, (sqlite3_uint64)nCol);
1690 for(i=0; i<nCol; i++) putc(aiFlg[i], out);
1691 fwrite(zTab, 1, strlen(zTab), out);
1692 putc(0, out);
1694 pStmt = db_prepare("%s", sql.z);
1695 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1696 int iType = sqlite3_column_int(pStmt,0);
1697 putc(iType, out);
1698 putc(0, out);
1699 switch( sqlite3_column_int(pStmt,0) ){
1700 case SQLITE_UPDATE: {
1701 for(k=1, i=0; i<nCol; i++){
1702 if( aiFlg[i] ){
1703 putValue(out, pStmt, k);
1704 k++;
1705 }else if( sqlite3_column_int(pStmt,k) ){
1706 putValue(out, pStmt, k+1);
1707 k += 3;
1708 }else{
1709 putc(0, out);
1710 k += 3;
1713 for(k=1, i=0; i<nCol; i++){
1714 if( aiFlg[i] ){
1715 putc(0, out);
1716 k++;
1717 }else if( sqlite3_column_int(pStmt,k) ){
1718 putValue(out, pStmt, k+2);
1719 k += 3;
1720 }else{
1721 putc(0, out);
1722 k += 3;
1725 break;
1727 case SQLITE_INSERT: {
1728 for(k=1, i=0; i<nCol; i++){
1729 if( aiFlg[i] ){
1730 putValue(out, pStmt, k);
1731 k++;
1732 }else{
1733 putValue(out, pStmt, k+2);
1734 k += 3;
1737 break;
1739 case SQLITE_DELETE: {
1740 for(k=1, i=0; i<nCol; i++){
1741 if( aiFlg[i] ){
1742 putValue(out, pStmt, k);
1743 k++;
1744 }else{
1745 putValue(out, pStmt, k+1);
1746 k += 3;
1749 break;
1753 sqlite3_finalize(pStmt);
1755 end_changeset_one_table:
1756 while( nCol>0 ) sqlite3_free(azCol[--nCol]);
1757 sqlite3_free(azCol);
1758 sqlite3_free(aiPk);
1759 sqlite3_free(zId);
1760 sqlite3_free(aiFlg);
1761 strFree(&sql);
1765 ** Return true if the ascii character passed as the only argument is a
1766 ** whitespace character. Otherwise return false.
1768 static int is_whitespace(char x){
1769 return (x==' ' || x=='\t' || x=='\n' || x=='\r');
1773 ** Extract the next SQL keyword or quoted string from buffer zIn and copy it
1774 ** (or a prefix of it if it will not fit) into buffer zBuf, size nBuf bytes.
1775 ** Return a pointer to the character within zIn immediately following
1776 ** the token or quoted string just extracted.
1778 static const char *gobble_token(const char *zIn, char *zBuf, int nBuf){
1779 const char *p = zIn;
1780 char *pOut = zBuf;
1781 char *pEnd = &pOut[nBuf-1];
1782 char q = 0; /* quote character, if any */
1784 if( p==0 ) return 0;
1785 while( is_whitespace(*p) ) p++;
1786 switch( *p ){
1787 case '"': q = '"'; break;
1788 case '\'': q = '\''; break;
1789 case '`': q = '`'; break;
1790 case '[': q = ']'; break;
1793 if( q ){
1794 p++;
1795 while( *p && pOut<pEnd ){
1796 if( *p==q ){
1797 p++;
1798 if( *p!=q ) break;
1800 if( pOut<pEnd ) *pOut++ = *p;
1801 p++;
1803 }else{
1804 while( *p && !is_whitespace(*p) && *p!='(' ){
1805 if( pOut<pEnd ) *pOut++ = *p;
1806 p++;
1810 *pOut = '\0';
1811 return p;
1815 ** This function is the implementation of SQL scalar function "module_name":
1817 ** module_name(SQL)
1819 ** The only argument should be an SQL statement of the type that may appear
1820 ** in the sqlite_schema table. If the statement is a "CREATE VIRTUAL TABLE"
1821 ** statement, then the value returned is the name of the module that it
1822 ** uses. Otherwise, if the statement is not a CVT, NULL is returned.
1824 static void module_name_func(
1825 sqlite3_context *pCtx,
1826 int nVal, sqlite3_value **apVal
1828 const char *zSql;
1829 char zToken[32];
1831 assert( nVal==1 );
1832 zSql = (const char*)sqlite3_value_text(apVal[0]);
1834 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1835 if( zSql==0 || sqlite3_stricmp(zToken, "create") ) return;
1836 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1837 if( zSql==0 || sqlite3_stricmp(zToken, "virtual") ) return;
1838 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1839 if( zSql==0 || sqlite3_stricmp(zToken, "table") ) return;
1840 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1841 if( zSql==0 ) return;
1842 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1843 if( zSql==0 || sqlite3_stricmp(zToken, "using") ) return;
1844 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1846 sqlite3_result_text(pCtx, zToken, -1, SQLITE_TRANSIENT);
1850 ** Return the text of an SQL statement that itself returns the list of
1851 ** tables to process within the database.
1853 const char *all_tables_sql(){
1854 if( g.bHandleVtab ){
1855 int rc;
1857 rc = sqlite3_exec(g.db,
1858 "CREATE TEMP TABLE tblmap(module COLLATE nocase, postfix);"
1859 "INSERT INTO temp.tblmap VALUES"
1860 "('fts3', '_content'), ('fts3', '_segments'), ('fts3', '_segdir'),"
1862 "('fts4', '_content'), ('fts4', '_segments'), ('fts4', '_segdir'),"
1863 "('fts4', '_docsize'), ('fts4', '_stat'),"
1865 "('fts5', '_data'), ('fts5', '_idx'), ('fts5', '_content'),"
1866 "('fts5', '_docsize'), ('fts5', '_config'),"
1868 "('rtree', '_node'), ('rtree', '_rowid'), ('rtree', '_parent');"
1869 , 0, 0, 0
1871 assert( rc==SQLITE_OK );
1873 rc = sqlite3_create_function(
1874 g.db, "module_name", 1, SQLITE_UTF8, 0, module_name_func, 0, 0
1876 assert( rc==SQLITE_OK );
1878 return
1879 "SELECT name FROM main.sqlite_schema\n"
1880 " WHERE type='table' AND (\n"
1881 " module_name(sql) IS NULL OR \n"
1882 " module_name(sql) IN (SELECT module FROM temp.tblmap)\n"
1883 " ) AND name NOT IN (\n"
1884 " SELECT a.name || b.postfix \n"
1885 "FROM main.sqlite_schema AS a, temp.tblmap AS b \n"
1886 "WHERE module_name(a.sql) = b.module\n"
1887 " )\n"
1888 "UNION \n"
1889 "SELECT name FROM aux.sqlite_schema\n"
1890 " WHERE type='table' AND (\n"
1891 " module_name(sql) IS NULL OR \n"
1892 " module_name(sql) IN (SELECT module FROM temp.tblmap)\n"
1893 " ) AND name NOT IN (\n"
1894 " SELECT a.name || b.postfix \n"
1895 "FROM aux.sqlite_schema AS a, temp.tblmap AS b \n"
1896 "WHERE module_name(a.sql) = b.module\n"
1897 " )\n"
1898 " ORDER BY name";
1899 }else{
1900 return
1901 "SELECT name FROM main.sqlite_schema\n"
1902 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1903 " UNION\n"
1904 "SELECT name FROM aux.sqlite_schema\n"
1905 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1906 " ORDER BY name";
1911 ** Print sketchy documentation for this utility program
1913 static void showHelp(void){
1914 printf("Usage: %s [options] DB1 DB2\n", g.zArgv0);
1915 printf(
1916 "Output SQL text that would transform DB1 into DB2.\n"
1917 "Options:\n"
1918 " --changeset FILE Write a CHANGESET into FILE\n"
1919 " -L|--lib LIBRARY Load an SQLite extension library\n"
1920 " --primarykey Use schema-defined PRIMARY KEYs\n"
1921 " --rbu Output SQL to create/populate RBU table(s)\n"
1922 " --schema Show only differences in the schema\n"
1923 " --summary Show only a summary of the differences\n"
1924 " --table TAB Show only differences in table TAB\n"
1925 " --transaction Show SQL output inside a transaction\n"
1926 " --vtab Handle fts3, fts4, fts5 and rtree tables\n"
1927 "See https://sqlite.org/sqldiff.html for detailed explanation.\n"
1931 int main(int argc, char **argv){
1932 const char *zDb1 = 0;
1933 const char *zDb2 = 0;
1934 int i;
1935 int rc;
1936 char *zErrMsg = 0;
1937 char *zSql;
1938 sqlite3_stmt *pStmt;
1939 char *zTab = 0;
1940 FILE *out = stdout;
1941 void (*xDiff)(const char*,FILE*) = diff_one_table;
1942 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1943 int nExt = 0;
1944 char **azExt = 0;
1945 #endif
1946 int useTransaction = 0;
1947 int neverUseTransaction = 0;
1949 g.zArgv0 = argv[0];
1950 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
1951 for(i=1; i<argc; i++){
1952 const char *z = argv[i];
1953 if( z[0]=='-' ){
1954 z++;
1955 if( z[0]=='-' ) z++;
1956 if( strcmp(z,"changeset")==0 ){
1957 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
1958 out = fopen(argv[++i], "wb");
1959 if( out==0 ) cmdlineError("cannot open: %s", argv[i]);
1960 xDiff = changeset_one_table;
1961 neverUseTransaction = 1;
1962 }else
1963 if( strcmp(z,"debug")==0 ){
1964 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
1965 g.fDebug = strtol(argv[++i], 0, 0);
1966 }else
1967 if( strcmp(z,"help")==0 ){
1968 showHelp();
1969 return 0;
1970 }else
1971 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1972 if( strcmp(z,"lib")==0 || strcmp(z,"L")==0 ){
1973 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
1974 azExt = realloc(azExt, sizeof(azExt[0])*(nExt+1));
1975 if( azExt==0 ) cmdlineError("out of memory");
1976 azExt[nExt++] = argv[++i];
1977 }else
1978 #endif
1979 if( strcmp(z,"primarykey")==0 ){
1980 g.bSchemaPK = 1;
1981 }else
1982 if( strcmp(z,"rbu")==0 ){
1983 xDiff = rbudiff_one_table;
1984 }else
1985 if( strcmp(z,"schema")==0 ){
1986 g.bSchemaOnly = 1;
1987 }else
1988 if( strcmp(z,"summary")==0 ){
1989 xDiff = summarize_one_table;
1990 }else
1991 if( strcmp(z,"table")==0 ){
1992 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
1993 zTab = argv[++i];
1994 g.bSchemaCompare =
1995 sqlite3_stricmp(zTab, "sqlite_schema")==0
1996 || sqlite3_stricmp(zTab, "sqlite_master")==0;
1997 }else
1998 if( strcmp(z,"transaction")==0 ){
1999 useTransaction = 1;
2000 }else
2001 if( strcmp(z,"vtab")==0 ){
2002 g.bHandleVtab = 1;
2003 }else
2005 cmdlineError("unknown option: %s", argv[i]);
2007 }else if( zDb1==0 ){
2008 zDb1 = argv[i];
2009 }else if( zDb2==0 ){
2010 zDb2 = argv[i];
2011 }else{
2012 cmdlineError("unknown argument: %s", argv[i]);
2015 if( zDb2==0 ){
2016 cmdlineError("two database arguments required");
2018 if( g.bSchemaOnly && g.bSchemaCompare ){
2019 cmdlineError("The --schema option is useless with --table %s .", zTab);
2021 rc = sqlite3_open(zDb1, &g.db);
2022 if( rc ){
2023 cmdlineError("cannot open database file \"%s\"", zDb1);
2025 rc = sqlite3_exec(g.db, "SELECT * FROM sqlite_schema", 0, 0, &zErrMsg);
2026 if( rc || zErrMsg ){
2027 cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb1);
2029 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2030 sqlite3_enable_load_extension(g.db, 1);
2031 for(i=0; i<nExt; i++){
2032 rc = sqlite3_load_extension(g.db, azExt[i], 0, &zErrMsg);
2033 if( rc || zErrMsg ){
2034 cmdlineError("error loading %s: %s", azExt[i], zErrMsg);
2037 free(azExt);
2038 #endif
2039 zSql = sqlite3_mprintf("ATTACH %Q as aux;", zDb2);
2040 rc = sqlite3_exec(g.db, zSql, 0, 0, &zErrMsg);
2041 sqlite3_free(zSql);
2042 zSql = 0;
2043 if( rc || zErrMsg ){
2044 cmdlineError("cannot attach database \"%s\"", zDb2);
2046 rc = sqlite3_exec(g.db, "SELECT * FROM aux.sqlite_schema", 0, 0, &zErrMsg);
2047 if( rc || zErrMsg ){
2048 cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb2);
2051 if( neverUseTransaction ) useTransaction = 0;
2052 if( useTransaction ) fprintf(out, "BEGIN TRANSACTION;\n");
2053 if( xDiff==rbudiff_one_table ){
2054 fprintf(out, "CREATE TABLE IF NOT EXISTS rbu_count"
2055 "(tbl TEXT PRIMARY KEY COLLATE NOCASE, cnt INTEGER) "
2056 "WITHOUT ROWID;\n"
2059 if( zTab ){
2060 xDiff(zTab, out);
2061 }else{
2062 /* Handle tables one by one */
2063 pStmt = db_prepare("%s", all_tables_sql() );
2064 while( SQLITE_ROW==sqlite3_step(pStmt) ){
2065 xDiff((const char*)sqlite3_column_text(pStmt,0), out);
2067 sqlite3_finalize(pStmt);
2069 if( useTransaction ) printf("COMMIT;\n");
2071 /* TBD: Handle trigger differences */
2072 /* TBD: Handle view differences */
2073 sqlite3_close(g.db);
2074 return 0;