blob: 9bd2c446fe484a1c544ee46c874e095fc883787f [file] [log] [blame]
drhd62c0f42015-04-09 13:34:29 +00001/*
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.
10**
11*************************************************************************
12**
drh50be9c42015-04-17 12:16:09 +000013** This is a utility program that computes the differences in content
drhd62c0f42015-04-09 13:34:29 +000014** between two SQLite databases.
drh50be9c42015-04-17 12:16:09 +000015**
16** To compile, simply link against SQLite.
17**
18** See the showHelp() routine below for a brief description of how to
19** run the utility.
drhd62c0f42015-04-09 13:34:29 +000020*/
21#include <stdio.h>
22#include <stdlib.h>
23#include <stdarg.h>
24#include <ctype.h>
25#include <string.h>
dana9ca8af2015-07-31 19:52:03 +000026#include <assert.h>
drhd62c0f42015-04-09 13:34:29 +000027#include "sqlite3.h"
28
29/*
30** All global variables are gathered into the "g" singleton.
31*/
32struct GlobalVars {
33 const char *zArgv0; /* Name of program */
34 int bSchemaOnly; /* Only show schema differences */
drha37591c2015-04-09 18:14:03 +000035 int bSchemaPK; /* Use the schema-defined PK, not the true PK */
dan9c987a82016-06-21 10:34:41 +000036 int bHandleVtab; /* Handle fts3, fts4, fts5 and rtree vtabs */
drhd62c0f42015-04-09 13:34:29 +000037 unsigned fDebug; /* Debug flags */
larrybra933ec42021-09-07 19:04:42 +000038 int bSchemaCompare; /* Doing single-table sqlite_schema compare */
drhd62c0f42015-04-09 13:34:29 +000039 sqlite3 *db; /* The database connection */
40} g;
41
42/*
43** Allowed values for g.fDebug
44*/
45#define DEBUG_COLUMN_NAMES 0x000001
46#define DEBUG_DIFF_SQL 0x000002
47
48/*
49** Dynamic string object
50*/
51typedef struct Str Str;
52struct Str {
53 char *z; /* Text of the string */
54 int nAlloc; /* Bytes allocated in z[] */
55 int nUsed; /* Bytes actually used in z[] */
56};
57
58/*
59** Initialize a Str object
60*/
61static void strInit(Str *p){
62 p->z = 0;
63 p->nAlloc = 0;
64 p->nUsed = 0;
65}
66
67/*
68** Print an error resulting from faulting command-line arguments and
69** abort the program.
70*/
71static 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);
79}
80
81/*
82** Print an error message for an error that occurs at runtime, then
83** abort the program.
84*/
85static 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);
93}
94
95/*
96** Free all memory held by a Str object
97*/
98static void strFree(Str *p){
99 sqlite3_free(p->z);
100 strInit(p);
101}
102
103/*
104** Add formatted text to the end of a Str object
105*/
106static 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;
117 }
118 if( p->nUsed+nNew < p->nAlloc-1 ){
119 p->nUsed += nNew;
120 break;
121 }
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");
125 }
126}
127
128
129
130/* Safely quote an SQL identifier. Use the minimum amount of transformation
131** necessary to allow the string to be used with %s.
132**
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.
136*/
137static char *safeId(const char *zId){
drhfc0ec3e2018-04-25 19:02:48 +0000138 int i, x;
139 char c;
drh06db66f2015-11-29 21:46:19 +0000140 if( zId[0]==0 ) return sqlite3_mprintf("\"\"");
drhd62c0f42015-04-09 13:34:29 +0000141 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);
147 }
148 }
149 }
drhfc0ec3e2018-04-25 19:02:48 +0000150 if( x || !sqlite3_keyword_check(zId,i) ){
151 return sqlite3_mprintf("%s", zId);
drhd62c0f42015-04-09 13:34:29 +0000152 }
drhfc0ec3e2018-04-25 19:02:48 +0000153 return sqlite3_mprintf("\"%w\"", zId);
drhd62c0f42015-04-09 13:34:29 +0000154}
155
156/*
157** Prepare a new SQL statement. Print an error and abort if anything
158** goes wrong.
159*/
160static sqlite3_stmt *db_vprepare(const char *zFormat, va_list ap){
161 char *zSql;
162 int rc;
163 sqlite3_stmt *pStmt;
164
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);
171 }
172 sqlite3_free(zSql);
173 return pStmt;
174}
175static 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;
182}
183
184/*
185** Free a list of strings
186*/
187static 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);
192 }
193}
194
195/*
larrybra933ec42021-09-07 19:04:42 +0000196** Return a list of column names [a] for the table zDb.zTab. Space to
drh39b355c2015-04-09 13:40:18 +0000197** hold the list is obtained from sqlite3_malloc() and should released
198** using namelistFree() when no longer needed.
drhd62c0f42015-04-09 13:34:29 +0000199**
drha37591c2015-04-09 18:14:03 +0000200** Primary key columns are listed first, followed by data columns.
201** The number of columns in the primary key is returned in *pnPkey.
drhd62c0f42015-04-09 13:34:29 +0000202**
drha37591c2015-04-09 18:14:03 +0000203** Normally, 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.
209**
210** If the primary key for a table is the rowid but rowid is inaccessible,
drhd62c0f42015-04-09 13:34:29 +0000211** then this routine returns a NULL pointer.
212**
larrybra933ec42021-09-07 19:04:42 +0000213** [a. If the named table is sqlite_schema, omits the "rootpage" column.]
214
drhd62c0f42015-04-09 13:34:29 +0000215** Examples:
216** CREATE TABLE t1(a INT UNIQUE, b INTEGER, c TEXT, PRIMARY KEY(c));
217** *pnPKey = 1;
drha37591c2015-04-09 18:14:03 +0000218** az = { "rowid", "a", "b", "c", 0 } // Normal case
219** az = { "c", "a", "b", 0 } // g.bSchemaPK==1
drhd62c0f42015-04-09 13:34:29 +0000220**
221** CREATE TABLE t2(a INT UNIQUE, b INTEGER, c TEXT, PRIMARY KEY(b));
222** *pnPKey = 1;
223** az = { "b", "a", "c", 0 }
224**
225** CREATE TABLE t3(x,y,z,PRIMARY KEY(y,z));
drha37591c2015-04-09 18:14:03 +0000226** *pnPKey = 1 // Normal case
227** az = { "rowid", "x", "y", "z", 0 } // Normal case
228** *pnPKey = 2 // g.bSchemaPK==1
229** az = { "y", "x", "z", 0 } // g.bSchemaPK==1
drhd62c0f42015-04-09 13:34:29 +0000230**
231** CREATE TABLE t4(x,y,z,PRIMARY KEY(y,z)) WITHOUT ROWID;
232** *pnPKey = 2
233** az = { "y", "z", "x", 0 }
234**
235** CREATE TABLE t5(rowid,_rowid_,oid);
236** az = 0 // The rowid is not accessible
237*/
dan99461852015-07-30 20:26:16 +0000238static char **columnNames(
239 const char *zDb, /* Database ("main" or "aux") to query */
240 const char *zTab, /* Name of table to return details of */
241 int *pnPKey, /* OUT: Number of PK columns */
242 int *pbRowid /* OUT: True if PK is an implicit rowid */
243){
drha37591c2015-04-09 18:14:03 +0000244 char **az = 0; /* List of column names to be returned */
245 int naz = 0; /* Number of entries in az[] */
246 sqlite3_stmt *pStmt; /* SQL statement being run */
drhd62c0f42015-04-09 13:34:29 +0000247 char *zPkIdxName = 0; /* Name of the PRIMARY KEY index */
drha37591c2015-04-09 18:14:03 +0000248 int truePk = 0; /* PRAGMA table_info indentifies the PK to use */
drhd62c0f42015-04-09 13:34:29 +0000249 int nPK = 0; /* Number of PRIMARY KEY columns */
drha37591c2015-04-09 18:14:03 +0000250 int i, j; /* Loop counters */
drhd62c0f42015-04-09 13:34:29 +0000251
drha37591c2015-04-09 18:14:03 +0000252 if( g.bSchemaPK==0 ){
253 /* Normal case: Figure out what the true primary key is for the table.
254 ** * For WITHOUT ROWID tables, the true primary key is the same as
255 ** the schema PRIMARY KEY, which is guaranteed to be present.
256 ** * For rowid tables with an INTEGER PRIMARY KEY, the true primary
257 ** key is the INTEGER PRIMARY KEY.
258 ** * For all other rowid tables, the rowid is the true primary key.
259 */
260 pStmt = db_prepare("PRAGMA %s.index_list=%Q", zDb, zTab);
drhd62c0f42015-04-09 13:34:29 +0000261 while( SQLITE_ROW==sqlite3_step(pStmt) ){
drha37591c2015-04-09 18:14:03 +0000262 if( sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,3),"pk")==0 ){
263 zPkIdxName = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
264 break;
265 }
drhd62c0f42015-04-09 13:34:29 +0000266 }
267 sqlite3_finalize(pStmt);
drha37591c2015-04-09 18:14:03 +0000268 if( zPkIdxName ){
269 int nKey = 0;
270 int nCol = 0;
271 truePk = 0;
272 pStmt = db_prepare("PRAGMA %s.index_xinfo=%Q", zDb, zPkIdxName);
273 while( SQLITE_ROW==sqlite3_step(pStmt) ){
274 nCol++;
275 if( sqlite3_column_int(pStmt,5) ){ nKey++; continue; }
276 if( sqlite3_column_int(pStmt,1)>=0 ) truePk = 1;
277 }
278 if( nCol==nKey ) truePk = 1;
279 if( truePk ){
280 nPK = nKey;
281 }else{
282 nPK = 1;
283 }
284 sqlite3_finalize(pStmt);
285 sqlite3_free(zPkIdxName);
286 }else{
287 truePk = 1;
288 nPK = 1;
289 }
290 pStmt = db_prepare("PRAGMA %s.table_info=%Q", zDb, zTab);
drhd62c0f42015-04-09 13:34:29 +0000291 }else{
drha37591c2015-04-09 18:14:03 +0000292 /* The g.bSchemaPK==1 case: Use whatever primary key is declared
293 ** in the schema. The "rowid" will still be used as the primary key
294 ** if the table definition does not contain a PRIMARY KEY.
295 */
296 nPK = 0;
297 pStmt = db_prepare("PRAGMA %s.table_info=%Q", zDb, zTab);
298 while( SQLITE_ROW==sqlite3_step(pStmt) ){
299 if( sqlite3_column_int(pStmt,5)>0 ) nPK++;
300 }
301 sqlite3_reset(pStmt);
302 if( nPK==0 ) nPK = 1;
drhd62c0f42015-04-09 13:34:29 +0000303 truePk = 1;
drhd62c0f42015-04-09 13:34:29 +0000304 }
305 *pnPKey = nPK;
306 naz = nPK;
307 az = sqlite3_malloc( sizeof(char*)*(nPK+1) );
308 if( az==0 ) runtimeError("out of memory");
309 memset(az, 0, sizeof(char*)*(nPK+1));
drhd62c0f42015-04-09 13:34:29 +0000310 while( SQLITE_ROW==sqlite3_step(pStmt) ){
larrybra933ec42021-09-07 19:04:42 +0000311 char * sid = safeId((char*)sqlite3_column_text(pStmt,1));
drhd62c0f42015-04-09 13:34:29 +0000312 int iPKey;
313 if( truePk && (iPKey = sqlite3_column_int(pStmt,5))>0 ){
larrybra933ec42021-09-07 19:04:42 +0000314 az[iPKey-1] = sid;
drhd62c0f42015-04-09 13:34:29 +0000315 }else{
larrybra933ec42021-09-07 19:04:42 +0000316 if( !g.bSchemaCompare || strcmp(sid,"rootpage")!=0 ){
317 az = sqlite3_realloc(az, sizeof(char*)*(naz+2) );
318 if( az==0 ) runtimeError("out of memory");
319 az[naz++] = sid;
320 }
drhd62c0f42015-04-09 13:34:29 +0000321 }
322 }
323 sqlite3_finalize(pStmt);
324 if( az ) az[naz] = 0;
dan99461852015-07-30 20:26:16 +0000325
326 /* If it is non-NULL, set *pbRowid to indicate whether or not the PK of
327 ** this table is an implicit rowid (*pbRowid==1) or not (*pbRowid==0). */
328 if( pbRowid ) *pbRowid = (az[0]==0);
329
330 /* If this table has an implicit rowid for a PK, figure out how to refer
larrybra933ec42021-09-07 19:04:42 +0000331 ** to it. There are usually three options - "rowid", "_rowid_" and "oid".
332 ** Any of these will work, unless the table has an explicit column of the
333 ** same name or the sqlite_schema tables are to be compared. In the latter
334 ** case, pretend that the "true" primary key is the name column, which
335 ** avoids extraneous diffs against the schemas due to rowid variance. */
drhd62c0f42015-04-09 13:34:29 +0000336 if( az[0]==0 ){
337 const char *azRowid[] = { "rowid", "_rowid_", "oid" };
larrybra933ec42021-09-07 19:04:42 +0000338 if( g.bSchemaCompare ){
339 az[0] = sqlite3_mprintf("%s", "name");
340 }else {
341 for(i=0; i<sizeof(azRowid)/sizeof(azRowid[0]); i++){
342 for(j=1; j<naz; j++){
343 if( sqlite3_stricmp(az[j], azRowid[i])==0 ) break;
344 }
345 if( j>=naz ){
346 az[0] = sqlite3_mprintf("%s", azRowid[i]);
347 break;
348 }
drhd62c0f42015-04-09 13:34:29 +0000349 }
350 }
351 if( az[0]==0 ){
352 for(i=1; i<naz; i++) sqlite3_free(az[i]);
353 sqlite3_free(az);
354 az = 0;
355 }
356 }
357 return az;
358}
359
360/*
361** Print the sqlite3_value X as an SQL literal.
362*/
drh8a1cd762015-04-14 19:01:08 +0000363static void printQuoted(FILE *out, sqlite3_value *X){
drhd62c0f42015-04-09 13:34:29 +0000364 switch( sqlite3_value_type(X) ){
365 case SQLITE_FLOAT: {
366 double r1;
367 char zBuf[50];
368 r1 = sqlite3_value_double(X);
369 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
drh8a1cd762015-04-14 19:01:08 +0000370 fprintf(out, "%s", zBuf);
drhd62c0f42015-04-09 13:34:29 +0000371 break;
372 }
373 case SQLITE_INTEGER: {
drh8a1cd762015-04-14 19:01:08 +0000374 fprintf(out, "%lld", sqlite3_value_int64(X));
drhd62c0f42015-04-09 13:34:29 +0000375 break;
376 }
377 case SQLITE_BLOB: {
378 const unsigned char *zBlob = sqlite3_value_blob(X);
379 int nBlob = sqlite3_value_bytes(X);
380 if( zBlob ){
381 int i;
drh8a1cd762015-04-14 19:01:08 +0000382 fprintf(out, "x'");
drhd62c0f42015-04-09 13:34:29 +0000383 for(i=0; i<nBlob; i++){
drh8a1cd762015-04-14 19:01:08 +0000384 fprintf(out, "%02x", zBlob[i]);
drhd62c0f42015-04-09 13:34:29 +0000385 }
drh8a1cd762015-04-14 19:01:08 +0000386 fprintf(out, "'");
drhd62c0f42015-04-09 13:34:29 +0000387 }else{
dan12c56aa2016-09-12 14:23:51 +0000388 /* Could be an OOM, could be a zero-byte blob */
389 fprintf(out, "X''");
drhd62c0f42015-04-09 13:34:29 +0000390 }
391 break;
392 }
393 case SQLITE_TEXT: {
394 const unsigned char *zArg = sqlite3_value_text(X);
drhd62c0f42015-04-09 13:34:29 +0000395
396 if( zArg==0 ){
drh8a1cd762015-04-14 19:01:08 +0000397 fprintf(out, "NULL");
drhd62c0f42015-04-09 13:34:29 +0000398 }else{
larrybr1ae057d2021-07-26 19:49:01 +0000399 int inctl = 0;
400 int i, j;
drh8a1cd762015-04-14 19:01:08 +0000401 fprintf(out, "'");
larrybr1ae057d2021-07-26 19:49:01 +0000402 for(i=j=0; zArg[i]; i++){
403 char c = zArg[i];
404 int ctl = iscntrl(c);
405 if( ctl>inctl ){
406 inctl = ctl;
407 fprintf(out, "%.*s'||X'%02x", i-j, &zArg[j], c);
408 j = i+1;
409 }else if( ctl ){
410 fprintf(out, "%02x", c);
411 j = i+1;
412 }else{
413 if( inctl ){
414 inctl = 0;
415 fprintf(out, "'\n||'");
416 }
417 if( c=='\'' ){
larrybre40875d2021-07-26 18:28:24 +0000418 fprintf(out, "%.*s'", i-j+1, &zArg[j]);
419 j = i+1;
420 }
421 }
larrybre40875d2021-07-26 18:28:24 +0000422 }
larrybr1ae057d2021-07-26 19:49:01 +0000423 fprintf(out, "%s'", &zArg[j]);
drhd62c0f42015-04-09 13:34:29 +0000424 }
425 break;
426 }
427 case SQLITE_NULL: {
drh8a1cd762015-04-14 19:01:08 +0000428 fprintf(out, "NULL");
drhd62c0f42015-04-09 13:34:29 +0000429 break;
430 }
431 }
432}
433
434/*
435** Output SQL that will recreate the aux.zTab table.
436*/
drh8a1cd762015-04-14 19:01:08 +0000437static void dump_table(const char *zTab, FILE *out){
drhd62c0f42015-04-09 13:34:29 +0000438 char *zId = safeId(zTab); /* Name of the table */
439 char **az = 0; /* List of columns */
440 int nPk; /* Number of true primary key columns */
441 int nCol; /* Number of data columns */
442 int i; /* Loop counter */
443 sqlite3_stmt *pStmt; /* SQL statement */
444 const char *zSep; /* Separator string */
445 Str ins; /* Beginning of the INSERT statement */
446
drh067b92b2020-06-19 15:24:12 +0000447 pStmt = db_prepare("SELECT sql FROM aux.sqlite_schema WHERE name=%Q", zTab);
drhd62c0f42015-04-09 13:34:29 +0000448 if( SQLITE_ROW==sqlite3_step(pStmt) ){
drh8a1cd762015-04-14 19:01:08 +0000449 fprintf(out, "%s;\n", sqlite3_column_text(pStmt,0));
drhd62c0f42015-04-09 13:34:29 +0000450 }
451 sqlite3_finalize(pStmt);
452 if( !g.bSchemaOnly ){
dan99461852015-07-30 20:26:16 +0000453 az = columnNames("aux", zTab, &nPk, 0);
drhd62c0f42015-04-09 13:34:29 +0000454 strInit(&ins);
455 if( az==0 ){
456 pStmt = db_prepare("SELECT * FROM aux.%s", zId);
457 strPrintf(&ins,"INSERT INTO %s VALUES", zId);
458 }else{
459 Str sql;
460 strInit(&sql);
461 zSep = "SELECT";
462 for(i=0; az[i]; i++){
463 strPrintf(&sql, "%s %s", zSep, az[i]);
464 zSep = ",";
465 }
466 strPrintf(&sql," FROM aux.%s", zId);
467 zSep = " ORDER BY";
468 for(i=1; i<=nPk; i++){
469 strPrintf(&sql, "%s %d", zSep, i);
470 zSep = ",";
471 }
472 pStmt = db_prepare("%s", sql.z);
473 strFree(&sql);
474 strPrintf(&ins, "INSERT INTO %s", zId);
475 zSep = "(";
476 for(i=0; az[i]; i++){
477 strPrintf(&ins, "%s%s", zSep, az[i]);
478 zSep = ",";
479 }
480 strPrintf(&ins,") VALUES");
481 namelistFree(az);
482 }
483 nCol = sqlite3_column_count(pStmt);
484 while( SQLITE_ROW==sqlite3_step(pStmt) ){
drh8a1cd762015-04-14 19:01:08 +0000485 fprintf(out, "%s",ins.z);
drhd62c0f42015-04-09 13:34:29 +0000486 zSep = "(";
487 for(i=0; i<nCol; i++){
drh8a1cd762015-04-14 19:01:08 +0000488 fprintf(out, "%s",zSep);
489 printQuoted(out, sqlite3_column_value(pStmt,i));
drhd62c0f42015-04-09 13:34:29 +0000490 zSep = ",";
491 }
drh8a1cd762015-04-14 19:01:08 +0000492 fprintf(out, ");\n");
drhd62c0f42015-04-09 13:34:29 +0000493 }
494 sqlite3_finalize(pStmt);
495 strFree(&ins);
496 } /* endif !g.bSchemaOnly */
drh067b92b2020-06-19 15:24:12 +0000497 pStmt = db_prepare("SELECT sql FROM aux.sqlite_schema"
drhd62c0f42015-04-09 13:34:29 +0000498 " WHERE type='index' AND tbl_name=%Q AND sql IS NOT NULL",
499 zTab);
500 while( SQLITE_ROW==sqlite3_step(pStmt) ){
drh8a1cd762015-04-14 19:01:08 +0000501 fprintf(out, "%s;\n", sqlite3_column_text(pStmt,0));
drhd62c0f42015-04-09 13:34:29 +0000502 }
503 sqlite3_finalize(pStmt);
danaff1a572020-11-17 21:09:56 +0000504 sqlite3_free(zId);
drhd62c0f42015-04-09 13:34:29 +0000505}
506
507
508/*
larrybra933ec42021-09-07 19:04:42 +0000509** Compute all differences for a single table, except if the
510** table name is sqlite_schema, ignore the rootpage column.
drhd62c0f42015-04-09 13:34:29 +0000511*/
drh8a1cd762015-04-14 19:01:08 +0000512static void diff_one_table(const char *zTab, FILE *out){
drhd62c0f42015-04-09 13:34:29 +0000513 char *zId = safeId(zTab); /* Name of table (translated for us in SQL) */
514 char **az = 0; /* Columns in main */
515 char **az2 = 0; /* Columns in aux */
516 int nPk; /* Primary key columns in main */
517 int nPk2; /* Primary key columns in aux */
drhb3f3d642015-04-25 18:39:21 +0000518 int n = 0; /* Number of columns in main */
drhd62c0f42015-04-09 13:34:29 +0000519 int n2; /* Number of columns in aux */
520 int nQ; /* Number of output columns in the diff query */
521 int i; /* Loop counter */
522 const char *zSep; /* Separator string */
523 Str sql; /* Comparison query */
524 sqlite3_stmt *pStmt; /* Query statement to do the diff */
larrybra933ec42021-09-07 19:04:42 +0000525 const char *zLead = /* Becomes line-comment for sqlite_schema */
526 (g.bSchemaCompare)? "-- " : "";
drhd62c0f42015-04-09 13:34:29 +0000527
528 strInit(&sql);
529 if( g.fDebug==DEBUG_COLUMN_NAMES ){
530 /* Simply run columnNames() on all tables of the origin
531 ** database and show the results. This is used for testing
532 ** and debugging of the columnNames() function.
533 */
dan99461852015-07-30 20:26:16 +0000534 az = columnNames("aux",zTab, &nPk, 0);
drhd62c0f42015-04-09 13:34:29 +0000535 if( az==0 ){
536 printf("Rowid not accessible for %s\n", zId);
537 }else{
538 printf("%s:", zId);
539 for(i=0; az[i]; i++){
540 printf(" %s", az[i]);
541 if( i+1==nPk ) printf(" *");
542 }
543 printf("\n");
544 }
545 goto end_diff_one_table;
546 }
drhd62c0f42015-04-09 13:34:29 +0000547
548 if( sqlite3_table_column_metadata(g.db,"aux",zTab,0,0,0,0,0,0) ){
549 if( !sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
550 /* Table missing from second database. */
larrybra933ec42021-09-07 19:04:42 +0000551 if( g.bSchemaCompare )
552 fprintf(out, "-- 2nd DB has no %s table\n", zTab);
553 else
554 fprintf(out, "DROP TABLE %s;\n", zId);
drhd62c0f42015-04-09 13:34:29 +0000555 }
556 goto end_diff_one_table;
557 }
558
559 if( sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
560 /* Table missing from source */
larrybra933ec42021-09-07 19:04:42 +0000561 if( g.bSchemaCompare )
562 fprintf(out, "-- 1st DB has no %s table\n", zTab);
563 else
564 dump_table(zTab, out);
drhd62c0f42015-04-09 13:34:29 +0000565 goto end_diff_one_table;
566 }
567
dan99461852015-07-30 20:26:16 +0000568 az = columnNames("main", zTab, &nPk, 0);
569 az2 = columnNames("aux", zTab, &nPk2, 0);
drhd62c0f42015-04-09 13:34:29 +0000570 if( az && az2 ){
drhedd22602015-11-07 18:32:17 +0000571 for(n=0; az[n] && az2[n]; n++){
drhd62c0f42015-04-09 13:34:29 +0000572 if( sqlite3_stricmp(az[n],az2[n])!=0 ) break;
573 }
574 }
575 if( az==0
576 || az2==0
577 || nPk!=nPk2
578 || az[n]
579 ){
580 /* Schema mismatch */
larrybra933ec42021-09-07 19:04:42 +0000581 fprintf(out, "%sDROP TABLE %s; -- due to schema mismatch\n", zLead, zId);
drh8a1cd762015-04-14 19:01:08 +0000582 dump_table(zTab, out);
drhd62c0f42015-04-09 13:34:29 +0000583 goto end_diff_one_table;
584 }
585
586 /* Build the comparison query */
drhedd22602015-11-07 18:32:17 +0000587 for(n2=n; az2[n2]; n2++){
588 fprintf(out, "ALTER TABLE %s ADD COLUMN %s;\n", zId, safeId(az2[n2]));
589 }
drhd62c0f42015-04-09 13:34:29 +0000590 nQ = nPk2+1+2*(n2-nPk2);
591 if( n2>nPk2 ){
592 zSep = "SELECT ";
593 for(i=0; i<nPk; i++){
594 strPrintf(&sql, "%sB.%s", zSep, az[i]);
595 zSep = ", ";
596 }
597 strPrintf(&sql, ", 1%s -- changed row\n", nPk==n ? "" : ",");
598 while( az[i] ){
599 strPrintf(&sql, " A.%s IS NOT B.%s, B.%s%s\n",
drhedd22602015-11-07 18:32:17 +0000600 az[i], az2[i], az2[i], az2[i+1]==0 ? "" : ",");
601 i++;
602 }
603 while( az2[i] ){
604 strPrintf(&sql, " B.%s IS NOT NULL, B.%s%s\n",
605 az2[i], az2[i], az2[i+1]==0 ? "" : ",");
drhd62c0f42015-04-09 13:34:29 +0000606 i++;
607 }
608 strPrintf(&sql, " FROM main.%s A, aux.%s B\n", zId, zId);
609 zSep = " WHERE";
610 for(i=0; i<nPk; i++){
611 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
612 zSep = " AND";
613 }
614 zSep = "\n AND (";
615 while( az[i] ){
616 strPrintf(&sql, "%sA.%s IS NOT B.%s%s\n",
drhedd22602015-11-07 18:32:17 +0000617 zSep, az[i], az2[i], az2[i+1]==0 ? ")" : "");
618 zSep = " OR ";
619 i++;
620 }
621 while( az2[i] ){
622 strPrintf(&sql, "%sB.%s IS NOT NULL%s\n",
623 zSep, az2[i], az2[i+1]==0 ? ")" : "");
drhd62c0f42015-04-09 13:34:29 +0000624 zSep = " OR ";
625 i++;
626 }
627 strPrintf(&sql, " UNION ALL\n");
628 }
629 zSep = "SELECT ";
630 for(i=0; i<nPk; i++){
631 strPrintf(&sql, "%sA.%s", zSep, az[i]);
632 zSep = ", ";
633 }
634 strPrintf(&sql, ", 2%s -- deleted row\n", nPk==n ? "" : ",");
drhedd22602015-11-07 18:32:17 +0000635 while( az2[i] ){
drhd62c0f42015-04-09 13:34:29 +0000636 strPrintf(&sql, " NULL, NULL%s\n", i==n2-1 ? "" : ",");
637 i++;
638 }
639 strPrintf(&sql, " FROM main.%s A\n", zId);
640 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B\n", zId);
641 zSep = " WHERE";
642 for(i=0; i<nPk; i++){
643 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
644 zSep = " AND";
645 }
646 strPrintf(&sql, ")\n");
647 zSep = " UNION ALL\nSELECT ";
648 for(i=0; i<nPk; i++){
649 strPrintf(&sql, "%sB.%s", zSep, az[i]);
650 zSep = ", ";
651 }
652 strPrintf(&sql, ", 3%s -- inserted row\n", nPk==n ? "" : ",");
653 while( az2[i] ){
drhedd22602015-11-07 18:32:17 +0000654 strPrintf(&sql, " 1, B.%s%s\n", az2[i], az2[i+1]==0 ? "" : ",");
drhd62c0f42015-04-09 13:34:29 +0000655 i++;
656 }
657 strPrintf(&sql, " FROM aux.%s B\n", zId);
658 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A\n", zId);
659 zSep = " WHERE";
660 for(i=0; i<nPk; i++){
661 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
662 zSep = " AND";
663 }
664 strPrintf(&sql, ")\n ORDER BY");
665 zSep = " ";
666 for(i=1; i<=nPk; i++){
667 strPrintf(&sql, "%s%d", zSep, i);
668 zSep = ", ";
669 }
670 strPrintf(&sql, ";\n");
671
672 if( g.fDebug & DEBUG_DIFF_SQL ){
673 printf("SQL for %s:\n%s\n", zId, sql.z);
674 goto end_diff_one_table;
675 }
676
677 /* Drop indexes that are missing in the destination */
678 pStmt = db_prepare(
drh067b92b2020-06-19 15:24:12 +0000679 "SELECT name FROM main.sqlite_schema"
drhd62c0f42015-04-09 13:34:29 +0000680 " WHERE type='index' AND tbl_name=%Q"
681 " AND sql IS NOT NULL"
drh067b92b2020-06-19 15:24:12 +0000682 " AND sql NOT IN (SELECT sql FROM aux.sqlite_schema"
drhd62c0f42015-04-09 13:34:29 +0000683 " WHERE type='index' AND tbl_name=%Q"
684 " AND sql IS NOT NULL)",
685 zTab, zTab);
686 while( SQLITE_ROW==sqlite3_step(pStmt) ){
687 char *z = safeId((const char*)sqlite3_column_text(pStmt,0));
drh8a1cd762015-04-14 19:01:08 +0000688 fprintf(out, "DROP INDEX %s;\n", z);
drhd62c0f42015-04-09 13:34:29 +0000689 sqlite3_free(z);
690 }
691 sqlite3_finalize(pStmt);
692
693 /* Run the query and output differences */
694 if( !g.bSchemaOnly ){
drh52254492016-07-08 02:14:24 +0000695 pStmt = db_prepare("%s", sql.z);
drhd62c0f42015-04-09 13:34:29 +0000696 while( SQLITE_ROW==sqlite3_step(pStmt) ){
697 int iType = sqlite3_column_int(pStmt, nPk);
698 if( iType==1 || iType==2 ){
699 if( iType==1 ){ /* Change the content of a row */
larrybra933ec42021-09-07 19:04:42 +0000700 fprintf(out, "%sUPDATE %s", zLead, zId);
drhd62c0f42015-04-09 13:34:29 +0000701 zSep = " SET";
702 for(i=nPk+1; i<nQ; i+=2){
703 if( sqlite3_column_int(pStmt,i)==0 ) continue;
drh8a1cd762015-04-14 19:01:08 +0000704 fprintf(out, "%s %s=", zSep, az2[(i+nPk-1)/2]);
drhd62c0f42015-04-09 13:34:29 +0000705 zSep = ",";
drh8a1cd762015-04-14 19:01:08 +0000706 printQuoted(out, sqlite3_column_value(pStmt,i+1));
drhd62c0f42015-04-09 13:34:29 +0000707 }
708 }else{ /* Delete a row */
larrybra933ec42021-09-07 19:04:42 +0000709 fprintf(out, "%sDELETE FROM %s", zLead, zId);
drhd62c0f42015-04-09 13:34:29 +0000710 }
711 zSep = " WHERE";
712 for(i=0; i<nPk; i++){
drh8a1cd762015-04-14 19:01:08 +0000713 fprintf(out, "%s %s=", zSep, az2[i]);
714 printQuoted(out, sqlite3_column_value(pStmt,i));
drh74504942015-11-09 12:47:04 +0000715 zSep = " AND";
drhd62c0f42015-04-09 13:34:29 +0000716 }
drh8a1cd762015-04-14 19:01:08 +0000717 fprintf(out, ";\n");
drhd62c0f42015-04-09 13:34:29 +0000718 }else{ /* Insert a row */
larrybra933ec42021-09-07 19:04:42 +0000719 fprintf(out, "%sINSERT INTO %s(%s", zLead, zId, az2[0]);
drh8a1cd762015-04-14 19:01:08 +0000720 for(i=1; az2[i]; i++) fprintf(out, ",%s", az2[i]);
721 fprintf(out, ") VALUES");
drhd62c0f42015-04-09 13:34:29 +0000722 zSep = "(";
723 for(i=0; i<nPk2; i++){
drh8a1cd762015-04-14 19:01:08 +0000724 fprintf(out, "%s", zSep);
drhd62c0f42015-04-09 13:34:29 +0000725 zSep = ",";
drh8a1cd762015-04-14 19:01:08 +0000726 printQuoted(out, sqlite3_column_value(pStmt,i));
drhd62c0f42015-04-09 13:34:29 +0000727 }
728 for(i=nPk2+2; i<nQ; i+=2){
drh8a1cd762015-04-14 19:01:08 +0000729 fprintf(out, ",");
730 printQuoted(out, sqlite3_column_value(pStmt,i));
drhd62c0f42015-04-09 13:34:29 +0000731 }
drh8a1cd762015-04-14 19:01:08 +0000732 fprintf(out, ");\n");
drhd62c0f42015-04-09 13:34:29 +0000733 }
734 }
735 sqlite3_finalize(pStmt);
736 } /* endif !g.bSchemaOnly */
737
738 /* Create indexes that are missing in the source */
739 pStmt = db_prepare(
drh067b92b2020-06-19 15:24:12 +0000740 "SELECT sql FROM aux.sqlite_schema"
drhd62c0f42015-04-09 13:34:29 +0000741 " WHERE type='index' AND tbl_name=%Q"
742 " AND sql IS NOT NULL"
drh067b92b2020-06-19 15:24:12 +0000743 " AND sql NOT IN (SELECT sql FROM main.sqlite_schema"
drhd62c0f42015-04-09 13:34:29 +0000744 " WHERE type='index' AND tbl_name=%Q"
745 " AND sql IS NOT NULL)",
746 zTab, zTab);
747 while( SQLITE_ROW==sqlite3_step(pStmt) ){
drh8a1cd762015-04-14 19:01:08 +0000748 fprintf(out, "%s;\n", sqlite3_column_text(pStmt,0));
drhd62c0f42015-04-09 13:34:29 +0000749 }
750 sqlite3_finalize(pStmt);
751
752end_diff_one_table:
753 strFree(&sql);
754 sqlite3_free(zId);
755 namelistFree(az);
756 namelistFree(az2);
757 return;
758}
759
760/*
dan99461852015-07-30 20:26:16 +0000761** Check that table zTab exists and has the same schema in both the "main"
762** and "aux" databases currently opened by the global db handle. If they
763** do not, output an error message on stderr and exit(1). Otherwise, if
764** the schemas do match, return control to the caller.
765*/
766static void checkSchemasMatch(const char *zTab){
767 sqlite3_stmt *pStmt = db_prepare(
drh067b92b2020-06-19 15:24:12 +0000768 "SELECT A.sql=B.sql FROM main.sqlite_schema A, aux.sqlite_schema B"
dan99461852015-07-30 20:26:16 +0000769 " WHERE A.name=%Q AND B.name=%Q", zTab, zTab
770 );
771 if( SQLITE_ROW==sqlite3_step(pStmt) ){
772 if( sqlite3_column_int(pStmt,0)==0 ){
773 runtimeError("schema changes for table %s", safeId(zTab));
774 }
775 }else{
776 runtimeError("table %s missing from one or both databases", safeId(zTab));
777 }
778 sqlite3_finalize(pStmt);
779}
780
dana9ca8af2015-07-31 19:52:03 +0000781/**************************************************************************
782** The following code is copied from fossil. It is used to generate the
783** fossil delta blobs sometimes used in RBU update records.
784*/
785
786typedef unsigned short u16;
787typedef unsigned int u32;
788typedef unsigned char u8;
789
790/*
791** The width of a hash window in bytes. The algorithm only works if this
792** is a power of 2.
793*/
794#define NHASH 16
795
796/*
797** The current state of the rolling hash.
798**
799** z[] holds the values that have been hashed. z[] is a circular buffer.
800** z[i] is the first entry and z[(i+NHASH-1)%NHASH] is the last entry of
801** the window.
802**
803** Hash.a is the sum of all elements of hash.z[]. Hash.b is a weighted
804** sum. Hash.b is z[i]*NHASH + z[i+1]*(NHASH-1) + ... + z[i+NHASH-1]*1.
805** (Each index for z[] should be module NHASH, of course. The %NHASH operator
806** is omitted in the prior expression for brevity.)
807*/
808typedef struct hash hash;
809struct hash {
810 u16 a, b; /* Hash values */
811 u16 i; /* Start of the hash window */
812 char z[NHASH]; /* The values that have been hashed */
813};
814
815/*
816** Initialize the rolling hash using the first NHASH characters of z[]
817*/
818static void hash_init(hash *pHash, const char *z){
819 u16 a, b, i;
820 a = b = 0;
821 for(i=0; i<NHASH; i++){
822 a += z[i];
823 b += (NHASH-i)*z[i];
824 pHash->z[i] = z[i];
825 }
826 pHash->a = a & 0xffff;
827 pHash->b = b & 0xffff;
828 pHash->i = 0;
829}
830
831/*
832** Advance the rolling hash by a single character "c"
833*/
834static void hash_next(hash *pHash, int c){
835 u16 old = pHash->z[pHash->i];
mistachkin1abbe282015-08-20 21:09:32 +0000836 pHash->z[pHash->i] = (char)c;
dana9ca8af2015-07-31 19:52:03 +0000837 pHash->i = (pHash->i+1)&(NHASH-1);
mistachkin1abbe282015-08-20 21:09:32 +0000838 pHash->a = pHash->a - old + (char)c;
dana9ca8af2015-07-31 19:52:03 +0000839 pHash->b = pHash->b - NHASH*old + pHash->a;
840}
841
842/*
843** Return a 32-bit hash value
844*/
845static u32 hash_32bit(hash *pHash){
846 return (pHash->a & 0xffff) | (((u32)(pHash->b & 0xffff))<<16);
847}
848
849/*
850** Write an base-64 integer into the given buffer.
851*/
852static void putInt(unsigned int v, char **pz){
853 static const char zDigits[] =
854 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~";
855 /* 123456789 123456789 123456789 123456789 123456789 123456789 123 */
856 int i, j;
857 char zBuf[20];
858 if( v==0 ){
859 *(*pz)++ = '0';
860 return;
861 }
862 for(i=0; v>0; i++, v>>=6){
863 zBuf[i] = zDigits[v&0x3f];
864 }
865 for(j=i-1; j>=0; j--){
866 *(*pz)++ = zBuf[j];
867 }
868}
869
870/*
dana9ca8af2015-07-31 19:52:03 +0000871** Return the number digits in the base-64 representation of a positive integer
872*/
873static int digit_count(int v){
874 unsigned int i, x;
mistachkin1abbe282015-08-20 21:09:32 +0000875 for(i=1, x=64; (unsigned int)v>=x; i++, x <<= 6){}
dana9ca8af2015-07-31 19:52:03 +0000876 return i;
877}
878
879/*
880** Compute a 32-bit checksum on the N-byte buffer. Return the result.
881*/
882static unsigned int checksum(const char *zIn, size_t N){
883 const unsigned char *z = (const unsigned char *)zIn;
884 unsigned sum0 = 0;
885 unsigned sum1 = 0;
886 unsigned sum2 = 0;
887 unsigned sum3 = 0;
888 while(N >= 16){
889 sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
890 sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
891 sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
892 sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
893 z += 16;
894 N -= 16;
895 }
896 while(N >= 4){
897 sum0 += z[0];
898 sum1 += z[1];
899 sum2 += z[2];
900 sum3 += z[3];
901 z += 4;
902 N -= 4;
903 }
904 sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
905 switch(N){
906 case 3: sum3 += (z[2] << 8);
907 case 2: sum3 += (z[1] << 16);
908 case 1: sum3 += (z[0] << 24);
909 default: ;
910 }
911 return sum3;
912}
913
914/*
915** Create a new delta.
916**
917** The delta is written into a preallocated buffer, zDelta, which
918** should be at least 60 bytes longer than the target file, zOut.
919** The delta string will be NUL-terminated, but it might also contain
920** embedded NUL characters if either the zSrc or zOut files are
921** binary. This function returns the length of the delta string
922** in bytes, excluding the final NUL terminator character.
923**
924** Output Format:
925**
926** The delta begins with a base64 number followed by a newline. This
927** number is the number of bytes in the TARGET file. Thus, given a
928** delta file z, a program can compute the size of the output file
929** simply by reading the first line and decoding the base-64 number
930** found there. The delta_output_size() routine does exactly this.
931**
932** After the initial size number, the delta consists of a series of
933** literal text segments and commands to copy from the SOURCE file.
934** A copy command looks like this:
935**
936** NNN@MMM,
937**
938** where NNN is the number of bytes to be copied and MMM is the offset
939** into the source file of the first byte (both base-64). If NNN is 0
940** it means copy the rest of the input file. Literal text is like this:
941**
942** NNN:TTTTT
943**
944** where NNN is the number of bytes of text (base-64) and TTTTT is the text.
945**
946** The last term is of the form
947**
948** NNN;
949**
950** In this case, NNN is a 32-bit bigendian checksum of the output file
951** that can be used to verify that the delta applied correctly. All
952** numbers are in base-64.
953**
954** Pure text files generate a pure text delta. Binary files generate a
955** delta that may contain some binary data.
956**
957** Algorithm:
958**
959** The encoder first builds a hash table to help it find matching
960** patterns in the source file. 16-byte chunks of the source file
961** sampled at evenly spaced intervals are used to populate the hash
962** table.
963**
964** Next we begin scanning the target file using a sliding 16-byte
965** window. The hash of the 16-byte window in the target is used to
966** search for a matching section in the source file. When a match
967** is found, a copy command is added to the delta. An effort is
968** made to extend the matching section to regions that come before
969** and after the 16-byte hash window. A copy command is only issued
970** if the result would use less space that just quoting the text
971** literally. Literal text is added to the delta for sections that
972** do not match or which can not be encoded efficiently using copy
973** commands.
974*/
975static int rbuDeltaCreate(
976 const char *zSrc, /* The source or pattern file */
977 unsigned int lenSrc, /* Length of the source file */
978 const char *zOut, /* The target file */
979 unsigned int lenOut, /* Length of the target file */
980 char *zDelta /* Write the delta into this buffer */
981){
mistachkin1abbe282015-08-20 21:09:32 +0000982 unsigned int i, base;
dana9ca8af2015-07-31 19:52:03 +0000983 char *zOrigDelta = zDelta;
984 hash h;
985 int nHash; /* Number of hash table entries */
986 int *landmark; /* Primary hash table */
987 int *collide; /* Collision chain */
988 int lastRead = -1; /* Last byte of zSrc read by a COPY command */
989
990 /* Add the target file size to the beginning of the delta
991 */
992 putInt(lenOut, &zDelta);
993 *(zDelta++) = '\n';
994
995 /* If the source file is very small, it means that we have no
996 ** chance of ever doing a copy command. Just output a single
997 ** literal segment for the entire target and exit.
998 */
999 if( lenSrc<=NHASH ){
1000 putInt(lenOut, &zDelta);
1001 *(zDelta++) = ':';
1002 memcpy(zDelta, zOut, lenOut);
1003 zDelta += lenOut;
1004 putInt(checksum(zOut, lenOut), &zDelta);
1005 *(zDelta++) = ';';
drh62e63bb2016-01-14 12:23:16 +00001006 return (int)(zDelta - zOrigDelta);
dana9ca8af2015-07-31 19:52:03 +00001007 }
1008
1009 /* Compute the hash table used to locate matching sections in the
1010 ** source file.
1011 */
1012 nHash = lenSrc/NHASH;
1013 collide = sqlite3_malloc( nHash*2*sizeof(int) );
1014 landmark = &collide[nHash];
1015 memset(landmark, -1, nHash*sizeof(int));
1016 memset(collide, -1, nHash*sizeof(int));
1017 for(i=0; i<lenSrc-NHASH; i+=NHASH){
1018 int hv;
1019 hash_init(&h, &zSrc[i]);
1020 hv = hash_32bit(&h) % nHash;
1021 collide[i/NHASH] = landmark[hv];
1022 landmark[hv] = i/NHASH;
1023 }
1024
1025 /* Begin scanning the target file and generating copy commands and
1026 ** literal sections of the delta.
1027 */
1028 base = 0; /* We have already generated everything before zOut[base] */
1029 while( base+NHASH<lenOut ){
1030 int iSrc, iBlock;
mistachkin1abbe282015-08-20 21:09:32 +00001031 int bestCnt, bestOfst=0, bestLitsz=0;
dana9ca8af2015-07-31 19:52:03 +00001032 hash_init(&h, &zOut[base]);
1033 i = 0; /* Trying to match a landmark against zOut[base+i] */
1034 bestCnt = 0;
1035 while( 1 ){
1036 int hv;
1037 int limit = 250;
1038
1039 hv = hash_32bit(&h) % nHash;
1040 iBlock = landmark[hv];
1041 while( iBlock>=0 && (limit--)>0 ){
1042 /*
1043 ** The hash window has identified a potential match against
1044 ** landmark block iBlock. But we need to investigate further.
1045 **
1046 ** Look for a region in zOut that matches zSrc. Anchor the search
1047 ** at zSrc[iSrc] and zOut[base+i]. Do not include anything prior to
1048 ** zOut[base] or after zOut[outLen] nor anything after zSrc[srcLen].
1049 **
1050 ** Set cnt equal to the length of the match and set ofst so that
1051 ** zSrc[ofst] is the first element of the match. litsz is the number
1052 ** of characters between zOut[base] and the beginning of the match.
1053 ** sz will be the overhead (in bytes) needed to encode the copy
1054 ** command. Only generate copy command if the overhead of the
1055 ** copy command is less than the amount of literal text to be copied.
1056 */
1057 int cnt, ofst, litsz;
1058 int j, k, x, y;
1059 int sz;
1060
1061 /* Beginning at iSrc, match forwards as far as we can. j counts
1062 ** the number of characters that match */
1063 iSrc = iBlock*NHASH;
mistachkin1abbe282015-08-20 21:09:32 +00001064 for(
1065 j=0, x=iSrc, y=base+i;
1066 (unsigned int)x<lenSrc && (unsigned int)y<lenOut;
1067 j++, x++, y++
1068 ){
dana9ca8af2015-07-31 19:52:03 +00001069 if( zSrc[x]!=zOut[y] ) break;
1070 }
1071 j--;
1072
1073 /* Beginning at iSrc-1, match backwards as far as we can. k counts
1074 ** the number of characters that match */
mistachkin1abbe282015-08-20 21:09:32 +00001075 for(k=1; k<iSrc && (unsigned int)k<=i; k++){
dana9ca8af2015-07-31 19:52:03 +00001076 if( zSrc[iSrc-k]!=zOut[base+i-k] ) break;
1077 }
1078 k--;
1079
1080 /* Compute the offset and size of the matching region */
1081 ofst = iSrc-k;
1082 cnt = j+k+1;
1083 litsz = i-k; /* Number of bytes of literal text before the copy */
1084 /* sz will hold the number of bytes needed to encode the "insert"
1085 ** command and the copy command, not counting the "insert" text */
1086 sz = digit_count(i-k)+digit_count(cnt)+digit_count(ofst)+3;
1087 if( cnt>=sz && cnt>bestCnt ){
1088 /* Remember this match only if it is the best so far and it
1089 ** does not increase the file size */
1090 bestCnt = cnt;
1091 bestOfst = iSrc-k;
1092 bestLitsz = litsz;
1093 }
1094
1095 /* Check the next matching block */
1096 iBlock = collide[iBlock];
1097 }
1098
1099 /* We have a copy command that does not cause the delta to be larger
1100 ** than a literal insert. So add the copy command to the delta.
1101 */
1102 if( bestCnt>0 ){
1103 if( bestLitsz>0 ){
1104 /* Add an insert command before the copy */
1105 putInt(bestLitsz,&zDelta);
1106 *(zDelta++) = ':';
1107 memcpy(zDelta, &zOut[base], bestLitsz);
1108 zDelta += bestLitsz;
1109 base += bestLitsz;
1110 }
1111 base += bestCnt;
1112 putInt(bestCnt, &zDelta);
1113 *(zDelta++) = '@';
1114 putInt(bestOfst, &zDelta);
1115 *(zDelta++) = ',';
1116 if( bestOfst + bestCnt -1 > lastRead ){
1117 lastRead = bestOfst + bestCnt - 1;
1118 }
1119 bestCnt = 0;
1120 break;
1121 }
1122
1123 /* If we reach this point, it means no match is found so far */
1124 if( base+i+NHASH>=lenOut ){
1125 /* We have reached the end of the file and have not found any
1126 ** matches. Do an "insert" for everything that does not match */
1127 putInt(lenOut-base, &zDelta);
1128 *(zDelta++) = ':';
1129 memcpy(zDelta, &zOut[base], lenOut-base);
1130 zDelta += lenOut-base;
1131 base = lenOut;
1132 break;
1133 }
1134
1135 /* Advance the hash by one character. Keep looking for a match */
1136 hash_next(&h, zOut[base+i+NHASH]);
1137 i++;
1138 }
1139 }
1140 /* Output a final "insert" record to get all the text at the end of
1141 ** the file that does not match anything in the source file.
1142 */
1143 if( base<lenOut ){
1144 putInt(lenOut-base, &zDelta);
1145 *(zDelta++) = ':';
1146 memcpy(zDelta, &zOut[base], lenOut-base);
1147 zDelta += lenOut-base;
1148 }
1149 /* Output the final checksum record. */
1150 putInt(checksum(zOut, lenOut), &zDelta);
1151 *(zDelta++) = ';';
1152 sqlite3_free(collide);
drh62e63bb2016-01-14 12:23:16 +00001153 return (int)(zDelta - zOrigDelta);
dana9ca8af2015-07-31 19:52:03 +00001154}
1155
1156/*
1157** End of code copied from fossil.
1158**************************************************************************/
1159
dan99461852015-07-30 20:26:16 +00001160static void strPrintfArray(
1161 Str *pStr, /* String object to append to */
1162 const char *zSep, /* Separator string */
1163 const char *zFmt, /* Format for each entry */
1164 char **az, int n /* Array of strings & its size (or -1) */
1165){
1166 int i;
1167 for(i=0; az[i] && (i<n || n<0); i++){
1168 if( i!=0 ) strPrintf(pStr, "%s", zSep);
1169 strPrintf(pStr, zFmt, az[i], az[i], az[i]);
1170 }
1171}
1172
1173static void getRbudiffQuery(
1174 const char *zTab,
1175 char **azCol,
1176 int nPK,
1177 int bOtaRowid,
1178 Str *pSql
1179){
1180 int i;
1181
1182 /* First the newly inserted rows: **/
1183 strPrintf(pSql, "SELECT ");
1184 strPrintfArray(pSql, ", ", "%s", azCol, -1);
dana9ca8af2015-07-31 19:52:03 +00001185 strPrintf(pSql, ", 0, "); /* Set ota_control to 0 for an insert */
1186 strPrintfArray(pSql, ", ", "NULL", azCol, -1);
dan99461852015-07-30 20:26:16 +00001187 strPrintf(pSql, " FROM aux.%Q AS n WHERE NOT EXISTS (\n", zTab);
1188 strPrintf(pSql, " SELECT 1 FROM ", zTab);
1189 strPrintf(pSql, " main.%Q AS o WHERE ", zTab);
dane5a0cfa2016-09-01 14:03:28 +00001190 strPrintfArray(pSql, " AND ", "(n.%Q = o.%Q)", azCol, nPK);
1191 strPrintf(pSql, "\n) AND ");
1192 strPrintfArray(pSql, " AND ", "(n.%Q IS NOT NULL)", azCol, nPK);
dan99461852015-07-30 20:26:16 +00001193
1194 /* Deleted rows: */
1195 strPrintf(pSql, "\nUNION ALL\nSELECT ");
1196 strPrintfArray(pSql, ", ", "%s", azCol, nPK);
dandd688e72015-07-31 15:13:29 +00001197 if( azCol[nPK] ){
1198 strPrintf(pSql, ", ");
1199 strPrintfArray(pSql, ", ", "NULL", &azCol[nPK], -1);
1200 }
dana9ca8af2015-07-31 19:52:03 +00001201 strPrintf(pSql, ", 1, "); /* Set ota_control to 1 for a delete */
1202 strPrintfArray(pSql, ", ", "NULL", azCol, -1);
dan99461852015-07-30 20:26:16 +00001203 strPrintf(pSql, " FROM main.%Q AS n WHERE NOT EXISTS (\n", zTab);
1204 strPrintf(pSql, " SELECT 1 FROM ", zTab);
1205 strPrintf(pSql, " aux.%Q AS o WHERE ", zTab);
dane5a0cfa2016-09-01 14:03:28 +00001206 strPrintfArray(pSql, " AND ", "(n.%Q = o.%Q)", azCol, nPK);
1207 strPrintf(pSql, "\n) AND ");
1208 strPrintfArray(pSql, " AND ", "(n.%Q IS NOT NULL)", azCol, nPK);
dan99461852015-07-30 20:26:16 +00001209
dandd688e72015-07-31 15:13:29 +00001210 /* Updated rows. If all table columns are part of the primary key, there
1211 ** can be no updates. In this case this part of the compound SELECT can
1212 ** be omitted altogether. */
1213 if( azCol[nPK] ){
1214 strPrintf(pSql, "\nUNION ALL\nSELECT ");
1215 strPrintfArray(pSql, ", ", "n.%s", azCol, nPK);
dan99461852015-07-30 20:26:16 +00001216 strPrintf(pSql, ",\n");
dandd688e72015-07-31 15:13:29 +00001217 strPrintfArray(pSql, " ,\n",
1218 " CASE WHEN n.%s IS o.%s THEN NULL ELSE n.%s END", &azCol[nPK], -1
1219 );
dan99461852015-07-30 20:26:16 +00001220
dandd688e72015-07-31 15:13:29 +00001221 if( bOtaRowid==0 ){
1222 strPrintf(pSql, ", '");
1223 strPrintfArray(pSql, "", ".", azCol, nPK);
1224 strPrintf(pSql, "' ||\n");
1225 }else{
1226 strPrintf(pSql, ",\n");
1227 }
1228 strPrintfArray(pSql, " ||\n",
1229 " CASE WHEN n.%s IS o.%s THEN '.' ELSE 'x' END", &azCol[nPK], -1
1230 );
dana9ca8af2015-07-31 19:52:03 +00001231 strPrintf(pSql, "\nAS ota_control, ");
1232 strPrintfArray(pSql, ", ", "NULL", azCol, nPK);
1233 strPrintf(pSql, ",\n");
1234 strPrintfArray(pSql, " ,\n",
1235 " CASE WHEN n.%s IS o.%s THEN NULL ELSE o.%s END", &azCol[nPK], -1
1236 );
dandd688e72015-07-31 15:13:29 +00001237
1238 strPrintf(pSql, "\nFROM main.%Q AS o, aux.%Q AS n\nWHERE ", zTab, zTab);
dane5a0cfa2016-09-01 14:03:28 +00001239 strPrintfArray(pSql, " AND ", "(n.%Q = o.%Q)", azCol, nPK);
dandd688e72015-07-31 15:13:29 +00001240 strPrintf(pSql, " AND ota_control LIKE '%%x%%'");
1241 }
dan99461852015-07-30 20:26:16 +00001242
1243 /* Now add an ORDER BY clause to sort everything by PK. */
1244 strPrintf(pSql, "\nORDER BY ");
1245 for(i=1; i<=nPK; i++) strPrintf(pSql, "%s%d", ((i>1)?", ":""), i);
1246}
1247
1248static void rbudiff_one_table(const char *zTab, FILE *out){
1249 int bOtaRowid; /* True to use an ota_rowid column */
1250 int nPK; /* Number of primary key columns in table */
1251 char **azCol; /* NULL terminated array of col names */
1252 int i;
1253 int nCol;
1254 Str ct = {0, 0, 0}; /* The "CREATE TABLE data_xxx" statement */
1255 Str sql = {0, 0, 0}; /* Query to find differences */
1256 Str insert = {0, 0, 0}; /* First part of output INSERT statement */
1257 sqlite3_stmt *pStmt = 0;
danfebfe022016-03-19 16:21:26 +00001258 int nRow = 0; /* Total rows in data_xxx table */
dan99461852015-07-30 20:26:16 +00001259
1260 /* --rbu mode must use real primary keys. */
1261 g.bSchemaPK = 1;
1262
1263 /* Check that the schemas of the two tables match. Exit early otherwise. */
1264 checkSchemasMatch(zTab);
1265
1266 /* Grab the column names and PK details for the table(s). If no usable PK
1267 ** columns are found, bail out early. */
1268 azCol = columnNames("main", zTab, &nPK, &bOtaRowid);
1269 if( azCol==0 ){
1270 runtimeError("table %s has no usable PK columns", zTab);
1271 }
dana9ca8af2015-07-31 19:52:03 +00001272 for(nCol=0; azCol[nCol]; nCol++);
dan99461852015-07-30 20:26:16 +00001273
1274 /* Build and output the CREATE TABLE statement for the data_xxx table */
1275 strPrintf(&ct, "CREATE TABLE IF NOT EXISTS 'data_%q'(", zTab);
1276 if( bOtaRowid ) strPrintf(&ct, "rbu_rowid, ");
1277 strPrintfArray(&ct, ", ", "%s", &azCol[bOtaRowid], -1);
1278 strPrintf(&ct, ", rbu_control);");
1279
dan99461852015-07-30 20:26:16 +00001280 /* Get the SQL for the query to retrieve data from the two databases */
1281 getRbudiffQuery(zTab, azCol, nPK, bOtaRowid, &sql);
1282
1283 /* Build the first part of the INSERT statement output for each row
1284 ** in the data_xxx table. */
1285 strPrintf(&insert, "INSERT INTO 'data_%q' (", zTab);
1286 if( bOtaRowid ) strPrintf(&insert, "rbu_rowid, ");
1287 strPrintfArray(&insert, ", ", "%s", &azCol[bOtaRowid], -1);
1288 strPrintf(&insert, ", rbu_control) VALUES(");
1289
1290 pStmt = db_prepare("%s", sql.z);
dana9ca8af2015-07-31 19:52:03 +00001291
dan99461852015-07-30 20:26:16 +00001292 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dana9ca8af2015-07-31 19:52:03 +00001293
1294 /* If this is the first row output, print out the CREATE TABLE
1295 ** statement first. And then set ct.z to NULL so that it is not
1296 ** printed again. */
dan99461852015-07-30 20:26:16 +00001297 if( ct.z ){
1298 fprintf(out, "%s\n", ct.z);
1299 strFree(&ct);
1300 }
1301
dana9ca8af2015-07-31 19:52:03 +00001302 /* Output the first part of the INSERT statement */
dan99461852015-07-30 20:26:16 +00001303 fprintf(out, "%s", insert.z);
danfebfe022016-03-19 16:21:26 +00001304 nRow++;
dana9ca8af2015-07-31 19:52:03 +00001305
1306 if( sqlite3_column_type(pStmt, nCol)==SQLITE_INTEGER ){
1307 for(i=0; i<=nCol; i++){
1308 if( i>0 ) fprintf(out, ", ");
1309 printQuoted(out, sqlite3_column_value(pStmt, i));
1310 }
1311 }else{
1312 char *zOtaControl;
1313 int nOtaControl = sqlite3_column_bytes(pStmt, nCol);
1314
dan6ff46272016-08-11 09:55:55 +00001315 zOtaControl = (char*)sqlite3_malloc(nOtaControl+1);
dana9ca8af2015-07-31 19:52:03 +00001316 memcpy(zOtaControl, sqlite3_column_text(pStmt, nCol), nOtaControl+1);
1317
1318 for(i=0; i<nCol; i++){
1319 int bDone = 0;
1320 if( i>=nPK
1321 && sqlite3_column_type(pStmt, i)==SQLITE_BLOB
1322 && sqlite3_column_type(pStmt, nCol+1+i)==SQLITE_BLOB
1323 ){
1324 const char *aSrc = sqlite3_column_blob(pStmt, nCol+1+i);
1325 int nSrc = sqlite3_column_bytes(pStmt, nCol+1+i);
1326 const char *aFinal = sqlite3_column_blob(pStmt, i);
1327 int nFinal = sqlite3_column_bytes(pStmt, i);
1328 char *aDelta;
1329 int nDelta;
1330
1331 aDelta = sqlite3_malloc(nFinal + 60);
1332 nDelta = rbuDeltaCreate(aSrc, nSrc, aFinal, nFinal, aDelta);
1333 if( nDelta<nFinal ){
1334 int j;
1335 fprintf(out, "x'");
1336 for(j=0; j<nDelta; j++) fprintf(out, "%02x", (u8)aDelta[j]);
1337 fprintf(out, "'");
1338 zOtaControl[i-bOtaRowid] = 'f';
1339 bDone = 1;
1340 }
1341 sqlite3_free(aDelta);
1342 }
1343
1344 if( bDone==0 ){
1345 printQuoted(out, sqlite3_column_value(pStmt, i));
1346 }
1347 fprintf(out, ", ");
1348 }
1349 fprintf(out, "'%s'", zOtaControl);
1350 sqlite3_free(zOtaControl);
dan99461852015-07-30 20:26:16 +00001351 }
dana9ca8af2015-07-31 19:52:03 +00001352
1353 /* And the closing bracket of the insert statement */
dan99461852015-07-30 20:26:16 +00001354 fprintf(out, ");\n");
1355 }
1356
1357 sqlite3_finalize(pStmt);
danfebfe022016-03-19 16:21:26 +00001358 if( nRow>0 ){
1359 Str cnt = {0, 0, 0};
1360 strPrintf(&cnt, "INSERT INTO rbu_count VALUES('data_%q', %d);", zTab, nRow);
1361 fprintf(out, "%s\n", cnt.z);
1362 strFree(&cnt);
1363 }
dan99461852015-07-30 20:26:16 +00001364
1365 strFree(&ct);
1366 strFree(&sql);
1367 strFree(&insert);
1368}
1369
1370/*
drh8a1cd762015-04-14 19:01:08 +00001371** Display a summary of differences between two versions of the same
1372** table table.
1373**
1374** * Number of rows changed
1375** * Number of rows added
1376** * Number of rows deleted
1377** * Number of identical rows
1378*/
1379static void summarize_one_table(const char *zTab, FILE *out){
1380 char *zId = safeId(zTab); /* Name of table (translated for us in SQL) */
1381 char **az = 0; /* Columns in main */
1382 char **az2 = 0; /* Columns in aux */
1383 int nPk; /* Primary key columns in main */
1384 int nPk2; /* Primary key columns in aux */
drhb3f3d642015-04-25 18:39:21 +00001385 int n = 0; /* Number of columns in main */
drh8a1cd762015-04-14 19:01:08 +00001386 int n2; /* Number of columns in aux */
1387 int i; /* Loop counter */
1388 const char *zSep; /* Separator string */
1389 Str sql; /* Comparison query */
1390 sqlite3_stmt *pStmt; /* Query statement to do the diff */
1391 sqlite3_int64 nUpdate; /* Number of updated rows */
1392 sqlite3_int64 nUnchanged; /* Number of unmodified rows */
1393 sqlite3_int64 nDelete; /* Number of deleted rows */
1394 sqlite3_int64 nInsert; /* Number of inserted rows */
1395
1396 strInit(&sql);
1397 if( sqlite3_table_column_metadata(g.db,"aux",zTab,0,0,0,0,0,0) ){
1398 if( !sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
1399 /* Table missing from second database. */
1400 fprintf(out, "%s: missing from second database\n", zTab);
1401 }
1402 goto end_summarize_one_table;
1403 }
1404
1405 if( sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
1406 /* Table missing from source */
1407 fprintf(out, "%s: missing from first database\n", zTab);
1408 goto end_summarize_one_table;
1409 }
1410
dan99461852015-07-30 20:26:16 +00001411 az = columnNames("main", zTab, &nPk, 0);
1412 az2 = columnNames("aux", zTab, &nPk2, 0);
drh8a1cd762015-04-14 19:01:08 +00001413 if( az && az2 ){
1414 for(n=0; az[n]; n++){
1415 if( sqlite3_stricmp(az[n],az2[n])!=0 ) break;
1416 }
1417 }
1418 if( az==0
1419 || az2==0
1420 || nPk!=nPk2
1421 || az[n]
1422 ){
1423 /* Schema mismatch */
1424 fprintf(out, "%s: incompatible schema\n", zTab);
1425 goto end_summarize_one_table;
1426 }
1427
1428 /* Build the comparison query */
1429 for(n2=n; az[n2]; n2++){}
1430 strPrintf(&sql, "SELECT 1, count(*)");
1431 if( n2==nPk2 ){
1432 strPrintf(&sql, ", 0\n");
1433 }else{
1434 zSep = ", sum(";
1435 for(i=nPk; az[i]; i++){
1436 strPrintf(&sql, "%sA.%s IS NOT B.%s", zSep, az[i], az[i]);
1437 zSep = " OR ";
1438 }
1439 strPrintf(&sql, ")\n");
1440 }
1441 strPrintf(&sql, " FROM main.%s A, aux.%s B\n", zId, zId);
1442 zSep = " WHERE";
1443 for(i=0; i<nPk; i++){
1444 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1445 zSep = " AND";
1446 }
1447 strPrintf(&sql, " UNION ALL\n");
1448 strPrintf(&sql, "SELECT 2, count(*), 0\n");
1449 strPrintf(&sql, " FROM main.%s A\n", zId);
1450 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B ", zId);
1451 zSep = "WHERE";
1452 for(i=0; i<nPk; i++){
1453 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1454 zSep = " AND";
1455 }
1456 strPrintf(&sql, ")\n");
1457 strPrintf(&sql, " UNION ALL\n");
1458 strPrintf(&sql, "SELECT 3, count(*), 0\n");
1459 strPrintf(&sql, " FROM aux.%s B\n", zId);
1460 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A ", zId);
1461 zSep = "WHERE";
1462 for(i=0; i<nPk; i++){
1463 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1464 zSep = " AND";
1465 }
1466 strPrintf(&sql, ")\n ORDER BY 1;\n");
1467
1468 if( (g.fDebug & DEBUG_DIFF_SQL)!=0 ){
1469 printf("SQL for %s:\n%s\n", zId, sql.z);
1470 goto end_summarize_one_table;
1471 }
1472
1473 /* Run the query and output difference summary */
drh52254492016-07-08 02:14:24 +00001474 pStmt = db_prepare("%s", sql.z);
drh8a1cd762015-04-14 19:01:08 +00001475 nUpdate = 0;
1476 nInsert = 0;
1477 nDelete = 0;
1478 nUnchanged = 0;
1479 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1480 switch( sqlite3_column_int(pStmt,0) ){
1481 case 1:
1482 nUpdate = sqlite3_column_int64(pStmt,2);
1483 nUnchanged = sqlite3_column_int64(pStmt,1) - nUpdate;
1484 break;
1485 case 2:
1486 nDelete = sqlite3_column_int64(pStmt,1);
1487 break;
1488 case 3:
1489 nInsert = sqlite3_column_int64(pStmt,1);
1490 break;
1491 }
1492 }
1493 sqlite3_finalize(pStmt);
1494 fprintf(out, "%s: %lld changes, %lld inserts, %lld deletes, %lld unchanged\n",
1495 zTab, nUpdate, nInsert, nDelete, nUnchanged);
1496
1497end_summarize_one_table:
1498 strFree(&sql);
1499 sqlite3_free(zId);
1500 namelistFree(az);
1501 namelistFree(az2);
1502 return;
1503}
1504
1505/*
drh697e5db2015-04-11 12:07:40 +00001506** Write a 64-bit signed integer as a varint onto out
1507*/
1508static void putsVarint(FILE *out, sqlite3_uint64 v){
1509 int i, n;
drh6e42ce42015-04-11 13:48:01 +00001510 unsigned char p[12];
drh697e5db2015-04-11 12:07:40 +00001511 if( v & (((sqlite3_uint64)0xff000000)<<32) ){
1512 p[8] = (unsigned char)v;
1513 v >>= 8;
1514 for(i=7; i>=0; i--){
1515 p[i] = (unsigned char)((v & 0x7f) | 0x80);
1516 v >>= 7;
1517 }
1518 fwrite(p, 8, 1, out);
1519 }else{
1520 n = 9;
1521 do{
1522 p[n--] = (unsigned char)((v & 0x7f) | 0x80);
1523 v >>= 7;
1524 }while( v!=0 );
drh6e42ce42015-04-11 13:48:01 +00001525 p[9] &= 0x7f;
1526 fwrite(p+n+1, 9-n, 1, out);
1527 }
1528}
1529
1530/*
1531** Write an SQLite value onto out.
1532*/
drhac4b8de2018-11-09 23:41:57 +00001533static void putValue(FILE *out, sqlite3_stmt *pStmt, int k){
1534 int iDType = sqlite3_column_type(pStmt, k);
drh6e42ce42015-04-11 13:48:01 +00001535 sqlite3_int64 iX;
1536 double rX;
1537 sqlite3_uint64 uX;
1538 int j;
1539
1540 putc(iDType, out);
1541 switch( iDType ){
1542 case SQLITE_INTEGER:
drhac4b8de2018-11-09 23:41:57 +00001543 iX = sqlite3_column_int64(pStmt, k);
drh6e42ce42015-04-11 13:48:01 +00001544 memcpy(&uX, &iX, 8);
1545 for(j=56; j>=0; j-=8) putc((uX>>j)&0xff, out);
1546 break;
1547 case SQLITE_FLOAT:
drhac4b8de2018-11-09 23:41:57 +00001548 rX = sqlite3_column_double(pStmt, k);
drh6e42ce42015-04-11 13:48:01 +00001549 memcpy(&uX, &rX, 8);
1550 for(j=56; j>=0; j-=8) putc((uX>>j)&0xff, out);
1551 break;
1552 case SQLITE_TEXT:
drhac4b8de2018-11-09 23:41:57 +00001553 iX = sqlite3_column_bytes(pStmt, k);
drh6e42ce42015-04-11 13:48:01 +00001554 putsVarint(out, (sqlite3_uint64)iX);
drhac4b8de2018-11-09 23:41:57 +00001555 fwrite(sqlite3_column_text(pStmt, k),1,(size_t)iX,out);
drh6e42ce42015-04-11 13:48:01 +00001556 break;
1557 case SQLITE_BLOB:
drhac4b8de2018-11-09 23:41:57 +00001558 iX = sqlite3_column_bytes(pStmt, k);
drh6e42ce42015-04-11 13:48:01 +00001559 putsVarint(out, (sqlite3_uint64)iX);
drhac4b8de2018-11-09 23:41:57 +00001560 fwrite(sqlite3_column_blob(pStmt, k),1,(size_t)iX,out);
drh6e42ce42015-04-11 13:48:01 +00001561 break;
1562 case SQLITE_NULL:
1563 break;
drh697e5db2015-04-11 12:07:40 +00001564 }
1565}
1566
1567/*
drh83e63dc2015-04-10 19:41:18 +00001568** Generate a CHANGESET for all differences from main.zTab to aux.zTab.
1569*/
1570static void changeset_one_table(const char *zTab, FILE *out){
1571 sqlite3_stmt *pStmt; /* SQL statment */
1572 char *zId = safeId(zTab); /* Escaped name of the table */
1573 char **azCol = 0; /* List of escaped column names */
1574 int nCol = 0; /* Number of columns */
1575 int *aiFlg = 0; /* 0 if column is not part of PK */
1576 int *aiPk = 0; /* Column numbers for each PK column */
1577 int nPk = 0; /* Number of PRIMARY KEY columns */
1578 Str sql; /* SQL for the diff query */
drh6e42ce42015-04-11 13:48:01 +00001579 int i, k; /* Loop counters */
drh83e63dc2015-04-10 19:41:18 +00001580 const char *zSep; /* List separator */
1581
dan99461852015-07-30 20:26:16 +00001582 /* Check that the schemas of the two tables match. Exit early otherwise. */
1583 checkSchemasMatch(zTab);
dane0404382020-08-14 16:14:40 +00001584 strInit(&sql);
dan99461852015-07-30 20:26:16 +00001585
drh83e63dc2015-04-10 19:41:18 +00001586 pStmt = db_prepare("PRAGMA main.table_info=%Q", zTab);
1587 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1588 nCol++;
1589 azCol = sqlite3_realloc(azCol, sizeof(char*)*nCol);
1590 if( azCol==0 ) runtimeError("out of memory");
1591 aiFlg = sqlite3_realloc(aiFlg, sizeof(int)*nCol);
1592 if( aiFlg==0 ) runtimeError("out of memory");
1593 azCol[nCol-1] = safeId((const char*)sqlite3_column_text(pStmt,1));
1594 aiFlg[nCol-1] = i = sqlite3_column_int(pStmt,5);
1595 if( i>0 ){
1596 if( i>nPk ){
1597 nPk = i;
1598 aiPk = sqlite3_realloc(aiPk, sizeof(int)*nPk);
1599 if( aiPk==0 ) runtimeError("out of memory");
1600 }
1601 aiPk[i-1] = nCol-1;
1602 }
1603 }
1604 sqlite3_finalize(pStmt);
1605 if( nPk==0 ) goto end_changeset_one_table;
drh83e63dc2015-04-10 19:41:18 +00001606 if( nCol>nPk ){
drh697e5db2015-04-11 12:07:40 +00001607 strPrintf(&sql, "SELECT %d", SQLITE_UPDATE);
drh6e42ce42015-04-11 13:48:01 +00001608 for(i=0; i<nCol; i++){
1609 if( aiFlg[i] ){
1610 strPrintf(&sql, ",\n A.%s", azCol[i]);
1611 }else{
1612 strPrintf(&sql, ",\n A.%s IS NOT B.%s, A.%s, B.%s",
1613 azCol[i], azCol[i], azCol[i], azCol[i]);
1614 }
1615 }
drh83e63dc2015-04-10 19:41:18 +00001616 strPrintf(&sql,"\n FROM main.%s A, aux.%s B\n", zId, zId);
1617 zSep = " WHERE";
1618 for(i=0; i<nPk; i++){
1619 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1620 zSep = " AND";
1621 }
1622 zSep = "\n AND (";
1623 for(i=0; i<nCol; i++){
1624 if( aiFlg[i] ) continue;
1625 strPrintf(&sql, "%sA.%s IS NOT B.%s", zSep, azCol[i], azCol[i]);
1626 zSep = " OR\n ";
1627 }
1628 strPrintf(&sql,")\n UNION ALL\n");
1629 }
drh697e5db2015-04-11 12:07:40 +00001630 strPrintf(&sql, "SELECT %d", SQLITE_DELETE);
drh6e42ce42015-04-11 13:48:01 +00001631 for(i=0; i<nCol; i++){
1632 if( aiFlg[i] ){
1633 strPrintf(&sql, ",\n A.%s", azCol[i]);
1634 }else{
1635 strPrintf(&sql, ",\n 1, A.%s, NULL", azCol[i]);
1636 }
1637 }
1638 strPrintf(&sql, "\n FROM main.%s A\n", zId);
drh83e63dc2015-04-10 19:41:18 +00001639 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B\n", zId);
1640 zSep = " WHERE";
1641 for(i=0; i<nPk; i++){
1642 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1643 zSep = " AND";
1644 }
1645 strPrintf(&sql, ")\n UNION ALL\n");
drh697e5db2015-04-11 12:07:40 +00001646 strPrintf(&sql, "SELECT %d", SQLITE_INSERT);
drh6e42ce42015-04-11 13:48:01 +00001647 for(i=0; i<nCol; i++){
1648 if( aiFlg[i] ){
1649 strPrintf(&sql, ",\n B.%s", azCol[i]);
1650 }else{
1651 strPrintf(&sql, ",\n 1, NULL, B.%s", azCol[i]);
1652 }
1653 }
1654 strPrintf(&sql, "\n FROM aux.%s B\n", zId);
drh83e63dc2015-04-10 19:41:18 +00001655 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A\n", zId);
1656 zSep = " WHERE";
1657 for(i=0; i<nPk; i++){
1658 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1659 zSep = " AND";
1660 }
1661 strPrintf(&sql, ")\n");
1662 strPrintf(&sql, " ORDER BY");
1663 zSep = " ";
1664 for(i=0; i<nPk; i++){
drh6e42ce42015-04-11 13:48:01 +00001665 strPrintf(&sql, "%s %d", zSep, aiPk[i]+2);
drh83e63dc2015-04-10 19:41:18 +00001666 zSep = ",";
1667 }
1668 strPrintf(&sql, ";\n");
1669
drh697e5db2015-04-11 12:07:40 +00001670 if( g.fDebug & DEBUG_DIFF_SQL ){
1671 printf("SQL for %s:\n%s\n", zId, sql.z);
1672 goto end_changeset_one_table;
1673 }
1674
1675 putc('T', out);
1676 putsVarint(out, (sqlite3_uint64)nCol);
dan07d0f152017-05-22 18:09:00 +00001677 for(i=0; i<nCol; i++) putc(aiFlg[i], out);
drh697e5db2015-04-11 12:07:40 +00001678 fwrite(zTab, 1, strlen(zTab), out);
1679 putc(0, out);
1680
1681 pStmt = db_prepare("%s", sql.z);
1682 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1683 int iType = sqlite3_column_int(pStmt,0);
drh697e5db2015-04-11 12:07:40 +00001684 putc(iType, out);
1685 putc(0, out);
drh6e42ce42015-04-11 13:48:01 +00001686 switch( sqlite3_column_int(pStmt,0) ){
1687 case SQLITE_UPDATE: {
1688 for(k=1, i=0; i<nCol; i++){
1689 if( aiFlg[i] ){
drhac4b8de2018-11-09 23:41:57 +00001690 putValue(out, pStmt, k);
drh6e42ce42015-04-11 13:48:01 +00001691 k++;
1692 }else if( sqlite3_column_int(pStmt,k) ){
drhac4b8de2018-11-09 23:41:57 +00001693 putValue(out, pStmt, k+1);
drh6e42ce42015-04-11 13:48:01 +00001694 k += 3;
1695 }else{
1696 putc(0, out);
1697 k += 3;
1698 }
1699 }
1700 for(k=1, i=0; i<nCol; i++){
1701 if( aiFlg[i] ){
1702 putc(0, out);
1703 k++;
1704 }else if( sqlite3_column_int(pStmt,k) ){
drhac4b8de2018-11-09 23:41:57 +00001705 putValue(out, pStmt, k+2);
drh6e42ce42015-04-11 13:48:01 +00001706 k += 3;
1707 }else{
1708 putc(0, out);
1709 k += 3;
1710 }
1711 }
1712 break;
1713 }
1714 case SQLITE_INSERT: {
1715 for(k=1, i=0; i<nCol; i++){
1716 if( aiFlg[i] ){
drhac4b8de2018-11-09 23:41:57 +00001717 putValue(out, pStmt, k);
drh6e42ce42015-04-11 13:48:01 +00001718 k++;
1719 }else{
drhac4b8de2018-11-09 23:41:57 +00001720 putValue(out, pStmt, k+2);
drh6e42ce42015-04-11 13:48:01 +00001721 k += 3;
1722 }
1723 }
1724 break;
1725 }
1726 case SQLITE_DELETE: {
1727 for(k=1, i=0; i<nCol; i++){
1728 if( aiFlg[i] ){
drhac4b8de2018-11-09 23:41:57 +00001729 putValue(out, pStmt, k);
drh6e42ce42015-04-11 13:48:01 +00001730 k++;
1731 }else{
drhac4b8de2018-11-09 23:41:57 +00001732 putValue(out, pStmt, k+1);
drh6e42ce42015-04-11 13:48:01 +00001733 k += 3;
1734 }
1735 }
1736 break;
drh697e5db2015-04-11 12:07:40 +00001737 }
1738 }
1739 }
1740 sqlite3_finalize(pStmt);
drh83e63dc2015-04-10 19:41:18 +00001741
1742end_changeset_one_table:
1743 while( nCol>0 ) sqlite3_free(azCol[--nCol]);
1744 sqlite3_free(azCol);
1745 sqlite3_free(aiPk);
1746 sqlite3_free(zId);
dane0404382020-08-14 16:14:40 +00001747 sqlite3_free(aiFlg);
1748 strFree(&sql);
drh83e63dc2015-04-10 19:41:18 +00001749}
1750
1751/*
dan42470512021-03-17 11:25:42 +00001752** Return true if the ascii character passed as the only argument is a
1753** whitespace character. Otherwise return false.
1754*/
1755static int is_whitespace(char x){
1756 return (x==' ' || x=='\t' || x=='\n' || x=='\r');
1757}
1758
1759/*
dan9c987a82016-06-21 10:34:41 +00001760** Extract the next SQL keyword or quoted string from buffer zIn and copy it
1761** (or a prefix of it if it will not fit) into buffer zBuf, size nBuf bytes.
1762** Return a pointer to the character within zIn immediately following
1763** the token or quoted string just extracted.
1764*/
dan42470512021-03-17 11:25:42 +00001765static const char *gobble_token(const char *zIn, char *zBuf, int nBuf){
dan9c987a82016-06-21 10:34:41 +00001766 const char *p = zIn;
1767 char *pOut = zBuf;
1768 char *pEnd = &pOut[nBuf-1];
1769 char q = 0; /* quote character, if any */
1770
1771 if( p==0 ) return 0;
dan42470512021-03-17 11:25:42 +00001772 while( is_whitespace(*p) ) p++;
dan9c987a82016-06-21 10:34:41 +00001773 switch( *p ){
1774 case '"': q = '"'; break;
1775 case '\'': q = '\''; break;
1776 case '`': q = '`'; break;
1777 case '[': q = ']'; break;
1778 }
1779
1780 if( q ){
1781 p++;
1782 while( *p && pOut<pEnd ){
1783 if( *p==q ){
1784 p++;
1785 if( *p!=q ) break;
1786 }
1787 if( pOut<pEnd ) *pOut++ = *p;
1788 p++;
1789 }
1790 }else{
dan42470512021-03-17 11:25:42 +00001791 while( *p && !is_whitespace(*p) && *p!='(' ){
dan9c987a82016-06-21 10:34:41 +00001792 if( pOut<pEnd ) *pOut++ = *p;
1793 p++;
1794 }
1795 }
1796
1797 *pOut = '\0';
1798 return p;
1799}
1800
1801/*
1802** This function is the implementation of SQL scalar function "module_name":
1803**
1804** module_name(SQL)
1805**
1806** The only argument should be an SQL statement of the type that may appear
drh067b92b2020-06-19 15:24:12 +00001807** in the sqlite_schema table. If the statement is a "CREATE VIRTUAL TABLE"
dan9c987a82016-06-21 10:34:41 +00001808** statement, then the value returned is the name of the module that it
1809** uses. Otherwise, if the statement is not a CVT, NULL is returned.
1810*/
1811static void module_name_func(
1812 sqlite3_context *pCtx,
1813 int nVal, sqlite3_value **apVal
1814){
1815 const char *zSql;
1816 char zToken[32];
1817
1818 assert( nVal==1 );
1819 zSql = (const char*)sqlite3_value_text(apVal[0]);
1820
1821 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1822 if( zSql==0 || sqlite3_stricmp(zToken, "create") ) return;
1823 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1824 if( zSql==0 || sqlite3_stricmp(zToken, "virtual") ) return;
1825 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1826 if( zSql==0 || sqlite3_stricmp(zToken, "table") ) return;
1827 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1828 if( zSql==0 ) return;
1829 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1830 if( zSql==0 || sqlite3_stricmp(zToken, "using") ) return;
1831 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1832
1833 sqlite3_result_text(pCtx, zToken, -1, SQLITE_TRANSIENT);
1834}
1835
1836/*
1837** Return the text of an SQL statement that itself returns the list of
1838** tables to process within the database.
1839*/
1840const char *all_tables_sql(){
1841 if( g.bHandleVtab ){
1842 int rc;
1843
1844 rc = sqlite3_exec(g.db,
dan12ca5ac2016-07-22 10:09:26 +00001845 "CREATE TEMP TABLE tblmap(module COLLATE nocase, postfix);"
dan9c987a82016-06-21 10:34:41 +00001846 "INSERT INTO temp.tblmap VALUES"
1847 "('fts3', '_content'), ('fts3', '_segments'), ('fts3', '_segdir'),"
1848
1849 "('fts4', '_content'), ('fts4', '_segments'), ('fts4', '_segdir'),"
1850 "('fts4', '_docsize'), ('fts4', '_stat'),"
1851
1852 "('fts5', '_data'), ('fts5', '_idx'), ('fts5', '_content'),"
1853 "('fts5', '_docsize'), ('fts5', '_config'),"
1854
1855 "('rtree', '_node'), ('rtree', '_rowid'), ('rtree', '_parent');"
1856 , 0, 0, 0
1857 );
1858 assert( rc==SQLITE_OK );
1859
1860 rc = sqlite3_create_function(
1861 g.db, "module_name", 1, SQLITE_UTF8, 0, module_name_func, 0, 0
1862 );
1863 assert( rc==SQLITE_OK );
1864
1865 return
drh067b92b2020-06-19 15:24:12 +00001866 "SELECT name FROM main.sqlite_schema\n"
dan9c987a82016-06-21 10:34:41 +00001867 " WHERE type='table' AND (\n"
1868 " module_name(sql) IS NULL OR \n"
1869 " module_name(sql) IN (SELECT module FROM temp.tblmap)\n"
1870 " ) AND name NOT IN (\n"
1871 " SELECT a.name || b.postfix \n"
drh067b92b2020-06-19 15:24:12 +00001872 "FROM main.sqlite_schema AS a, temp.tblmap AS b \n"
dan9c987a82016-06-21 10:34:41 +00001873 "WHERE module_name(a.sql) = b.module\n"
1874 " )\n"
1875 "UNION \n"
drh067b92b2020-06-19 15:24:12 +00001876 "SELECT name FROM aux.sqlite_schema\n"
dan9c987a82016-06-21 10:34:41 +00001877 " WHERE type='table' AND (\n"
1878 " module_name(sql) IS NULL OR \n"
1879 " module_name(sql) IN (SELECT module FROM temp.tblmap)\n"
1880 " ) AND name NOT IN (\n"
1881 " SELECT a.name || b.postfix \n"
drh067b92b2020-06-19 15:24:12 +00001882 "FROM aux.sqlite_schema AS a, temp.tblmap AS b \n"
dan9c987a82016-06-21 10:34:41 +00001883 "WHERE module_name(a.sql) = b.module\n"
1884 " )\n"
1885 " ORDER BY name";
1886 }else{
1887 return
drh067b92b2020-06-19 15:24:12 +00001888 "SELECT name FROM main.sqlite_schema\n"
dan9c987a82016-06-21 10:34:41 +00001889 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1890 " UNION\n"
drh067b92b2020-06-19 15:24:12 +00001891 "SELECT name FROM aux.sqlite_schema\n"
dan9c987a82016-06-21 10:34:41 +00001892 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1893 " ORDER BY name";
1894 }
1895}
1896
1897/*
drhd62c0f42015-04-09 13:34:29 +00001898** Print sketchy documentation for this utility program
1899*/
1900static void showHelp(void){
1901 printf("Usage: %s [options] DB1 DB2\n", g.zArgv0);
1902 printf(
1903"Output SQL text that would transform DB1 into DB2.\n"
1904"Options:\n"
drh83e63dc2015-04-10 19:41:18 +00001905" --changeset FILE Write a CHANGESET into FILE\n"
drh9a9219f2015-05-04 13:25:56 +00001906" -L|--lib LIBRARY Load an SQLite extension library\n"
drha37591c2015-04-09 18:14:03 +00001907" --primarykey Use schema-defined PRIMARY KEYs\n"
dan99461852015-07-30 20:26:16 +00001908" --rbu Output SQL to create/populate RBU table(s)\n"
drhd62c0f42015-04-09 13:34:29 +00001909" --schema Show only differences in the schema\n"
drh8a1cd762015-04-14 19:01:08 +00001910" --summary Show only a summary of the differences\n"
drhd62c0f42015-04-09 13:34:29 +00001911" --table TAB Show only differences in table TAB\n"
drh05d4ebf2015-11-13 13:15:42 +00001912" --transaction Show SQL output inside a transaction\n"
dan9c987a82016-06-21 10:34:41 +00001913" --vtab Handle fts3, fts4, fts5 and rtree tables\n"
larrybra933ec42021-09-07 19:04:42 +00001914"See https://sqlite.org/sqldiff.html for detailed explanation.\n"
drhd62c0f42015-04-09 13:34:29 +00001915 );
1916}
1917
1918int main(int argc, char **argv){
1919 const char *zDb1 = 0;
1920 const char *zDb2 = 0;
1921 int i;
1922 int rc;
1923 char *zErrMsg = 0;
1924 char *zSql;
1925 sqlite3_stmt *pStmt;
1926 char *zTab = 0;
drh8a1cd762015-04-14 19:01:08 +00001927 FILE *out = stdout;
1928 void (*xDiff)(const char*,FILE*) = diff_one_table;
drh9493caf2016-03-17 23:16:37 +00001929#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh9a9219f2015-05-04 13:25:56 +00001930 int nExt = 0;
drh33aa4db2015-05-04 15:04:47 +00001931 char **azExt = 0;
drh9493caf2016-03-17 23:16:37 +00001932#endif
drh05d4ebf2015-11-13 13:15:42 +00001933 int useTransaction = 0;
1934 int neverUseTransaction = 0;
drhd62c0f42015-04-09 13:34:29 +00001935
1936 g.zArgv0 = argv[0];
drhaa62e482015-05-12 00:46:40 +00001937 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
drhd62c0f42015-04-09 13:34:29 +00001938 for(i=1; i<argc; i++){
1939 const char *z = argv[i];
1940 if( z[0]=='-' ){
1941 z++;
1942 if( z[0]=='-' ) z++;
drh83e63dc2015-04-10 19:41:18 +00001943 if( strcmp(z,"changeset")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001944 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drh83e63dc2015-04-10 19:41:18 +00001945 out = fopen(argv[++i], "wb");
1946 if( out==0 ) cmdlineError("cannot open: %s", argv[i]);
drh8a1cd762015-04-14 19:01:08 +00001947 xDiff = changeset_one_table;
drh05d4ebf2015-11-13 13:15:42 +00001948 neverUseTransaction = 1;
drh83e63dc2015-04-10 19:41:18 +00001949 }else
drhd62c0f42015-04-09 13:34:29 +00001950 if( strcmp(z,"debug")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001951 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drhd62c0f42015-04-09 13:34:29 +00001952 g.fDebug = strtol(argv[++i], 0, 0);
1953 }else
1954 if( strcmp(z,"help")==0 ){
1955 showHelp();
1956 return 0;
1957 }else
drh6582ae52015-05-12 12:24:50 +00001958#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh9a9219f2015-05-04 13:25:56 +00001959 if( strcmp(z,"lib")==0 || strcmp(z,"L")==0 ){
1960 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
1961 azExt = realloc(azExt, sizeof(azExt[0])*(nExt+1));
1962 if( azExt==0 ) cmdlineError("out of memory");
1963 azExt[nExt++] = argv[++i];
1964 }else
drh6582ae52015-05-12 12:24:50 +00001965#endif
drha37591c2015-04-09 18:14:03 +00001966 if( strcmp(z,"primarykey")==0 ){
1967 g.bSchemaPK = 1;
1968 }else
dan99461852015-07-30 20:26:16 +00001969 if( strcmp(z,"rbu")==0 ){
1970 xDiff = rbudiff_one_table;
1971 }else
drhd62c0f42015-04-09 13:34:29 +00001972 if( strcmp(z,"schema")==0 ){
1973 g.bSchemaOnly = 1;
1974 }else
drh8a1cd762015-04-14 19:01:08 +00001975 if( strcmp(z,"summary")==0 ){
1976 xDiff = summarize_one_table;
1977 }else
drhd62c0f42015-04-09 13:34:29 +00001978 if( strcmp(z,"table")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001979 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drhd62c0f42015-04-09 13:34:29 +00001980 zTab = argv[++i];
larrybra933ec42021-09-07 19:04:42 +00001981 g.bSchemaCompare =
1982 sqlite3_stricmp(zTab, "sqlite_schema")
1983 || sqlite3_stricmp(zTab, "sqlite_master");
drhd62c0f42015-04-09 13:34:29 +00001984 }else
drh05d4ebf2015-11-13 13:15:42 +00001985 if( strcmp(z,"transaction")==0 ){
1986 useTransaction = 1;
1987 }else
dan9c987a82016-06-21 10:34:41 +00001988 if( strcmp(z,"vtab")==0 ){
1989 g.bHandleVtab = 1;
1990 }else
drhd62c0f42015-04-09 13:34:29 +00001991 {
1992 cmdlineError("unknown option: %s", argv[i]);
1993 }
1994 }else if( zDb1==0 ){
1995 zDb1 = argv[i];
1996 }else if( zDb2==0 ){
1997 zDb2 = argv[i];
1998 }else{
1999 cmdlineError("unknown argument: %s", argv[i]);
2000 }
2001 }
2002 if( zDb2==0 ){
2003 cmdlineError("two database arguments required");
2004 }
larrybra933ec42021-09-07 19:04:42 +00002005 if( g.bSchemaOnly && g.bSchemaCompare ){
2006 cmdlineError("The --schema option is useless with --table %s .", zTab);
2007 }
drhd62c0f42015-04-09 13:34:29 +00002008 rc = sqlite3_open(zDb1, &g.db);
2009 if( rc ){
2010 cmdlineError("cannot open database file \"%s\"", zDb1);
2011 }
drh067b92b2020-06-19 15:24:12 +00002012 rc = sqlite3_exec(g.db, "SELECT * FROM sqlite_schema", 0, 0, &zErrMsg);
drhd62c0f42015-04-09 13:34:29 +00002013 if( rc || zErrMsg ){
2014 cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb1);
2015 }
drh6582ae52015-05-12 12:24:50 +00002016#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh9a9219f2015-05-04 13:25:56 +00002017 sqlite3_enable_load_extension(g.db, 1);
2018 for(i=0; i<nExt; i++){
2019 rc = sqlite3_load_extension(g.db, azExt[i], 0, &zErrMsg);
2020 if( rc || zErrMsg ){
2021 cmdlineError("error loading %s: %s", azExt[i], zErrMsg);
2022 }
2023 }
2024 free(azExt);
drh9493caf2016-03-17 23:16:37 +00002025#endif
drhd62c0f42015-04-09 13:34:29 +00002026 zSql = sqlite3_mprintf("ATTACH %Q as aux;", zDb2);
2027 rc = sqlite3_exec(g.db, zSql, 0, 0, &zErrMsg);
dane0404382020-08-14 16:14:40 +00002028 sqlite3_free(zSql);
2029 zSql = 0;
drhd62c0f42015-04-09 13:34:29 +00002030 if( rc || zErrMsg ){
2031 cmdlineError("cannot attach database \"%s\"", zDb2);
2032 }
drh067b92b2020-06-19 15:24:12 +00002033 rc = sqlite3_exec(g.db, "SELECT * FROM aux.sqlite_schema", 0, 0, &zErrMsg);
drhd62c0f42015-04-09 13:34:29 +00002034 if( rc || zErrMsg ){
2035 cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb2);
2036 }
2037
drh05d4ebf2015-11-13 13:15:42 +00002038 if( neverUseTransaction ) useTransaction = 0;
danfebfe022016-03-19 16:21:26 +00002039 if( useTransaction ) fprintf(out, "BEGIN TRANSACTION;\n");
2040 if( xDiff==rbudiff_one_table ){
2041 fprintf(out, "CREATE TABLE IF NOT EXISTS rbu_count"
2042 "(tbl TEXT PRIMARY KEY COLLATE NOCASE, cnt INTEGER) "
2043 "WITHOUT ROWID;\n"
2044 );
2045 }
drhd62c0f42015-04-09 13:34:29 +00002046 if( zTab ){
drh8a1cd762015-04-14 19:01:08 +00002047 xDiff(zTab, out);
drhd62c0f42015-04-09 13:34:29 +00002048 }else{
2049 /* Handle tables one by one */
drh52254492016-07-08 02:14:24 +00002050 pStmt = db_prepare("%s", all_tables_sql() );
drhd62c0f42015-04-09 13:34:29 +00002051 while( SQLITE_ROW==sqlite3_step(pStmt) ){
drh8a1cd762015-04-14 19:01:08 +00002052 xDiff((const char*)sqlite3_column_text(pStmt,0), out);
drhd62c0f42015-04-09 13:34:29 +00002053 }
2054 sqlite3_finalize(pStmt);
2055 }
drh05d4ebf2015-11-13 13:15:42 +00002056 if( useTransaction ) printf("COMMIT;\n");
drhd62c0f42015-04-09 13:34:29 +00002057
2058 /* TBD: Handle trigger differences */
2059 /* TBD: Handle view differences */
2060 sqlite3_close(g.db);
2061 return 0;
2062}