4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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
30 ** All global variables are gathered into the "g" singleton.
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 */
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
;
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
){
68 ** Print an error resulting from faulting command-line arguments and
71 static void cmdlineError(const char *zFormat
, ...){
73 fprintf(stderr
, "%s: ", g
.zArgv0
);
74 va_start(ap
, zFormat
);
75 vfprintf(stderr
, zFormat
, ap
);
77 fprintf(stderr
, "\n\"%s --help\" for more help\n", g
.zArgv0
);
82 ** Print an error message for an error that occurs at runtime, then
85 static void runtimeError(const char *zFormat
, ...){
87 fprintf(stderr
, "%s: ", g
.zArgv0
);
88 va_start(ap
, zFormat
);
89 vfprintf(stderr
, zFormat
, ap
);
91 fprintf(stderr
, "\n");
96 ** Free all memory held by a Str object
98 static void strFree(Str
*p
){
104 ** Add formatted text to the end of a Str object
106 static void strPrintf(Str
*p
, const char *zFormat
, ...){
111 va_start(ap
, zFormat
);
112 sqlite3_vsnprintf(p
->nAlloc
-p
->nUsed
, p
->z
+p
->nUsed
, zFormat
, ap
);
114 nNew
= (int)strlen(p
->z
+ p
->nUsed
);
118 if( p
->nUsed
+nNew
< p
->nAlloc
-1 ){
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
137 static char *safeId(const char *zId
){
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
) ){
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
160 static sqlite3_stmt
*db_vprepare(const char *zFormat
, va_list ap
){
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);
169 runtimeError("SQL statement error: %s\n\"%s\"", sqlite3_errmsg(g
.db
),
175 static sqlite3_stmt
*db_prepare(const char *zFormat
, ...){
178 va_start(ap
, zFormat
);
179 pStmt
= db_vprepare(zFormat
, ap
);
185 ** Free a list of strings
187 static void namelistFree(char **az
){
190 for(i
=0; az
[i
]; i
++) sqlite3_free(az
[i
]);
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.]
217 ** CREATE TABLE t1(a INT UNIQUE, b INTEGER, c TEXT, PRIMARY KEY(c));
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));
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;
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));
268 sqlite3_finalize(pStmt
);
273 pStmt
= db_prepare("PRAGMA %s.index_xinfo=%Q", zDb
, zPkIdxName
);
274 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
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;
285 sqlite3_finalize(pStmt
);
286 sqlite3_free(zPkIdxName
);
291 pStmt
= db_prepare("PRAGMA %s.table_info=%Q", zDb
, zTab
);
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.
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;
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. */
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));
325 if( truePk
&& (iPKey
= sqlite3_column_int(pStmt
,5))>0 ){
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");
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. */
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;
358 az
[0] = sqlite3_mprintf("%s", azRowid
[i
]);
363 for(i
=1; i
<naz
; i
++) sqlite3_free(az
[i
]);
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
) ){
379 r1
= sqlite3_value_double(X
);
380 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%!.15g", r1
);
381 fprintf(out
, "%s", zBuf
);
384 case SQLITE_INTEGER
: {
385 fprintf(out
, "%lld", sqlite3_value_int64(X
));
389 const unsigned char *zBlob
= sqlite3_value_blob(X
);
390 int nBlob
= sqlite3_value_bytes(X
);
394 for(i
=0; i
<nBlob
; i
++){
395 fprintf(out
, "%02x", zBlob
[i
]);
399 /* Could be an OOM, could be a zero-byte blob */
405 const unsigned char *zArg
= sqlite3_value_text(X
);
408 fprintf(out
, "NULL");
413 for(i
=j
=0; zArg
[i
]; i
++){
415 int ctl
= iscntrl(c
);
418 fprintf(out
, "%.*s'||X'%02x", i
-j
, &zArg
[j
], c
);
421 fprintf(out
, "%02x", c
);
426 fprintf(out
, "'\n||'");
429 fprintf(out
, "%.*s'", i
-j
+1, &zArg
[j
]);
434 fprintf(out
, "%s'", &zArg
[j
]);
439 fprintf(out
, "NULL");
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);
467 pStmt
= db_prepare("SELECT * FROM aux.%s", zId
);
468 strPrintf(&ins
,"INSERT INTO %s VALUES", zId
);
473 for(i
=0; az
[i
]; i
++){
474 strPrintf(&sql
, "%s %s", zSep
, az
[i
]);
477 strPrintf(&sql
," FROM aux.%s", zId
);
479 for(i
=1; i
<=nPk
; i
++){
480 strPrintf(&sql
, "%s %d", zSep
, i
);
483 pStmt
= db_prepare("%s", sql
.z
);
485 strPrintf(&ins
, "INSERT INTO %s", zId
);
487 for(i
=0; az
[i
]; i
++){
488 strPrintf(&ins
, "%s%s", zSep
, az
[i
]);
491 strPrintf(&ins
,") VALUES");
494 nCol
= sqlite3_column_count(pStmt
);
495 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
496 fprintf(out
, "%s",ins
.z
);
498 for(i
=0; i
<nCol
; i
++){
499 fprintf(out
, "%s",zSep
);
500 printQuoted(out
, sqlite3_column_value(pStmt
,i
));
503 fprintf(out
, ");\n");
505 sqlite3_finalize(pStmt
);
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",
511 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
512 fprintf(out
, "%s;\n", sqlite3_column_text(pStmt
,0));
514 sqlite3_finalize(pStmt
);
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
)? "-- " : "";
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);
547 printf("Rowid not accessible for %s\n", zId
);
550 for(i
=0; az
[i
]; i
++){
551 printf(" %s", az
[i
]);
552 if( i
+1==nPk
) printf(" *");
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
);
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
);
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);
582 for(n
=0; az
[n
] && az2
[n
]; n
++){
583 if( sqlite3_stricmp(az
[n
],az2
[n
])!=0 ) break;
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
);
603 nQ
= nPk2
+1+2*(n2
-nPk2
);
606 for(i
=0; i
<nPk
; i
++){
607 strPrintf(&sql
, "%sB.%s", zSep
, az
[i
]);
610 strPrintf(&sql
, ", 1 /* changed row */");
612 strPrintf(&sql
, ", A.%s IS NOT B.%s, B.%s",
613 az
[i
], az2
[i
], az2
[i
]);
617 strPrintf(&sql
, ", B.%s IS NOT NULL, B.%s",
621 strPrintf(&sql
, "\n FROM main.%s A, aux.%s B\n", zId
, zId
);
623 for(i
=0; i
<nPk
; i
++){
624 strPrintf(&sql
, "%s A.%s=B.%s", zSep
, az
[i
], az
[i
]);
629 strPrintf(&sql
, "%sA.%s IS NOT B.%s%s\n",
630 zSep
, az
[i
], az2
[i
], az2
[i
+1]==0 ? ")" : "");
635 strPrintf(&sql
, "%sB.%s IS NOT NULL%s\n",
636 zSep
, az2
[i
], az2
[i
+1]==0 ? ")" : "");
640 strPrintf(&sql
, " UNION ALL\n");
643 for(i
=0; i
<nPk
; i
++){
644 strPrintf(&sql
, "%sA.%s", zSep
, az
[i
]);
647 strPrintf(&sql
, ", 2 /* deleted row */");
649 strPrintf(&sql
, ", NULL, NULL");
652 strPrintf(&sql
, "\n FROM main.%s A\n", zId
);
653 strPrintf(&sql
, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B\n", zId
);
655 for(i
=0; i
<nPk
; i
++){
656 strPrintf(&sql
, "%s A.%s=B.%s", zSep
, az
[i
], az
[i
]);
659 strPrintf(&sql
, ")\n");
660 zSep
= " UNION ALL\nSELECT ";
661 for(i
=0; i
<nPk
; i
++){
662 strPrintf(&sql
, "%sB.%s", zSep
, az
[i
]);
665 strPrintf(&sql
, ", 3 /* inserted row */");
667 strPrintf(&sql
, ", 1, B.%s", az2
[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
);
673 for(i
=0; i
<nPk
; i
++){
674 strPrintf(&sql
, "%s A.%s=B.%s", zSep
, az
[i
], az
[i
]);
677 strPrintf(&sql
, ")\n ORDER BY");
679 for(i
=1; i
<=nPk
; i
++){
680 strPrintf(&sql
, "%s%d", zSep
, i
);
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 */
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)",
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
);
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
);
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]);
719 printQuoted(out
, sqlite3_column_value(pStmt
,i
+1));
721 }else{ /* Delete a row */
722 fprintf(out
, "%sDELETE FROM %s", zLead
, zId
);
725 for(i
=0; i
<nPk
; i
++){
726 fprintf(out
, "%s %s=", zSep
, az2
[i
]);
727 printQuoted(out
, sqlite3_column_value(pStmt
,i
));
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");
736 for(i
=0; i
<nPk2
; i
++){
737 fprintf(out
, "%s", zSep
);
739 printQuoted(out
, sqlite3_column_value(pStmt
,i
));
741 for(i
=nPk2
+2; i
<nQ
; i
+=2){
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 */
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)",
760 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
761 fprintf(out
, "%s;\n", sqlite3_column_text(pStmt
,0));
763 sqlite3_finalize(pStmt
);
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
));
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
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
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
;
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
){
834 for(i
=0; i
<NHASH
; i
++){
839 pHash
->a
= a
& 0xffff;
840 pHash
->b
= b
& 0xffff;
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 */
875 for(i
=0; v
>0; i
++, v
>>=6){
876 zBuf
[i
] = zDigits
[v
&0x3f];
878 for(j
=i
-1; j
>=0; j
--){
884 ** Return the number digits in the base-64 representation of a positive integer
886 static int digit_count(int v
){
888 for(i
=1, x
=64; (unsigned int)v
>=x
; i
++, x
<<= 6){}
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
;
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]);
917 sum3
+= (sum2
<< 8) + (sum1
<< 16) + (sum0
<< 24);
919 case 3: sum3
+= (z
[2] << 8);
920 case 2: sum3
+= (z
[1] << 16);
921 case 1: sum3
+= (z
[0] << 24);
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.
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:
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:
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
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.
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
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
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
;
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
);
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
);
1015 memcpy(zDelta
, zOut
, lenOut
);
1017 putInt(checksum(zOut
, lenOut
), &zDelta
);
1019 return (int)(zDelta
- zOrigDelta
);
1022 /* Compute the hash table used to locate matching sections in the
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
){
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
){
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] */
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
;
1074 /* Beginning at iSrc, match forwards as far as we can. j counts
1075 ** the number of characters that match */
1076 iSrc
= iBlock
*NHASH
;
1078 j
=0, x
=iSrc
, y
=base
+i
;
1079 (unsigned int)x
<lenSrc
&& (unsigned int)y
<lenOut
;
1082 if( zSrc
[x
]!=zOut
[y
] ) break;
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;
1093 /* Compute the offset and size of the matching region */
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 */
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.
1117 /* Add an insert command before the copy */
1118 putInt(bestLitsz
,&zDelta
);
1120 memcpy(zDelta
, &zOut
[base
], bestLitsz
);
1121 zDelta
+= bestLitsz
;
1125 putInt(bestCnt
, &zDelta
);
1127 putInt(bestOfst
, &zDelta
);
1129 if( bestOfst
+ bestCnt
-1 > lastRead
){
1130 lastRead
= bestOfst
+ bestCnt
- 1;
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
);
1142 memcpy(zDelta
, &zOut
[base
], lenOut
-base
);
1143 zDelta
+= lenOut
-base
;
1148 /* Advance the hash by one character. Keep looking for a match */
1149 hash_next(&h
, zOut
[base
+i
+NHASH
]);
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.
1157 putInt(lenOut
-base
, &zDelta
);
1159 memcpy(zDelta
, &zOut
[base
], lenOut
-base
);
1160 zDelta
+= lenOut
-base
;
1162 /* Output the final checksum record. */
1163 putInt(checksum(zOut
, lenOut
), &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) */
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(
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
);
1208 strPrintf(pSql
, "\nUNION ALL\nSELECT ");
1209 strPrintfArray(pSql
, ", ", "%s", 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. */
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
1235 strPrintf(pSql
, ", '");
1236 strPrintfArray(pSql
, "", ".", azCol
, nPK
);
1237 strPrintf(pSql
, "' ||\n");
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 */
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. */
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
);
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. */
1311 fprintf(out
, "%s\n", ct
.z
);
1315 /* Output the first part of the INSERT statement */
1316 fprintf(out
, "%s", insert
.z
);
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
));
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
++){
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
);
1344 aDelta
= sqlite3_malloc(nFinal
+ 60);
1345 nDelta
= rbuDeltaCreate(aSrc
, nSrc
, aFinal
, nFinal
, aDelta
);
1346 if( nDelta
<nFinal
){
1349 for(j
=0; j
<nDelta
; j
++) fprintf(out
, "%02x", (u8
)aDelta
[j
]);
1351 zOtaControl
[i
-bOtaRowid
] = 'f';
1354 sqlite3_free(aDelta
);
1358 printQuoted(out
, sqlite3_column_value(pStmt
, i
));
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
);
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
);
1384 ** Display a summary of differences between two versions of the same
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 */
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);
1427 for(n
=0; az
[n
]; n
++){
1428 if( sqlite3_stricmp(az
[n
],az2
[n
])!=0 ) break;
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(*)");
1445 strPrintf(&sql
, ", 0\n");
1448 for(i
=nPk
; az
[i
]; i
++){
1449 strPrintf(&sql
, "%sA.%s IS NOT B.%s", zSep
, az
[i
], az
[i
]);
1452 strPrintf(&sql
, ")\n");
1454 strPrintf(&sql
, " FROM main.%s A, aux.%s B\n", zId
, zId
);
1456 for(i
=0; i
<nPk
; i
++){
1457 strPrintf(&sql
, "%s A.%s=B.%s", zSep
, az
[i
], az
[i
]);
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
);
1465 for(i
=0; i
<nPk
; i
++){
1466 strPrintf(&sql
, "%s A.%s=B.%s", zSep
, az
[i
], az
[i
]);
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
);
1475 for(i
=0; i
<nPk
; i
++){
1476 strPrintf(&sql
, "%s A.%s=B.%s", zSep
, az
[i
], az
[i
]);
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
);
1492 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
1493 switch( sqlite3_column_int(pStmt
,0) ){
1495 nUpdate
= sqlite3_column_int64(pStmt
,2);
1496 nUnchanged
= sqlite3_column_int64(pStmt
,1) - nUpdate
;
1499 nDelete
= sqlite3_column_int64(pStmt
,1);
1502 nInsert
= sqlite3_column_int64(pStmt
,1);
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
:
1519 ** Write a 64-bit signed integer as a varint onto out
1521 static void putsVarint(FILE *out
, sqlite3_uint64 v
){
1523 unsigned char p
[12];
1524 if( v
& (((sqlite3_uint64
)0xff000000)<<32) ){
1525 p
[8] = (unsigned char)v
;
1527 for(i
=7; i
>=0; i
--){
1528 p
[i
] = (unsigned char)((v
& 0x7f) | 0x80);
1531 fwrite(p
, 8, 1, out
);
1535 p
[n
--] = (unsigned char)((v
& 0x7f) | 0x80);
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
);
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
);
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
);
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
);
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
);
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
);
1599 pStmt
= db_prepare("PRAGMA main.table_info=%Q", zTab
);
1600 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
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);
1611 aiPk
= sqlite3_realloc(aiPk
, sizeof(int)*nPk
);
1612 if( aiPk
==0 ) runtimeError("out of memory");
1617 sqlite3_finalize(pStmt
);
1618 if( nPk
==0 ) goto end_changeset_one_table
;
1620 strPrintf(&sql
, "SELECT %d", SQLITE_UPDATE
);
1621 for(i
=0; i
<nCol
; i
++){
1623 strPrintf(&sql
, ",\n A.%s", azCol
[i
]);
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
);
1631 for(i
=0; i
<nPk
; i
++){
1632 strPrintf(&sql
, "%s A.%s=B.%s", zSep
, azCol
[aiPk
[i
]], azCol
[aiPk
[i
]]);
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
]);
1641 strPrintf(&sql
,")\n UNION ALL\n");
1643 strPrintf(&sql
, "SELECT %d", SQLITE_DELETE
);
1644 for(i
=0; i
<nCol
; i
++){
1646 strPrintf(&sql
, ",\n A.%s", azCol
[i
]);
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
);
1654 for(i
=0; i
<nPk
; i
++){
1655 strPrintf(&sql
, "%s A.%s=B.%s", zSep
, azCol
[aiPk
[i
]], azCol
[aiPk
[i
]]);
1658 strPrintf(&sql
, ")\n UNION ALL\n");
1659 strPrintf(&sql
, "SELECT %d", SQLITE_INSERT
);
1660 for(i
=0; i
<nCol
; i
++){
1662 strPrintf(&sql
, ",\n B.%s", azCol
[i
]);
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
);
1670 for(i
=0; i
<nPk
; i
++){
1671 strPrintf(&sql
, "%s A.%s=B.%s", zSep
, azCol
[aiPk
[i
]], azCol
[aiPk
[i
]]);
1674 strPrintf(&sql
, ")\n");
1675 strPrintf(&sql
, " ORDER BY");
1677 for(i
=0; i
<nPk
; i
++){
1678 strPrintf(&sql
, "%s %d", zSep
, aiPk
[i
]+2);
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
;
1689 putsVarint(out
, (sqlite3_uint64
)nCol
);
1690 for(i
=0; i
<nCol
; i
++) putc(aiFlg
[i
], out
);
1691 fwrite(zTab
, 1, strlen(zTab
), out
);
1694 pStmt
= db_prepare("%s", sql
.z
);
1695 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
1696 int iType
= sqlite3_column_int(pStmt
,0);
1699 switch( sqlite3_column_int(pStmt
,0) ){
1700 case SQLITE_UPDATE
: {
1701 for(k
=1, i
=0; i
<nCol
; i
++){
1703 putValue(out
, pStmt
, k
);
1705 }else if( sqlite3_column_int(pStmt
,k
) ){
1706 putValue(out
, pStmt
, k
+1);
1713 for(k
=1, i
=0; i
<nCol
; i
++){
1717 }else if( sqlite3_column_int(pStmt
,k
) ){
1718 putValue(out
, pStmt
, k
+2);
1727 case SQLITE_INSERT
: {
1728 for(k
=1, i
=0; i
<nCol
; i
++){
1730 putValue(out
, pStmt
, k
);
1733 putValue(out
, pStmt
, k
+2);
1739 case SQLITE_DELETE
: {
1740 for(k
=1, i
=0; i
<nCol
; i
++){
1742 putValue(out
, pStmt
, k
);
1745 putValue(out
, pStmt
, k
+1);
1753 sqlite3_finalize(pStmt
);
1755 end_changeset_one_table
:
1756 while( nCol
>0 ) sqlite3_free(azCol
[--nCol
]);
1757 sqlite3_free(azCol
);
1760 sqlite3_free(aiFlg
);
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
;
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
++;
1787 case '"': q
= '"'; break;
1788 case '\'': q
= '\''; break;
1789 case '`': q
= '`'; break;
1790 case '[': q
= ']'; break;
1795 while( *p
&& pOut
<pEnd
){
1800 if( pOut
<pEnd
) *pOut
++ = *p
;
1804 while( *p
&& !is_whitespace(*p
) && *p
!='(' ){
1805 if( pOut
<pEnd
) *pOut
++ = *p
;
1815 ** This function is the implementation of SQL scalar function "module_name":
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
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
){
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');"
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
);
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"
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"
1901 "SELECT name FROM main.sqlite_schema\n"
1902 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1904 "SELECT name FROM aux.sqlite_schema\n"
1905 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1911 ** Print sketchy documentation for this utility program
1913 static void showHelp(void){
1914 printf("Usage: %s [options] DB1 DB2\n", g
.zArgv0
);
1916 "Output SQL text that would transform DB1 into DB2.\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;
1938 sqlite3_stmt
*pStmt
;
1941 void (*xDiff
)(const char*,FILE*) = diff_one_table
;
1942 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1946 int useTransaction
= 0;
1947 int neverUseTransaction
= 0;
1950 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD
);
1951 for(i
=1; i
<argc
; i
++){
1952 const char *z
= argv
[i
];
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;
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);
1967 if( strcmp(z
,"help")==0 ){
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
];
1979 if( strcmp(z
,"primarykey")==0 ){
1982 if( strcmp(z
,"rbu")==0 ){
1983 xDiff
= rbudiff_one_table
;
1985 if( strcmp(z
,"schema")==0 ){
1988 if( strcmp(z
,"summary")==0 ){
1989 xDiff
= summarize_one_table
;
1991 if( strcmp(z
,"table")==0 ){
1992 if( i
==argc
-1 ) cmdlineError("missing argument to %s", argv
[i
]);
1995 sqlite3_stricmp(zTab
, "sqlite_schema")==0
1996 || sqlite3_stricmp(zTab
, "sqlite_master")==0;
1998 if( strcmp(z
,"transaction")==0 ){
2001 if( strcmp(z
,"vtab")==0 ){
2005 cmdlineError("unknown option: %s", argv
[i
]);
2007 }else if( zDb1
==0 ){
2009 }else if( zDb2
==0 ){
2012 cmdlineError("unknown argument: %s", argv
[i
]);
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
);
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
);
2039 zSql
= sqlite3_mprintf("ATTACH %Q as aux;", zDb2
);
2040 rc
= sqlite3_exec(g
.db
, zSql
, 0, 0, &zErrMsg
);
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) "
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
);