blob: 9f0b705c40ab95ab27ae2dda9fb8c994cdeba751 [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 */
drhd62c0f42015-04-09 13:34:29 +000036 unsigned fDebug; /* Debug flags */
37 sqlite3 *db; /* The database connection */
38} g;
39
40/*
41** Allowed values for g.fDebug
42*/
43#define DEBUG_COLUMN_NAMES 0x000001
44#define DEBUG_DIFF_SQL 0x000002
45
46/*
47** Dynamic string object
48*/
49typedef struct Str Str;
50struct Str {
51 char *z; /* Text of the string */
52 int nAlloc; /* Bytes allocated in z[] */
53 int nUsed; /* Bytes actually used in z[] */
54};
55
56/*
57** Initialize a Str object
58*/
59static void strInit(Str *p){
60 p->z = 0;
61 p->nAlloc = 0;
62 p->nUsed = 0;
63}
64
65/*
66** Print an error resulting from faulting command-line arguments and
67** abort the program.
68*/
69static void cmdlineError(const char *zFormat, ...){
70 va_list ap;
71 fprintf(stderr, "%s: ", g.zArgv0);
72 va_start(ap, zFormat);
73 vfprintf(stderr, zFormat, ap);
74 va_end(ap);
75 fprintf(stderr, "\n\"%s --help\" for more help\n", g.zArgv0);
76 exit(1);
77}
78
79/*
80** Print an error message for an error that occurs at runtime, then
81** abort the program.
82*/
83static void runtimeError(const char *zFormat, ...){
84 va_list ap;
85 fprintf(stderr, "%s: ", g.zArgv0);
86 va_start(ap, zFormat);
87 vfprintf(stderr, zFormat, ap);
88 va_end(ap);
89 fprintf(stderr, "\n");
90 exit(1);
91}
92
93/*
94** Free all memory held by a Str object
95*/
96static void strFree(Str *p){
97 sqlite3_free(p->z);
98 strInit(p);
99}
100
101/*
102** Add formatted text to the end of a Str object
103*/
104static void strPrintf(Str *p, const char *zFormat, ...){
105 int nNew;
106 for(;;){
107 if( p->z ){
108 va_list ap;
109 va_start(ap, zFormat);
110 sqlite3_vsnprintf(p->nAlloc-p->nUsed, p->z+p->nUsed, zFormat, ap);
111 va_end(ap);
112 nNew = (int)strlen(p->z + p->nUsed);
113 }else{
114 nNew = p->nAlloc;
115 }
116 if( p->nUsed+nNew < p->nAlloc-1 ){
117 p->nUsed += nNew;
118 break;
119 }
120 p->nAlloc = p->nAlloc*2 + 1000;
121 p->z = sqlite3_realloc(p->z, p->nAlloc);
122 if( p->z==0 ) runtimeError("out of memory");
123 }
124}
125
126
127
128/* Safely quote an SQL identifier. Use the minimum amount of transformation
129** necessary to allow the string to be used with %s.
130**
131** Space to hold the returned string is obtained from sqlite3_malloc(). The
132** caller is responsible for ensuring this space is freed when no longer
133** needed.
134*/
135static char *safeId(const char *zId){
136 /* All SQLite keywords, in alphabetical order */
137 static const char *azKeywords[] = {
138 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
139 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
140 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
141 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
142 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
143 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
144 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
145 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
146 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
147 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
148 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
149 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
150 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
151 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
152 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
153 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
154 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
155 "WITH", "WITHOUT",
156 };
157 int lwr, upr, mid, c, i, x;
158 for(i=x=0; (c = zId[i])!=0; i++){
159 if( !isalpha(c) && c!='_' ){
160 if( i>0 && isdigit(c) ){
161 x++;
162 }else{
163 return sqlite3_mprintf("\"%w\"", zId);
164 }
165 }
166 }
167 if( x ) return sqlite3_mprintf("%s", zId);
168 lwr = 0;
169 upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
170 while( lwr<=upr ){
171 mid = (lwr+upr)/2;
172 c = sqlite3_stricmp(azKeywords[mid], zId);
173 if( c==0 ) return sqlite3_mprintf("\"%w\"", zId);
174 if( c<0 ){
175 lwr = mid+1;
176 }else{
177 upr = mid-1;
178 }
179 }
180 return sqlite3_mprintf("%s", zId);
181}
182
183/*
184** Prepare a new SQL statement. Print an error and abort if anything
185** goes wrong.
186*/
187static sqlite3_stmt *db_vprepare(const char *zFormat, va_list ap){
188 char *zSql;
189 int rc;
190 sqlite3_stmt *pStmt;
191
192 zSql = sqlite3_vmprintf(zFormat, ap);
193 if( zSql==0 ) runtimeError("out of memory");
194 rc = sqlite3_prepare_v2(g.db, zSql, -1, &pStmt, 0);
195 if( rc ){
196 runtimeError("SQL statement error: %s\n\"%s\"", sqlite3_errmsg(g.db),
197 zSql);
198 }
199 sqlite3_free(zSql);
200 return pStmt;
201}
202static sqlite3_stmt *db_prepare(const char *zFormat, ...){
203 va_list ap;
204 sqlite3_stmt *pStmt;
205 va_start(ap, zFormat);
206 pStmt = db_vprepare(zFormat, ap);
207 va_end(ap);
208 return pStmt;
209}
210
211/*
212** Free a list of strings
213*/
214static void namelistFree(char **az){
215 if( az ){
216 int i;
217 for(i=0; az[i]; i++) sqlite3_free(az[i]);
218 sqlite3_free(az);
219 }
220}
221
222/*
223** Return a list of column names for the table zDb.zTab. Space to
drh39b355c2015-04-09 13:40:18 +0000224** hold the list is obtained from sqlite3_malloc() and should released
225** using namelistFree() when no longer needed.
drhd62c0f42015-04-09 13:34:29 +0000226**
drha37591c2015-04-09 18:14:03 +0000227** Primary key columns are listed first, followed by data columns.
228** The number of columns in the primary key is returned in *pnPkey.
drhd62c0f42015-04-09 13:34:29 +0000229**
drha37591c2015-04-09 18:14:03 +0000230** Normally, the "primary key" in the previous sentence is the true
231** primary key - the rowid or INTEGER PRIMARY KEY for ordinary tables
232** or the declared PRIMARY KEY for WITHOUT ROWID tables. However, if
233** the g.bSchemaPK flag is set, then the schema-defined PRIMARY KEY is
234** used in all cases. In that case, entries that have NULL values in
235** any of their primary key fields will be excluded from the analysis.
236**
237** If the primary key for a table is the rowid but rowid is inaccessible,
drhd62c0f42015-04-09 13:34:29 +0000238** then this routine returns a NULL pointer.
239**
240** Examples:
241** CREATE TABLE t1(a INT UNIQUE, b INTEGER, c TEXT, PRIMARY KEY(c));
242** *pnPKey = 1;
drha37591c2015-04-09 18:14:03 +0000243** az = { "rowid", "a", "b", "c", 0 } // Normal case
244** az = { "c", "a", "b", 0 } // g.bSchemaPK==1
drhd62c0f42015-04-09 13:34:29 +0000245**
246** CREATE TABLE t2(a INT UNIQUE, b INTEGER, c TEXT, PRIMARY KEY(b));
247** *pnPKey = 1;
248** az = { "b", "a", "c", 0 }
249**
250** CREATE TABLE t3(x,y,z,PRIMARY KEY(y,z));
drha37591c2015-04-09 18:14:03 +0000251** *pnPKey = 1 // Normal case
252** az = { "rowid", "x", "y", "z", 0 } // Normal case
253** *pnPKey = 2 // g.bSchemaPK==1
254** az = { "y", "x", "z", 0 } // g.bSchemaPK==1
drhd62c0f42015-04-09 13:34:29 +0000255**
256** CREATE TABLE t4(x,y,z,PRIMARY KEY(y,z)) WITHOUT ROWID;
257** *pnPKey = 2
258** az = { "y", "z", "x", 0 }
259**
260** CREATE TABLE t5(rowid,_rowid_,oid);
261** az = 0 // The rowid is not accessible
262*/
dan99461852015-07-30 20:26:16 +0000263static char **columnNames(
264 const char *zDb, /* Database ("main" or "aux") to query */
265 const char *zTab, /* Name of table to return details of */
266 int *pnPKey, /* OUT: Number of PK columns */
267 int *pbRowid /* OUT: True if PK is an implicit rowid */
268){
drha37591c2015-04-09 18:14:03 +0000269 char **az = 0; /* List of column names to be returned */
270 int naz = 0; /* Number of entries in az[] */
271 sqlite3_stmt *pStmt; /* SQL statement being run */
drhd62c0f42015-04-09 13:34:29 +0000272 char *zPkIdxName = 0; /* Name of the PRIMARY KEY index */
drha37591c2015-04-09 18:14:03 +0000273 int truePk = 0; /* PRAGMA table_info indentifies the PK to use */
drhd62c0f42015-04-09 13:34:29 +0000274 int nPK = 0; /* Number of PRIMARY KEY columns */
drha37591c2015-04-09 18:14:03 +0000275 int i, j; /* Loop counters */
drhd62c0f42015-04-09 13:34:29 +0000276
drha37591c2015-04-09 18:14:03 +0000277 if( g.bSchemaPK==0 ){
278 /* Normal case: Figure out what the true primary key is for the table.
279 ** * For WITHOUT ROWID tables, the true primary key is the same as
280 ** the schema PRIMARY KEY, which is guaranteed to be present.
281 ** * For rowid tables with an INTEGER PRIMARY KEY, the true primary
282 ** key is the INTEGER PRIMARY KEY.
283 ** * For all other rowid tables, the rowid is the true primary key.
284 */
285 pStmt = db_prepare("PRAGMA %s.index_list=%Q", zDb, zTab);
drhd62c0f42015-04-09 13:34:29 +0000286 while( SQLITE_ROW==sqlite3_step(pStmt) ){
drha37591c2015-04-09 18:14:03 +0000287 if( sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,3),"pk")==0 ){
288 zPkIdxName = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
289 break;
290 }
drhd62c0f42015-04-09 13:34:29 +0000291 }
292 sqlite3_finalize(pStmt);
drha37591c2015-04-09 18:14:03 +0000293 if( zPkIdxName ){
294 int nKey = 0;
295 int nCol = 0;
296 truePk = 0;
297 pStmt = db_prepare("PRAGMA %s.index_xinfo=%Q", zDb, zPkIdxName);
298 while( SQLITE_ROW==sqlite3_step(pStmt) ){
299 nCol++;
300 if( sqlite3_column_int(pStmt,5) ){ nKey++; continue; }
301 if( sqlite3_column_int(pStmt,1)>=0 ) truePk = 1;
302 }
303 if( nCol==nKey ) truePk = 1;
304 if( truePk ){
305 nPK = nKey;
306 }else{
307 nPK = 1;
308 }
309 sqlite3_finalize(pStmt);
310 sqlite3_free(zPkIdxName);
311 }else{
312 truePk = 1;
313 nPK = 1;
314 }
315 pStmt = db_prepare("PRAGMA %s.table_info=%Q", zDb, zTab);
drhd62c0f42015-04-09 13:34:29 +0000316 }else{
drha37591c2015-04-09 18:14:03 +0000317 /* The g.bSchemaPK==1 case: Use whatever primary key is declared
318 ** in the schema. The "rowid" will still be used as the primary key
319 ** if the table definition does not contain a PRIMARY KEY.
320 */
321 nPK = 0;
322 pStmt = db_prepare("PRAGMA %s.table_info=%Q", zDb, zTab);
323 while( SQLITE_ROW==sqlite3_step(pStmt) ){
324 if( sqlite3_column_int(pStmt,5)>0 ) nPK++;
325 }
326 sqlite3_reset(pStmt);
327 if( nPK==0 ) nPK = 1;
drhd62c0f42015-04-09 13:34:29 +0000328 truePk = 1;
drhd62c0f42015-04-09 13:34:29 +0000329 }
330 *pnPKey = nPK;
331 naz = nPK;
332 az = sqlite3_malloc( sizeof(char*)*(nPK+1) );
333 if( az==0 ) runtimeError("out of memory");
334 memset(az, 0, sizeof(char*)*(nPK+1));
drhd62c0f42015-04-09 13:34:29 +0000335 while( SQLITE_ROW==sqlite3_step(pStmt) ){
336 int iPKey;
337 if( truePk && (iPKey = sqlite3_column_int(pStmt,5))>0 ){
338 az[iPKey-1] = safeId((char*)sqlite3_column_text(pStmt,1));
339 }else{
340 az = sqlite3_realloc(az, sizeof(char*)*(naz+2) );
341 if( az==0 ) runtimeError("out of memory");
342 az[naz++] = safeId((char*)sqlite3_column_text(pStmt,1));
343 }
344 }
345 sqlite3_finalize(pStmt);
346 if( az ) az[naz] = 0;
dan99461852015-07-30 20:26:16 +0000347
348 /* If it is non-NULL, set *pbRowid to indicate whether or not the PK of
349 ** this table is an implicit rowid (*pbRowid==1) or not (*pbRowid==0). */
350 if( pbRowid ) *pbRowid = (az[0]==0);
351
352 /* If this table has an implicit rowid for a PK, figure out how to refer
353 ** to it. There are three options - "rowid", "_rowid_" and "oid". Any
354 ** of these will work, unless the table has an explicit column of the
355 ** same name. */
drhd62c0f42015-04-09 13:34:29 +0000356 if( az[0]==0 ){
357 const char *azRowid[] = { "rowid", "_rowid_", "oid" };
358 for(i=0; i<sizeof(azRowid)/sizeof(azRowid[0]); i++){
359 for(j=1; j<naz; j++){
360 if( sqlite3_stricmp(az[j], azRowid[i])==0 ) break;
361 }
362 if( j>=naz ){
363 az[0] = sqlite3_mprintf("%s", azRowid[i]);
364 break;
365 }
366 }
367 if( az[0]==0 ){
368 for(i=1; i<naz; i++) sqlite3_free(az[i]);
369 sqlite3_free(az);
370 az = 0;
371 }
372 }
373 return az;
374}
375
376/*
377** Print the sqlite3_value X as an SQL literal.
378*/
drh8a1cd762015-04-14 19:01:08 +0000379static void printQuoted(FILE *out, sqlite3_value *X){
drhd62c0f42015-04-09 13:34:29 +0000380 switch( sqlite3_value_type(X) ){
381 case SQLITE_FLOAT: {
382 double r1;
383 char zBuf[50];
384 r1 = sqlite3_value_double(X);
385 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
drh8a1cd762015-04-14 19:01:08 +0000386 fprintf(out, "%s", zBuf);
drhd62c0f42015-04-09 13:34:29 +0000387 break;
388 }
389 case SQLITE_INTEGER: {
drh8a1cd762015-04-14 19:01:08 +0000390 fprintf(out, "%lld", sqlite3_value_int64(X));
drhd62c0f42015-04-09 13:34:29 +0000391 break;
392 }
393 case SQLITE_BLOB: {
394 const unsigned char *zBlob = sqlite3_value_blob(X);
395 int nBlob = sqlite3_value_bytes(X);
396 if( zBlob ){
397 int i;
drh8a1cd762015-04-14 19:01:08 +0000398 fprintf(out, "x'");
drhd62c0f42015-04-09 13:34:29 +0000399 for(i=0; i<nBlob; i++){
drh8a1cd762015-04-14 19:01:08 +0000400 fprintf(out, "%02x", zBlob[i]);
drhd62c0f42015-04-09 13:34:29 +0000401 }
drh8a1cd762015-04-14 19:01:08 +0000402 fprintf(out, "'");
drhd62c0f42015-04-09 13:34:29 +0000403 }else{
drh8a1cd762015-04-14 19:01:08 +0000404 fprintf(out, "NULL");
drhd62c0f42015-04-09 13:34:29 +0000405 }
406 break;
407 }
408 case SQLITE_TEXT: {
409 const unsigned char *zArg = sqlite3_value_text(X);
410 int i, j;
411
412 if( zArg==0 ){
drh8a1cd762015-04-14 19:01:08 +0000413 fprintf(out, "NULL");
drhd62c0f42015-04-09 13:34:29 +0000414 }else{
drh8a1cd762015-04-14 19:01:08 +0000415 fprintf(out, "'");
drhd62c0f42015-04-09 13:34:29 +0000416 for(i=j=0; zArg[i]; i++){
417 if( zArg[i]=='\'' ){
drh8a1cd762015-04-14 19:01:08 +0000418 fprintf(out, "%.*s'", i-j+1, &zArg[j]);
drhd62c0f42015-04-09 13:34:29 +0000419 j = i+1;
420 }
421 }
drh8a1cd762015-04-14 19:01:08 +0000422 fprintf(out, "%s'", &zArg[j]);
drhd62c0f42015-04-09 13:34:29 +0000423 }
424 break;
425 }
426 case SQLITE_NULL: {
drh8a1cd762015-04-14 19:01:08 +0000427 fprintf(out, "NULL");
drhd62c0f42015-04-09 13:34:29 +0000428 break;
429 }
430 }
431}
432
433/*
434** Output SQL that will recreate the aux.zTab table.
435*/
drh8a1cd762015-04-14 19:01:08 +0000436static void dump_table(const char *zTab, FILE *out){
drhd62c0f42015-04-09 13:34:29 +0000437 char *zId = safeId(zTab); /* Name of the table */
438 char **az = 0; /* List of columns */
439 int nPk; /* Number of true primary key columns */
440 int nCol; /* Number of data columns */
441 int i; /* Loop counter */
442 sqlite3_stmt *pStmt; /* SQL statement */
443 const char *zSep; /* Separator string */
444 Str ins; /* Beginning of the INSERT statement */
445
446 pStmt = db_prepare("SELECT sql FROM aux.sqlite_master WHERE name=%Q", zTab);
447 if( SQLITE_ROW==sqlite3_step(pStmt) ){
drh8a1cd762015-04-14 19:01:08 +0000448 fprintf(out, "%s;\n", sqlite3_column_text(pStmt,0));
drhd62c0f42015-04-09 13:34:29 +0000449 }
450 sqlite3_finalize(pStmt);
451 if( !g.bSchemaOnly ){
dan99461852015-07-30 20:26:16 +0000452 az = columnNames("aux", zTab, &nPk, 0);
drhd62c0f42015-04-09 13:34:29 +0000453 strInit(&ins);
454 if( az==0 ){
455 pStmt = db_prepare("SELECT * FROM aux.%s", zId);
456 strPrintf(&ins,"INSERT INTO %s VALUES", zId);
457 }else{
458 Str sql;
459 strInit(&sql);
460 zSep = "SELECT";
461 for(i=0; az[i]; i++){
462 strPrintf(&sql, "%s %s", zSep, az[i]);
463 zSep = ",";
464 }
465 strPrintf(&sql," FROM aux.%s", zId);
466 zSep = " ORDER BY";
467 for(i=1; i<=nPk; i++){
468 strPrintf(&sql, "%s %d", zSep, i);
469 zSep = ",";
470 }
471 pStmt = db_prepare("%s", sql.z);
472 strFree(&sql);
473 strPrintf(&ins, "INSERT INTO %s", zId);
474 zSep = "(";
475 for(i=0; az[i]; i++){
476 strPrintf(&ins, "%s%s", zSep, az[i]);
477 zSep = ",";
478 }
479 strPrintf(&ins,") VALUES");
480 namelistFree(az);
481 }
482 nCol = sqlite3_column_count(pStmt);
483 while( SQLITE_ROW==sqlite3_step(pStmt) ){
drh8a1cd762015-04-14 19:01:08 +0000484 fprintf(out, "%s",ins.z);
drhd62c0f42015-04-09 13:34:29 +0000485 zSep = "(";
486 for(i=0; i<nCol; i++){
drh8a1cd762015-04-14 19:01:08 +0000487 fprintf(out, "%s",zSep);
488 printQuoted(out, sqlite3_column_value(pStmt,i));
drhd62c0f42015-04-09 13:34:29 +0000489 zSep = ",";
490 }
drh8a1cd762015-04-14 19:01:08 +0000491 fprintf(out, ");\n");
drhd62c0f42015-04-09 13:34:29 +0000492 }
493 sqlite3_finalize(pStmt);
494 strFree(&ins);
495 } /* endif !g.bSchemaOnly */
496 pStmt = db_prepare("SELECT sql FROM aux.sqlite_master"
497 " WHERE type='index' AND tbl_name=%Q AND sql IS NOT NULL",
498 zTab);
499 while( SQLITE_ROW==sqlite3_step(pStmt) ){
drh8a1cd762015-04-14 19:01:08 +0000500 fprintf(out, "%s;\n", sqlite3_column_text(pStmt,0));
drhd62c0f42015-04-09 13:34:29 +0000501 }
502 sqlite3_finalize(pStmt);
503}
504
505
506/*
507** Compute all differences for a single table.
508*/
drh8a1cd762015-04-14 19:01:08 +0000509static void diff_one_table(const char *zTab, FILE *out){
drhd62c0f42015-04-09 13:34:29 +0000510 char *zId = safeId(zTab); /* Name of table (translated for us in SQL) */
511 char **az = 0; /* Columns in main */
512 char **az2 = 0; /* Columns in aux */
513 int nPk; /* Primary key columns in main */
514 int nPk2; /* Primary key columns in aux */
drhb3f3d642015-04-25 18:39:21 +0000515 int n = 0; /* Number of columns in main */
drhd62c0f42015-04-09 13:34:29 +0000516 int n2; /* Number of columns in aux */
517 int nQ; /* Number of output columns in the diff query */
518 int i; /* Loop counter */
519 const char *zSep; /* Separator string */
520 Str sql; /* Comparison query */
521 sqlite3_stmt *pStmt; /* Query statement to do the diff */
522
523 strInit(&sql);
524 if( g.fDebug==DEBUG_COLUMN_NAMES ){
525 /* Simply run columnNames() on all tables of the origin
526 ** database and show the results. This is used for testing
527 ** and debugging of the columnNames() function.
528 */
dan99461852015-07-30 20:26:16 +0000529 az = columnNames("aux",zTab, &nPk, 0);
drhd62c0f42015-04-09 13:34:29 +0000530 if( az==0 ){
531 printf("Rowid not accessible for %s\n", zId);
532 }else{
533 printf("%s:", zId);
534 for(i=0; az[i]; i++){
535 printf(" %s", az[i]);
536 if( i+1==nPk ) printf(" *");
537 }
538 printf("\n");
539 }
540 goto end_diff_one_table;
541 }
542
543
544 if( sqlite3_table_column_metadata(g.db,"aux",zTab,0,0,0,0,0,0) ){
545 if( !sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
546 /* Table missing from second database. */
drh8a1cd762015-04-14 19:01:08 +0000547 fprintf(out, "DROP TABLE %s;\n", zId);
drhd62c0f42015-04-09 13:34:29 +0000548 }
549 goto end_diff_one_table;
550 }
551
552 if( sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
553 /* Table missing from source */
drh8a1cd762015-04-14 19:01:08 +0000554 dump_table(zTab, out);
drhd62c0f42015-04-09 13:34:29 +0000555 goto end_diff_one_table;
556 }
557
dan99461852015-07-30 20:26:16 +0000558 az = columnNames("main", zTab, &nPk, 0);
559 az2 = columnNames("aux", zTab, &nPk2, 0);
drhd62c0f42015-04-09 13:34:29 +0000560 if( az && az2 ){
561 for(n=0; az[n]; n++){
562 if( sqlite3_stricmp(az[n],az2[n])!=0 ) break;
563 }
564 }
565 if( az==0
566 || az2==0
567 || nPk!=nPk2
568 || az[n]
569 ){
570 /* Schema mismatch */
drh8a1cd762015-04-14 19:01:08 +0000571 fprintf(out, "DROP TABLE %s;\n", zId);
572 dump_table(zTab, out);
drhd62c0f42015-04-09 13:34:29 +0000573 goto end_diff_one_table;
574 }
575
576 /* Build the comparison query */
577 for(n2=n; az[n2]; n2++){}
578 nQ = nPk2+1+2*(n2-nPk2);
579 if( n2>nPk2 ){
580 zSep = "SELECT ";
581 for(i=0; i<nPk; i++){
582 strPrintf(&sql, "%sB.%s", zSep, az[i]);
583 zSep = ", ";
584 }
585 strPrintf(&sql, ", 1%s -- changed row\n", nPk==n ? "" : ",");
586 while( az[i] ){
587 strPrintf(&sql, " A.%s IS NOT B.%s, B.%s%s\n",
588 az[i], az[i], az[i], i==n2-1 ? "" : ",");
589 i++;
590 }
591 strPrintf(&sql, " FROM main.%s A, aux.%s B\n", zId, zId);
592 zSep = " WHERE";
593 for(i=0; i<nPk; i++){
594 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
595 zSep = " AND";
596 }
597 zSep = "\n AND (";
598 while( az[i] ){
599 strPrintf(&sql, "%sA.%s IS NOT B.%s%s\n",
600 zSep, az[i], az[i], i==n2-1 ? ")" : "");
601 zSep = " OR ";
602 i++;
603 }
604 strPrintf(&sql, " UNION ALL\n");
605 }
606 zSep = "SELECT ";
607 for(i=0; i<nPk; i++){
608 strPrintf(&sql, "%sA.%s", zSep, az[i]);
609 zSep = ", ";
610 }
611 strPrintf(&sql, ", 2%s -- deleted row\n", nPk==n ? "" : ",");
612 while( az[i] ){
613 strPrintf(&sql, " NULL, NULL%s\n", i==n2-1 ? "" : ",");
614 i++;
615 }
616 strPrintf(&sql, " FROM main.%s A\n", zId);
617 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B\n", zId);
618 zSep = " WHERE";
619 for(i=0; i<nPk; i++){
620 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
621 zSep = " AND";
622 }
623 strPrintf(&sql, ")\n");
624 zSep = " UNION ALL\nSELECT ";
625 for(i=0; i<nPk; i++){
626 strPrintf(&sql, "%sB.%s", zSep, az[i]);
627 zSep = ", ";
628 }
629 strPrintf(&sql, ", 3%s -- inserted row\n", nPk==n ? "" : ",");
630 while( az2[i] ){
631 strPrintf(&sql, " 1, B.%s%s\n", az[i], i==n2-1 ? "" : ",");
632 i++;
633 }
634 strPrintf(&sql, " FROM aux.%s B\n", zId);
635 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A\n", zId);
636 zSep = " WHERE";
637 for(i=0; i<nPk; i++){
638 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
639 zSep = " AND";
640 }
641 strPrintf(&sql, ")\n ORDER BY");
642 zSep = " ";
643 for(i=1; i<=nPk; i++){
644 strPrintf(&sql, "%s%d", zSep, i);
645 zSep = ", ";
646 }
647 strPrintf(&sql, ";\n");
648
649 if( g.fDebug & DEBUG_DIFF_SQL ){
650 printf("SQL for %s:\n%s\n", zId, sql.z);
651 goto end_diff_one_table;
652 }
653
654 /* Drop indexes that are missing in the destination */
655 pStmt = db_prepare(
656 "SELECT name FROM main.sqlite_master"
657 " WHERE type='index' AND tbl_name=%Q"
658 " AND sql IS NOT NULL"
659 " AND sql NOT IN (SELECT sql FROM aux.sqlite_master"
660 " WHERE type='index' AND tbl_name=%Q"
661 " AND sql IS NOT NULL)",
662 zTab, zTab);
663 while( SQLITE_ROW==sqlite3_step(pStmt) ){
664 char *z = safeId((const char*)sqlite3_column_text(pStmt,0));
drh8a1cd762015-04-14 19:01:08 +0000665 fprintf(out, "DROP INDEX %s;\n", z);
drhd62c0f42015-04-09 13:34:29 +0000666 sqlite3_free(z);
667 }
668 sqlite3_finalize(pStmt);
669
670 /* Run the query and output differences */
671 if( !g.bSchemaOnly ){
672 pStmt = db_prepare(sql.z);
673 while( SQLITE_ROW==sqlite3_step(pStmt) ){
674 int iType = sqlite3_column_int(pStmt, nPk);
675 if( iType==1 || iType==2 ){
676 if( iType==1 ){ /* Change the content of a row */
drh8a1cd762015-04-14 19:01:08 +0000677 fprintf(out, "UPDATE %s", zId);
drhd62c0f42015-04-09 13:34:29 +0000678 zSep = " SET";
679 for(i=nPk+1; i<nQ; i+=2){
680 if( sqlite3_column_int(pStmt,i)==0 ) continue;
drh8a1cd762015-04-14 19:01:08 +0000681 fprintf(out, "%s %s=", zSep, az2[(i+nPk-1)/2]);
drhd62c0f42015-04-09 13:34:29 +0000682 zSep = ",";
drh8a1cd762015-04-14 19:01:08 +0000683 printQuoted(out, sqlite3_column_value(pStmt,i+1));
drhd62c0f42015-04-09 13:34:29 +0000684 }
685 }else{ /* Delete a row */
drh8a1cd762015-04-14 19:01:08 +0000686 fprintf(out, "DELETE FROM %s", zId);
drhd62c0f42015-04-09 13:34:29 +0000687 }
688 zSep = " WHERE";
689 for(i=0; i<nPk; i++){
drh8a1cd762015-04-14 19:01:08 +0000690 fprintf(out, "%s %s=", zSep, az2[i]);
691 printQuoted(out, sqlite3_column_value(pStmt,i));
drhd62c0f42015-04-09 13:34:29 +0000692 zSep = ",";
693 }
drh8a1cd762015-04-14 19:01:08 +0000694 fprintf(out, ";\n");
drhd62c0f42015-04-09 13:34:29 +0000695 }else{ /* Insert a row */
drh8a1cd762015-04-14 19:01:08 +0000696 fprintf(out, "INSERT INTO %s(%s", zId, az2[0]);
697 for(i=1; az2[i]; i++) fprintf(out, ",%s", az2[i]);
698 fprintf(out, ") VALUES");
drhd62c0f42015-04-09 13:34:29 +0000699 zSep = "(";
700 for(i=0; i<nPk2; i++){
drh8a1cd762015-04-14 19:01:08 +0000701 fprintf(out, "%s", zSep);
drhd62c0f42015-04-09 13:34:29 +0000702 zSep = ",";
drh8a1cd762015-04-14 19:01:08 +0000703 printQuoted(out, sqlite3_column_value(pStmt,i));
drhd62c0f42015-04-09 13:34:29 +0000704 }
705 for(i=nPk2+2; i<nQ; i+=2){
drh8a1cd762015-04-14 19:01:08 +0000706 fprintf(out, ",");
707 printQuoted(out, sqlite3_column_value(pStmt,i));
drhd62c0f42015-04-09 13:34:29 +0000708 }
drh8a1cd762015-04-14 19:01:08 +0000709 fprintf(out, ");\n");
drhd62c0f42015-04-09 13:34:29 +0000710 }
711 }
712 sqlite3_finalize(pStmt);
713 } /* endif !g.bSchemaOnly */
714
715 /* Create indexes that are missing in the source */
716 pStmt = db_prepare(
717 "SELECT sql FROM aux.sqlite_master"
718 " WHERE type='index' AND tbl_name=%Q"
719 " AND sql IS NOT NULL"
720 " AND sql NOT IN (SELECT sql FROM main.sqlite_master"
721 " WHERE type='index' AND tbl_name=%Q"
722 " AND sql IS NOT NULL)",
723 zTab, zTab);
724 while( SQLITE_ROW==sqlite3_step(pStmt) ){
drh8a1cd762015-04-14 19:01:08 +0000725 fprintf(out, "%s;\n", sqlite3_column_text(pStmt,0));
drhd62c0f42015-04-09 13:34:29 +0000726 }
727 sqlite3_finalize(pStmt);
728
729end_diff_one_table:
730 strFree(&sql);
731 sqlite3_free(zId);
732 namelistFree(az);
733 namelistFree(az2);
734 return;
735}
736
737/*
dan99461852015-07-30 20:26:16 +0000738** Check that table zTab exists and has the same schema in both the "main"
739** and "aux" databases currently opened by the global db handle. If they
740** do not, output an error message on stderr and exit(1). Otherwise, if
741** the schemas do match, return control to the caller.
742*/
743static void checkSchemasMatch(const char *zTab){
744 sqlite3_stmt *pStmt = db_prepare(
745 "SELECT A.sql=B.sql FROM main.sqlite_master A, aux.sqlite_master B"
746 " WHERE A.name=%Q AND B.name=%Q", zTab, zTab
747 );
748 if( SQLITE_ROW==sqlite3_step(pStmt) ){
749 if( sqlite3_column_int(pStmt,0)==0 ){
750 runtimeError("schema changes for table %s", safeId(zTab));
751 }
752 }else{
753 runtimeError("table %s missing from one or both databases", safeId(zTab));
754 }
755 sqlite3_finalize(pStmt);
756}
757
dana9ca8af2015-07-31 19:52:03 +0000758/**************************************************************************
759** The following code is copied from fossil. It is used to generate the
760** fossil delta blobs sometimes used in RBU update records.
761*/
762
763typedef unsigned short u16;
764typedef unsigned int u32;
765typedef unsigned char u8;
766
767/*
768** The width of a hash window in bytes. The algorithm only works if this
769** is a power of 2.
770*/
771#define NHASH 16
772
773/*
774** The current state of the rolling hash.
775**
776** z[] holds the values that have been hashed. z[] is a circular buffer.
777** z[i] is the first entry and z[(i+NHASH-1)%NHASH] is the last entry of
778** the window.
779**
780** Hash.a is the sum of all elements of hash.z[]. Hash.b is a weighted
781** sum. Hash.b is z[i]*NHASH + z[i+1]*(NHASH-1) + ... + z[i+NHASH-1]*1.
782** (Each index for z[] should be module NHASH, of course. The %NHASH operator
783** is omitted in the prior expression for brevity.)
784*/
785typedef struct hash hash;
786struct hash {
787 u16 a, b; /* Hash values */
788 u16 i; /* Start of the hash window */
789 char z[NHASH]; /* The values that have been hashed */
790};
791
792/*
793** Initialize the rolling hash using the first NHASH characters of z[]
794*/
795static void hash_init(hash *pHash, const char *z){
796 u16 a, b, i;
797 a = b = 0;
798 for(i=0; i<NHASH; i++){
799 a += z[i];
800 b += (NHASH-i)*z[i];
801 pHash->z[i] = z[i];
802 }
803 pHash->a = a & 0xffff;
804 pHash->b = b & 0xffff;
805 pHash->i = 0;
806}
807
808/*
809** Advance the rolling hash by a single character "c"
810*/
811static void hash_next(hash *pHash, int c){
812 u16 old = pHash->z[pHash->i];
mistachkin1abbe282015-08-20 21:09:32 +0000813 pHash->z[pHash->i] = (char)c;
dana9ca8af2015-07-31 19:52:03 +0000814 pHash->i = (pHash->i+1)&(NHASH-1);
mistachkin1abbe282015-08-20 21:09:32 +0000815 pHash->a = pHash->a - old + (char)c;
dana9ca8af2015-07-31 19:52:03 +0000816 pHash->b = pHash->b - NHASH*old + pHash->a;
817}
818
819/*
820** Return a 32-bit hash value
821*/
822static u32 hash_32bit(hash *pHash){
823 return (pHash->a & 0xffff) | (((u32)(pHash->b & 0xffff))<<16);
824}
825
826/*
827** Write an base-64 integer into the given buffer.
828*/
829static void putInt(unsigned int v, char **pz){
830 static const char zDigits[] =
831 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~";
832 /* 123456789 123456789 123456789 123456789 123456789 123456789 123 */
833 int i, j;
834 char zBuf[20];
835 if( v==0 ){
836 *(*pz)++ = '0';
837 return;
838 }
839 for(i=0; v>0; i++, v>>=6){
840 zBuf[i] = zDigits[v&0x3f];
841 }
842 for(j=i-1; j>=0; j--){
843 *(*pz)++ = zBuf[j];
844 }
845}
846
847/*
dana9ca8af2015-07-31 19:52:03 +0000848** Return the number digits in the base-64 representation of a positive integer
849*/
850static int digit_count(int v){
851 unsigned int i, x;
mistachkin1abbe282015-08-20 21:09:32 +0000852 for(i=1, x=64; (unsigned int)v>=x; i++, x <<= 6){}
dana9ca8af2015-07-31 19:52:03 +0000853 return i;
854}
855
856/*
857** Compute a 32-bit checksum on the N-byte buffer. Return the result.
858*/
859static unsigned int checksum(const char *zIn, size_t N){
860 const unsigned char *z = (const unsigned char *)zIn;
861 unsigned sum0 = 0;
862 unsigned sum1 = 0;
863 unsigned sum2 = 0;
864 unsigned sum3 = 0;
865 while(N >= 16){
866 sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
867 sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
868 sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
869 sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
870 z += 16;
871 N -= 16;
872 }
873 while(N >= 4){
874 sum0 += z[0];
875 sum1 += z[1];
876 sum2 += z[2];
877 sum3 += z[3];
878 z += 4;
879 N -= 4;
880 }
881 sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
882 switch(N){
883 case 3: sum3 += (z[2] << 8);
884 case 2: sum3 += (z[1] << 16);
885 case 1: sum3 += (z[0] << 24);
886 default: ;
887 }
888 return sum3;
889}
890
891/*
892** Create a new delta.
893**
894** The delta is written into a preallocated buffer, zDelta, which
895** should be at least 60 bytes longer than the target file, zOut.
896** The delta string will be NUL-terminated, but it might also contain
897** embedded NUL characters if either the zSrc or zOut files are
898** binary. This function returns the length of the delta string
899** in bytes, excluding the final NUL terminator character.
900**
901** Output Format:
902**
903** The delta begins with a base64 number followed by a newline. This
904** number is the number of bytes in the TARGET file. Thus, given a
905** delta file z, a program can compute the size of the output file
906** simply by reading the first line and decoding the base-64 number
907** found there. The delta_output_size() routine does exactly this.
908**
909** After the initial size number, the delta consists of a series of
910** literal text segments and commands to copy from the SOURCE file.
911** A copy command looks like this:
912**
913** NNN@MMM,
914**
915** where NNN is the number of bytes to be copied and MMM is the offset
916** into the source file of the first byte (both base-64). If NNN is 0
917** it means copy the rest of the input file. Literal text is like this:
918**
919** NNN:TTTTT
920**
921** where NNN is the number of bytes of text (base-64) and TTTTT is the text.
922**
923** The last term is of the form
924**
925** NNN;
926**
927** In this case, NNN is a 32-bit bigendian checksum of the output file
928** that can be used to verify that the delta applied correctly. All
929** numbers are in base-64.
930**
931** Pure text files generate a pure text delta. Binary files generate a
932** delta that may contain some binary data.
933**
934** Algorithm:
935**
936** The encoder first builds a hash table to help it find matching
937** patterns in the source file. 16-byte chunks of the source file
938** sampled at evenly spaced intervals are used to populate the hash
939** table.
940**
941** Next we begin scanning the target file using a sliding 16-byte
942** window. The hash of the 16-byte window in the target is used to
943** search for a matching section in the source file. When a match
944** is found, a copy command is added to the delta. An effort is
945** made to extend the matching section to regions that come before
946** and after the 16-byte hash window. A copy command is only issued
947** if the result would use less space that just quoting the text
948** literally. Literal text is added to the delta for sections that
949** do not match or which can not be encoded efficiently using copy
950** commands.
951*/
952static int rbuDeltaCreate(
953 const char *zSrc, /* The source or pattern file */
954 unsigned int lenSrc, /* Length of the source file */
955 const char *zOut, /* The target file */
956 unsigned int lenOut, /* Length of the target file */
957 char *zDelta /* Write the delta into this buffer */
958){
mistachkin1abbe282015-08-20 21:09:32 +0000959 unsigned int i, base;
dana9ca8af2015-07-31 19:52:03 +0000960 char *zOrigDelta = zDelta;
961 hash h;
962 int nHash; /* Number of hash table entries */
963 int *landmark; /* Primary hash table */
964 int *collide; /* Collision chain */
965 int lastRead = -1; /* Last byte of zSrc read by a COPY command */
966
967 /* Add the target file size to the beginning of the delta
968 */
969 putInt(lenOut, &zDelta);
970 *(zDelta++) = '\n';
971
972 /* If the source file is very small, it means that we have no
973 ** chance of ever doing a copy command. Just output a single
974 ** literal segment for the entire target and exit.
975 */
976 if( lenSrc<=NHASH ){
977 putInt(lenOut, &zDelta);
978 *(zDelta++) = ':';
979 memcpy(zDelta, zOut, lenOut);
980 zDelta += lenOut;
981 putInt(checksum(zOut, lenOut), &zDelta);
982 *(zDelta++) = ';';
983 return zDelta - zOrigDelta;
984 }
985
986 /* Compute the hash table used to locate matching sections in the
987 ** source file.
988 */
989 nHash = lenSrc/NHASH;
990 collide = sqlite3_malloc( nHash*2*sizeof(int) );
991 landmark = &collide[nHash];
992 memset(landmark, -1, nHash*sizeof(int));
993 memset(collide, -1, nHash*sizeof(int));
994 for(i=0; i<lenSrc-NHASH; i+=NHASH){
995 int hv;
996 hash_init(&h, &zSrc[i]);
997 hv = hash_32bit(&h) % nHash;
998 collide[i/NHASH] = landmark[hv];
999 landmark[hv] = i/NHASH;
1000 }
1001
1002 /* Begin scanning the target file and generating copy commands and
1003 ** literal sections of the delta.
1004 */
1005 base = 0; /* We have already generated everything before zOut[base] */
1006 while( base+NHASH<lenOut ){
1007 int iSrc, iBlock;
mistachkin1abbe282015-08-20 21:09:32 +00001008 int bestCnt, bestOfst=0, bestLitsz=0;
dana9ca8af2015-07-31 19:52:03 +00001009 hash_init(&h, &zOut[base]);
1010 i = 0; /* Trying to match a landmark against zOut[base+i] */
1011 bestCnt = 0;
1012 while( 1 ){
1013 int hv;
1014 int limit = 250;
1015
1016 hv = hash_32bit(&h) % nHash;
1017 iBlock = landmark[hv];
1018 while( iBlock>=0 && (limit--)>0 ){
1019 /*
1020 ** The hash window has identified a potential match against
1021 ** landmark block iBlock. But we need to investigate further.
1022 **
1023 ** Look for a region in zOut that matches zSrc. Anchor the search
1024 ** at zSrc[iSrc] and zOut[base+i]. Do not include anything prior to
1025 ** zOut[base] or after zOut[outLen] nor anything after zSrc[srcLen].
1026 **
1027 ** Set cnt equal to the length of the match and set ofst so that
1028 ** zSrc[ofst] is the first element of the match. litsz is the number
1029 ** of characters between zOut[base] and the beginning of the match.
1030 ** sz will be the overhead (in bytes) needed to encode the copy
1031 ** command. Only generate copy command if the overhead of the
1032 ** copy command is less than the amount of literal text to be copied.
1033 */
1034 int cnt, ofst, litsz;
1035 int j, k, x, y;
1036 int sz;
1037
1038 /* Beginning at iSrc, match forwards as far as we can. j counts
1039 ** the number of characters that match */
1040 iSrc = iBlock*NHASH;
mistachkin1abbe282015-08-20 21:09:32 +00001041 for(
1042 j=0, x=iSrc, y=base+i;
1043 (unsigned int)x<lenSrc && (unsigned int)y<lenOut;
1044 j++, x++, y++
1045 ){
dana9ca8af2015-07-31 19:52:03 +00001046 if( zSrc[x]!=zOut[y] ) break;
1047 }
1048 j--;
1049
1050 /* Beginning at iSrc-1, match backwards as far as we can. k counts
1051 ** the number of characters that match */
mistachkin1abbe282015-08-20 21:09:32 +00001052 for(k=1; k<iSrc && (unsigned int)k<=i; k++){
dana9ca8af2015-07-31 19:52:03 +00001053 if( zSrc[iSrc-k]!=zOut[base+i-k] ) break;
1054 }
1055 k--;
1056
1057 /* Compute the offset and size of the matching region */
1058 ofst = iSrc-k;
1059 cnt = j+k+1;
1060 litsz = i-k; /* Number of bytes of literal text before the copy */
1061 /* sz will hold the number of bytes needed to encode the "insert"
1062 ** command and the copy command, not counting the "insert" text */
1063 sz = digit_count(i-k)+digit_count(cnt)+digit_count(ofst)+3;
1064 if( cnt>=sz && cnt>bestCnt ){
1065 /* Remember this match only if it is the best so far and it
1066 ** does not increase the file size */
1067 bestCnt = cnt;
1068 bestOfst = iSrc-k;
1069 bestLitsz = litsz;
1070 }
1071
1072 /* Check the next matching block */
1073 iBlock = collide[iBlock];
1074 }
1075
1076 /* We have a copy command that does not cause the delta to be larger
1077 ** than a literal insert. So add the copy command to the delta.
1078 */
1079 if( bestCnt>0 ){
1080 if( bestLitsz>0 ){
1081 /* Add an insert command before the copy */
1082 putInt(bestLitsz,&zDelta);
1083 *(zDelta++) = ':';
1084 memcpy(zDelta, &zOut[base], bestLitsz);
1085 zDelta += bestLitsz;
1086 base += bestLitsz;
1087 }
1088 base += bestCnt;
1089 putInt(bestCnt, &zDelta);
1090 *(zDelta++) = '@';
1091 putInt(bestOfst, &zDelta);
1092 *(zDelta++) = ',';
1093 if( bestOfst + bestCnt -1 > lastRead ){
1094 lastRead = bestOfst + bestCnt - 1;
1095 }
1096 bestCnt = 0;
1097 break;
1098 }
1099
1100 /* If we reach this point, it means no match is found so far */
1101 if( base+i+NHASH>=lenOut ){
1102 /* We have reached the end of the file and have not found any
1103 ** matches. Do an "insert" for everything that does not match */
1104 putInt(lenOut-base, &zDelta);
1105 *(zDelta++) = ':';
1106 memcpy(zDelta, &zOut[base], lenOut-base);
1107 zDelta += lenOut-base;
1108 base = lenOut;
1109 break;
1110 }
1111
1112 /* Advance the hash by one character. Keep looking for a match */
1113 hash_next(&h, zOut[base+i+NHASH]);
1114 i++;
1115 }
1116 }
1117 /* Output a final "insert" record to get all the text at the end of
1118 ** the file that does not match anything in the source file.
1119 */
1120 if( base<lenOut ){
1121 putInt(lenOut-base, &zDelta);
1122 *(zDelta++) = ':';
1123 memcpy(zDelta, &zOut[base], lenOut-base);
1124 zDelta += lenOut-base;
1125 }
1126 /* Output the final checksum record. */
1127 putInt(checksum(zOut, lenOut), &zDelta);
1128 *(zDelta++) = ';';
1129 sqlite3_free(collide);
1130 return zDelta - zOrigDelta;
1131}
1132
1133/*
1134** End of code copied from fossil.
1135**************************************************************************/
1136
dan99461852015-07-30 20:26:16 +00001137static void strPrintfArray(
1138 Str *pStr, /* String object to append to */
1139 const char *zSep, /* Separator string */
1140 const char *zFmt, /* Format for each entry */
1141 char **az, int n /* Array of strings & its size (or -1) */
1142){
1143 int i;
1144 for(i=0; az[i] && (i<n || n<0); i++){
1145 if( i!=0 ) strPrintf(pStr, "%s", zSep);
1146 strPrintf(pStr, zFmt, az[i], az[i], az[i]);
1147 }
1148}
1149
1150static void getRbudiffQuery(
1151 const char *zTab,
1152 char **azCol,
1153 int nPK,
1154 int bOtaRowid,
1155 Str *pSql
1156){
1157 int i;
1158
1159 /* First the newly inserted rows: **/
1160 strPrintf(pSql, "SELECT ");
1161 strPrintfArray(pSql, ", ", "%s", azCol, -1);
dana9ca8af2015-07-31 19:52:03 +00001162 strPrintf(pSql, ", 0, "); /* Set ota_control to 0 for an insert */
1163 strPrintfArray(pSql, ", ", "NULL", azCol, -1);
dan99461852015-07-30 20:26:16 +00001164 strPrintf(pSql, " FROM aux.%Q AS n WHERE NOT EXISTS (\n", zTab);
1165 strPrintf(pSql, " SELECT 1 FROM ", zTab);
1166 strPrintf(pSql, " main.%Q AS o WHERE ", zTab);
1167 strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
1168 strPrintf(pSql, "\n)");
1169
1170 /* Deleted rows: */
1171 strPrintf(pSql, "\nUNION ALL\nSELECT ");
1172 strPrintfArray(pSql, ", ", "%s", azCol, nPK);
dandd688e72015-07-31 15:13:29 +00001173 if( azCol[nPK] ){
1174 strPrintf(pSql, ", ");
1175 strPrintfArray(pSql, ", ", "NULL", &azCol[nPK], -1);
1176 }
dana9ca8af2015-07-31 19:52:03 +00001177 strPrintf(pSql, ", 1, "); /* Set ota_control to 1 for a delete */
1178 strPrintfArray(pSql, ", ", "NULL", azCol, -1);
dan99461852015-07-30 20:26:16 +00001179 strPrintf(pSql, " FROM main.%Q AS n WHERE NOT EXISTS (\n", zTab);
1180 strPrintf(pSql, " SELECT 1 FROM ", zTab);
1181 strPrintf(pSql, " aux.%Q AS o WHERE ", zTab);
1182 strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
1183 strPrintf(pSql, "\n) ");
1184
dandd688e72015-07-31 15:13:29 +00001185 /* Updated rows. If all table columns are part of the primary key, there
1186 ** can be no updates. In this case this part of the compound SELECT can
1187 ** be omitted altogether. */
1188 if( azCol[nPK] ){
1189 strPrintf(pSql, "\nUNION ALL\nSELECT ");
1190 strPrintfArray(pSql, ", ", "n.%s", azCol, nPK);
dan99461852015-07-30 20:26:16 +00001191 strPrintf(pSql, ",\n");
dandd688e72015-07-31 15:13:29 +00001192 strPrintfArray(pSql, " ,\n",
1193 " CASE WHEN n.%s IS o.%s THEN NULL ELSE n.%s END", &azCol[nPK], -1
1194 );
dan99461852015-07-30 20:26:16 +00001195
dandd688e72015-07-31 15:13:29 +00001196 if( bOtaRowid==0 ){
1197 strPrintf(pSql, ", '");
1198 strPrintfArray(pSql, "", ".", azCol, nPK);
1199 strPrintf(pSql, "' ||\n");
1200 }else{
1201 strPrintf(pSql, ",\n");
1202 }
1203 strPrintfArray(pSql, " ||\n",
1204 " CASE WHEN n.%s IS o.%s THEN '.' ELSE 'x' END", &azCol[nPK], -1
1205 );
dana9ca8af2015-07-31 19:52:03 +00001206 strPrintf(pSql, "\nAS ota_control, ");
1207 strPrintfArray(pSql, ", ", "NULL", azCol, nPK);
1208 strPrintf(pSql, ",\n");
1209 strPrintfArray(pSql, " ,\n",
1210 " CASE WHEN n.%s IS o.%s THEN NULL ELSE o.%s END", &azCol[nPK], -1
1211 );
dandd688e72015-07-31 15:13:29 +00001212
1213 strPrintf(pSql, "\nFROM main.%Q AS o, aux.%Q AS n\nWHERE ", zTab, zTab);
1214 strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
1215 strPrintf(pSql, " AND ota_control LIKE '%%x%%'");
1216 }
dan99461852015-07-30 20:26:16 +00001217
1218 /* Now add an ORDER BY clause to sort everything by PK. */
1219 strPrintf(pSql, "\nORDER BY ");
1220 for(i=1; i<=nPK; i++) strPrintf(pSql, "%s%d", ((i>1)?", ":""), i);
1221}
1222
1223static void rbudiff_one_table(const char *zTab, FILE *out){
1224 int bOtaRowid; /* True to use an ota_rowid column */
1225 int nPK; /* Number of primary key columns in table */
1226 char **azCol; /* NULL terminated array of col names */
1227 int i;
1228 int nCol;
1229 Str ct = {0, 0, 0}; /* The "CREATE TABLE data_xxx" statement */
1230 Str sql = {0, 0, 0}; /* Query to find differences */
1231 Str insert = {0, 0, 0}; /* First part of output INSERT statement */
1232 sqlite3_stmt *pStmt = 0;
1233
1234 /* --rbu mode must use real primary keys. */
1235 g.bSchemaPK = 1;
1236
1237 /* Check that the schemas of the two tables match. Exit early otherwise. */
1238 checkSchemasMatch(zTab);
1239
1240 /* Grab the column names and PK details for the table(s). If no usable PK
1241 ** columns are found, bail out early. */
1242 azCol = columnNames("main", zTab, &nPK, &bOtaRowid);
1243 if( azCol==0 ){
1244 runtimeError("table %s has no usable PK columns", zTab);
1245 }
dana9ca8af2015-07-31 19:52:03 +00001246 for(nCol=0; azCol[nCol]; nCol++);
dan99461852015-07-30 20:26:16 +00001247
1248 /* Build and output the CREATE TABLE statement for the data_xxx table */
1249 strPrintf(&ct, "CREATE TABLE IF NOT EXISTS 'data_%q'(", zTab);
1250 if( bOtaRowid ) strPrintf(&ct, "rbu_rowid, ");
1251 strPrintfArray(&ct, ", ", "%s", &azCol[bOtaRowid], -1);
1252 strPrintf(&ct, ", rbu_control);");
1253
dan99461852015-07-30 20:26:16 +00001254 /* Get the SQL for the query to retrieve data from the two databases */
1255 getRbudiffQuery(zTab, azCol, nPK, bOtaRowid, &sql);
1256
1257 /* Build the first part of the INSERT statement output for each row
1258 ** in the data_xxx table. */
1259 strPrintf(&insert, "INSERT INTO 'data_%q' (", zTab);
1260 if( bOtaRowid ) strPrintf(&insert, "rbu_rowid, ");
1261 strPrintfArray(&insert, ", ", "%s", &azCol[bOtaRowid], -1);
1262 strPrintf(&insert, ", rbu_control) VALUES(");
1263
1264 pStmt = db_prepare("%s", sql.z);
dana9ca8af2015-07-31 19:52:03 +00001265
dan99461852015-07-30 20:26:16 +00001266 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dana9ca8af2015-07-31 19:52:03 +00001267
1268 /* If this is the first row output, print out the CREATE TABLE
1269 ** statement first. And then set ct.z to NULL so that it is not
1270 ** printed again. */
dan99461852015-07-30 20:26:16 +00001271 if( ct.z ){
1272 fprintf(out, "%s\n", ct.z);
1273 strFree(&ct);
1274 }
1275
dana9ca8af2015-07-31 19:52:03 +00001276 /* Output the first part of the INSERT statement */
dan99461852015-07-30 20:26:16 +00001277 fprintf(out, "%s", insert.z);
dana9ca8af2015-07-31 19:52:03 +00001278
1279 if( sqlite3_column_type(pStmt, nCol)==SQLITE_INTEGER ){
1280 for(i=0; i<=nCol; i++){
1281 if( i>0 ) fprintf(out, ", ");
1282 printQuoted(out, sqlite3_column_value(pStmt, i));
1283 }
1284 }else{
1285 char *zOtaControl;
1286 int nOtaControl = sqlite3_column_bytes(pStmt, nCol);
1287
1288 zOtaControl = (char*)sqlite3_malloc(nOtaControl);
1289 memcpy(zOtaControl, sqlite3_column_text(pStmt, nCol), nOtaControl+1);
1290
1291 for(i=0; i<nCol; i++){
1292 int bDone = 0;
1293 if( i>=nPK
1294 && sqlite3_column_type(pStmt, i)==SQLITE_BLOB
1295 && sqlite3_column_type(pStmt, nCol+1+i)==SQLITE_BLOB
1296 ){
1297 const char *aSrc = sqlite3_column_blob(pStmt, nCol+1+i);
1298 int nSrc = sqlite3_column_bytes(pStmt, nCol+1+i);
1299 const char *aFinal = sqlite3_column_blob(pStmt, i);
1300 int nFinal = sqlite3_column_bytes(pStmt, i);
1301 char *aDelta;
1302 int nDelta;
1303
1304 aDelta = sqlite3_malloc(nFinal + 60);
1305 nDelta = rbuDeltaCreate(aSrc, nSrc, aFinal, nFinal, aDelta);
1306 if( nDelta<nFinal ){
1307 int j;
1308 fprintf(out, "x'");
1309 for(j=0; j<nDelta; j++) fprintf(out, "%02x", (u8)aDelta[j]);
1310 fprintf(out, "'");
1311 zOtaControl[i-bOtaRowid] = 'f';
1312 bDone = 1;
1313 }
1314 sqlite3_free(aDelta);
1315 }
1316
1317 if( bDone==0 ){
1318 printQuoted(out, sqlite3_column_value(pStmt, i));
1319 }
1320 fprintf(out, ", ");
1321 }
1322 fprintf(out, "'%s'", zOtaControl);
1323 sqlite3_free(zOtaControl);
dan99461852015-07-30 20:26:16 +00001324 }
dana9ca8af2015-07-31 19:52:03 +00001325
1326 /* And the closing bracket of the insert statement */
dan99461852015-07-30 20:26:16 +00001327 fprintf(out, ");\n");
1328 }
1329
1330 sqlite3_finalize(pStmt);
1331
1332 strFree(&ct);
1333 strFree(&sql);
1334 strFree(&insert);
1335}
1336
1337/*
drh8a1cd762015-04-14 19:01:08 +00001338** Display a summary of differences between two versions of the same
1339** table table.
1340**
1341** * Number of rows changed
1342** * Number of rows added
1343** * Number of rows deleted
1344** * Number of identical rows
1345*/
1346static void summarize_one_table(const char *zTab, FILE *out){
1347 char *zId = safeId(zTab); /* Name of table (translated for us in SQL) */
1348 char **az = 0; /* Columns in main */
1349 char **az2 = 0; /* Columns in aux */
1350 int nPk; /* Primary key columns in main */
1351 int nPk2; /* Primary key columns in aux */
drhb3f3d642015-04-25 18:39:21 +00001352 int n = 0; /* Number of columns in main */
drh8a1cd762015-04-14 19:01:08 +00001353 int n2; /* Number of columns in aux */
1354 int i; /* Loop counter */
1355 const char *zSep; /* Separator string */
1356 Str sql; /* Comparison query */
1357 sqlite3_stmt *pStmt; /* Query statement to do the diff */
1358 sqlite3_int64 nUpdate; /* Number of updated rows */
1359 sqlite3_int64 nUnchanged; /* Number of unmodified rows */
1360 sqlite3_int64 nDelete; /* Number of deleted rows */
1361 sqlite3_int64 nInsert; /* Number of inserted rows */
1362
1363 strInit(&sql);
1364 if( sqlite3_table_column_metadata(g.db,"aux",zTab,0,0,0,0,0,0) ){
1365 if( !sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
1366 /* Table missing from second database. */
1367 fprintf(out, "%s: missing from second database\n", zTab);
1368 }
1369 goto end_summarize_one_table;
1370 }
1371
1372 if( sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
1373 /* Table missing from source */
1374 fprintf(out, "%s: missing from first database\n", zTab);
1375 goto end_summarize_one_table;
1376 }
1377
dan99461852015-07-30 20:26:16 +00001378 az = columnNames("main", zTab, &nPk, 0);
1379 az2 = columnNames("aux", zTab, &nPk2, 0);
drh8a1cd762015-04-14 19:01:08 +00001380 if( az && az2 ){
1381 for(n=0; az[n]; n++){
1382 if( sqlite3_stricmp(az[n],az2[n])!=0 ) break;
1383 }
1384 }
1385 if( az==0
1386 || az2==0
1387 || nPk!=nPk2
1388 || az[n]
1389 ){
1390 /* Schema mismatch */
1391 fprintf(out, "%s: incompatible schema\n", zTab);
1392 goto end_summarize_one_table;
1393 }
1394
1395 /* Build the comparison query */
1396 for(n2=n; az[n2]; n2++){}
1397 strPrintf(&sql, "SELECT 1, count(*)");
1398 if( n2==nPk2 ){
1399 strPrintf(&sql, ", 0\n");
1400 }else{
1401 zSep = ", sum(";
1402 for(i=nPk; az[i]; i++){
1403 strPrintf(&sql, "%sA.%s IS NOT B.%s", zSep, az[i], az[i]);
1404 zSep = " OR ";
1405 }
1406 strPrintf(&sql, ")\n");
1407 }
1408 strPrintf(&sql, " FROM main.%s A, aux.%s B\n", zId, zId);
1409 zSep = " WHERE";
1410 for(i=0; i<nPk; i++){
1411 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1412 zSep = " AND";
1413 }
1414 strPrintf(&sql, " UNION ALL\n");
1415 strPrintf(&sql, "SELECT 2, count(*), 0\n");
1416 strPrintf(&sql, " FROM main.%s A\n", zId);
1417 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B ", zId);
1418 zSep = "WHERE";
1419 for(i=0; i<nPk; i++){
1420 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1421 zSep = " AND";
1422 }
1423 strPrintf(&sql, ")\n");
1424 strPrintf(&sql, " UNION ALL\n");
1425 strPrintf(&sql, "SELECT 3, count(*), 0\n");
1426 strPrintf(&sql, " FROM aux.%s B\n", zId);
1427 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A ", zId);
1428 zSep = "WHERE";
1429 for(i=0; i<nPk; i++){
1430 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1431 zSep = " AND";
1432 }
1433 strPrintf(&sql, ")\n ORDER BY 1;\n");
1434
1435 if( (g.fDebug & DEBUG_DIFF_SQL)!=0 ){
1436 printf("SQL for %s:\n%s\n", zId, sql.z);
1437 goto end_summarize_one_table;
1438 }
1439
1440 /* Run the query and output difference summary */
1441 pStmt = db_prepare(sql.z);
1442 nUpdate = 0;
1443 nInsert = 0;
1444 nDelete = 0;
1445 nUnchanged = 0;
1446 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1447 switch( sqlite3_column_int(pStmt,0) ){
1448 case 1:
1449 nUpdate = sqlite3_column_int64(pStmt,2);
1450 nUnchanged = sqlite3_column_int64(pStmt,1) - nUpdate;
1451 break;
1452 case 2:
1453 nDelete = sqlite3_column_int64(pStmt,1);
1454 break;
1455 case 3:
1456 nInsert = sqlite3_column_int64(pStmt,1);
1457 break;
1458 }
1459 }
1460 sqlite3_finalize(pStmt);
1461 fprintf(out, "%s: %lld changes, %lld inserts, %lld deletes, %lld unchanged\n",
1462 zTab, nUpdate, nInsert, nDelete, nUnchanged);
1463
1464end_summarize_one_table:
1465 strFree(&sql);
1466 sqlite3_free(zId);
1467 namelistFree(az);
1468 namelistFree(az2);
1469 return;
1470}
1471
1472/*
drh697e5db2015-04-11 12:07:40 +00001473** Write a 64-bit signed integer as a varint onto out
1474*/
1475static void putsVarint(FILE *out, sqlite3_uint64 v){
1476 int i, n;
drh6e42ce42015-04-11 13:48:01 +00001477 unsigned char p[12];
drh697e5db2015-04-11 12:07:40 +00001478 if( v & (((sqlite3_uint64)0xff000000)<<32) ){
1479 p[8] = (unsigned char)v;
1480 v >>= 8;
1481 for(i=7; i>=0; i--){
1482 p[i] = (unsigned char)((v & 0x7f) | 0x80);
1483 v >>= 7;
1484 }
1485 fwrite(p, 8, 1, out);
1486 }else{
1487 n = 9;
1488 do{
1489 p[n--] = (unsigned char)((v & 0x7f) | 0x80);
1490 v >>= 7;
1491 }while( v!=0 );
drh6e42ce42015-04-11 13:48:01 +00001492 p[9] &= 0x7f;
1493 fwrite(p+n+1, 9-n, 1, out);
1494 }
1495}
1496
1497/*
1498** Write an SQLite value onto out.
1499*/
1500static void putValue(FILE *out, sqlite3_value *pVal){
1501 int iDType = sqlite3_value_type(pVal);
1502 sqlite3_int64 iX;
1503 double rX;
1504 sqlite3_uint64 uX;
1505 int j;
1506
1507 putc(iDType, out);
1508 switch( iDType ){
1509 case SQLITE_INTEGER:
1510 iX = sqlite3_value_int64(pVal);
1511 memcpy(&uX, &iX, 8);
1512 for(j=56; j>=0; j-=8) putc((uX>>j)&0xff, out);
1513 break;
1514 case SQLITE_FLOAT:
drh33aa4db2015-05-04 15:04:47 +00001515 rX = sqlite3_value_double(pVal);
drh6e42ce42015-04-11 13:48:01 +00001516 memcpy(&uX, &rX, 8);
1517 for(j=56; j>=0; j-=8) putc((uX>>j)&0xff, out);
1518 break;
1519 case SQLITE_TEXT:
1520 iX = sqlite3_value_bytes(pVal);
1521 putsVarint(out, (sqlite3_uint64)iX);
drh33aa4db2015-05-04 15:04:47 +00001522 fwrite(sqlite3_value_text(pVal),1,(size_t)iX,out);
drh6e42ce42015-04-11 13:48:01 +00001523 break;
1524 case SQLITE_BLOB:
1525 iX = sqlite3_value_bytes(pVal);
1526 putsVarint(out, (sqlite3_uint64)iX);
drh33aa4db2015-05-04 15:04:47 +00001527 fwrite(sqlite3_value_blob(pVal),1,(size_t)iX,out);
drh6e42ce42015-04-11 13:48:01 +00001528 break;
1529 case SQLITE_NULL:
1530 break;
drh697e5db2015-04-11 12:07:40 +00001531 }
1532}
1533
1534/*
drh83e63dc2015-04-10 19:41:18 +00001535** Generate a CHANGESET for all differences from main.zTab to aux.zTab.
1536*/
1537static void changeset_one_table(const char *zTab, FILE *out){
1538 sqlite3_stmt *pStmt; /* SQL statment */
1539 char *zId = safeId(zTab); /* Escaped name of the table */
1540 char **azCol = 0; /* List of escaped column names */
1541 int nCol = 0; /* Number of columns */
1542 int *aiFlg = 0; /* 0 if column is not part of PK */
1543 int *aiPk = 0; /* Column numbers for each PK column */
1544 int nPk = 0; /* Number of PRIMARY KEY columns */
1545 Str sql; /* SQL for the diff query */
drh6e42ce42015-04-11 13:48:01 +00001546 int i, k; /* Loop counters */
drh83e63dc2015-04-10 19:41:18 +00001547 const char *zSep; /* List separator */
1548
dan99461852015-07-30 20:26:16 +00001549 /* Check that the schemas of the two tables match. Exit early otherwise. */
1550 checkSchemasMatch(zTab);
1551
drh83e63dc2015-04-10 19:41:18 +00001552 pStmt = db_prepare("PRAGMA main.table_info=%Q", zTab);
1553 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1554 nCol++;
1555 azCol = sqlite3_realloc(azCol, sizeof(char*)*nCol);
1556 if( azCol==0 ) runtimeError("out of memory");
1557 aiFlg = sqlite3_realloc(aiFlg, sizeof(int)*nCol);
1558 if( aiFlg==0 ) runtimeError("out of memory");
1559 azCol[nCol-1] = safeId((const char*)sqlite3_column_text(pStmt,1));
1560 aiFlg[nCol-1] = i = sqlite3_column_int(pStmt,5);
1561 if( i>0 ){
1562 if( i>nPk ){
1563 nPk = i;
1564 aiPk = sqlite3_realloc(aiPk, sizeof(int)*nPk);
1565 if( aiPk==0 ) runtimeError("out of memory");
1566 }
1567 aiPk[i-1] = nCol-1;
1568 }
1569 }
1570 sqlite3_finalize(pStmt);
1571 if( nPk==0 ) goto end_changeset_one_table;
1572 strInit(&sql);
1573 if( nCol>nPk ){
drh697e5db2015-04-11 12:07:40 +00001574 strPrintf(&sql, "SELECT %d", SQLITE_UPDATE);
drh6e42ce42015-04-11 13:48:01 +00001575 for(i=0; i<nCol; i++){
1576 if( aiFlg[i] ){
1577 strPrintf(&sql, ",\n A.%s", azCol[i]);
1578 }else{
1579 strPrintf(&sql, ",\n A.%s IS NOT B.%s, A.%s, B.%s",
1580 azCol[i], azCol[i], azCol[i], azCol[i]);
1581 }
1582 }
drh83e63dc2015-04-10 19:41:18 +00001583 strPrintf(&sql,"\n FROM main.%s A, aux.%s B\n", zId, zId);
1584 zSep = " WHERE";
1585 for(i=0; i<nPk; i++){
1586 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1587 zSep = " AND";
1588 }
1589 zSep = "\n AND (";
1590 for(i=0; i<nCol; i++){
1591 if( aiFlg[i] ) continue;
1592 strPrintf(&sql, "%sA.%s IS NOT B.%s", zSep, azCol[i], azCol[i]);
1593 zSep = " OR\n ";
1594 }
1595 strPrintf(&sql,")\n UNION ALL\n");
1596 }
drh697e5db2015-04-11 12:07:40 +00001597 strPrintf(&sql, "SELECT %d", SQLITE_DELETE);
drh6e42ce42015-04-11 13:48:01 +00001598 for(i=0; i<nCol; i++){
1599 if( aiFlg[i] ){
1600 strPrintf(&sql, ",\n A.%s", azCol[i]);
1601 }else{
1602 strPrintf(&sql, ",\n 1, A.%s, NULL", azCol[i]);
1603 }
1604 }
1605 strPrintf(&sql, "\n FROM main.%s A\n", zId);
drh83e63dc2015-04-10 19:41:18 +00001606 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B\n", zId);
1607 zSep = " WHERE";
1608 for(i=0; i<nPk; i++){
1609 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1610 zSep = " AND";
1611 }
1612 strPrintf(&sql, ")\n UNION ALL\n");
drh697e5db2015-04-11 12:07:40 +00001613 strPrintf(&sql, "SELECT %d", SQLITE_INSERT);
drh6e42ce42015-04-11 13:48:01 +00001614 for(i=0; i<nCol; i++){
1615 if( aiFlg[i] ){
1616 strPrintf(&sql, ",\n B.%s", azCol[i]);
1617 }else{
1618 strPrintf(&sql, ",\n 1, NULL, B.%s", azCol[i]);
1619 }
1620 }
1621 strPrintf(&sql, "\n FROM aux.%s B\n", zId);
drh83e63dc2015-04-10 19:41:18 +00001622 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A\n", zId);
1623 zSep = " WHERE";
1624 for(i=0; i<nPk; i++){
1625 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1626 zSep = " AND";
1627 }
1628 strPrintf(&sql, ")\n");
1629 strPrintf(&sql, " ORDER BY");
1630 zSep = " ";
1631 for(i=0; i<nPk; i++){
drh6e42ce42015-04-11 13:48:01 +00001632 strPrintf(&sql, "%s %d", zSep, aiPk[i]+2);
drh83e63dc2015-04-10 19:41:18 +00001633 zSep = ",";
1634 }
1635 strPrintf(&sql, ";\n");
1636
drh697e5db2015-04-11 12:07:40 +00001637 if( g.fDebug & DEBUG_DIFF_SQL ){
1638 printf("SQL for %s:\n%s\n", zId, sql.z);
1639 goto end_changeset_one_table;
1640 }
1641
1642 putc('T', out);
1643 putsVarint(out, (sqlite3_uint64)nCol);
1644 for(i=0; i<nCol; i++) putc(aiFlg[i]!=0, out);
1645 fwrite(zTab, 1, strlen(zTab), out);
1646 putc(0, out);
1647
1648 pStmt = db_prepare("%s", sql.z);
1649 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1650 int iType = sqlite3_column_int(pStmt,0);
drh697e5db2015-04-11 12:07:40 +00001651 putc(iType, out);
1652 putc(0, out);
drh6e42ce42015-04-11 13:48:01 +00001653 switch( sqlite3_column_int(pStmt,0) ){
1654 case SQLITE_UPDATE: {
1655 for(k=1, i=0; i<nCol; i++){
1656 if( aiFlg[i] ){
1657 putValue(out, sqlite3_column_value(pStmt,k));
1658 k++;
1659 }else if( sqlite3_column_int(pStmt,k) ){
1660 putValue(out, sqlite3_column_value(pStmt,k+1));
1661 k += 3;
1662 }else{
1663 putc(0, out);
1664 k += 3;
1665 }
1666 }
1667 for(k=1, i=0; i<nCol; i++){
1668 if( aiFlg[i] ){
1669 putc(0, out);
1670 k++;
1671 }else if( sqlite3_column_int(pStmt,k) ){
1672 putValue(out, sqlite3_column_value(pStmt,k+2));
1673 k += 3;
1674 }else{
1675 putc(0, out);
1676 k += 3;
1677 }
1678 }
1679 break;
1680 }
1681 case SQLITE_INSERT: {
1682 for(k=1, i=0; i<nCol; i++){
1683 if( aiFlg[i] ){
1684 putValue(out, sqlite3_column_value(pStmt,k));
1685 k++;
1686 }else{
1687 putValue(out, sqlite3_column_value(pStmt,k+2));
1688 k += 3;
1689 }
1690 }
1691 break;
1692 }
1693 case SQLITE_DELETE: {
1694 for(k=1, i=0; i<nCol; i++){
1695 if( aiFlg[i] ){
1696 putValue(out, sqlite3_column_value(pStmt,k));
1697 k++;
1698 }else{
1699 putValue(out, sqlite3_column_value(pStmt,k+1));
1700 k += 3;
1701 }
1702 }
1703 break;
drh697e5db2015-04-11 12:07:40 +00001704 }
1705 }
1706 }
1707 sqlite3_finalize(pStmt);
drh83e63dc2015-04-10 19:41:18 +00001708
1709end_changeset_one_table:
1710 while( nCol>0 ) sqlite3_free(azCol[--nCol]);
1711 sqlite3_free(azCol);
1712 sqlite3_free(aiPk);
1713 sqlite3_free(zId);
1714}
1715
1716/*
drhd62c0f42015-04-09 13:34:29 +00001717** Print sketchy documentation for this utility program
1718*/
1719static void showHelp(void){
1720 printf("Usage: %s [options] DB1 DB2\n", g.zArgv0);
1721 printf(
1722"Output SQL text that would transform DB1 into DB2.\n"
1723"Options:\n"
drh83e63dc2015-04-10 19:41:18 +00001724" --changeset FILE Write a CHANGESET into FILE\n"
drh9a9219f2015-05-04 13:25:56 +00001725" -L|--lib LIBRARY Load an SQLite extension library\n"
drha37591c2015-04-09 18:14:03 +00001726" --primarykey Use schema-defined PRIMARY KEYs\n"
dan99461852015-07-30 20:26:16 +00001727" --rbu Output SQL to create/populate RBU table(s)\n"
drhd62c0f42015-04-09 13:34:29 +00001728" --schema Show only differences in the schema\n"
drh8a1cd762015-04-14 19:01:08 +00001729" --summary Show only a summary of the differences\n"
drhd62c0f42015-04-09 13:34:29 +00001730" --table TAB Show only differences in table TAB\n"
1731 );
1732}
1733
1734int main(int argc, char **argv){
1735 const char *zDb1 = 0;
1736 const char *zDb2 = 0;
1737 int i;
1738 int rc;
1739 char *zErrMsg = 0;
1740 char *zSql;
1741 sqlite3_stmt *pStmt;
1742 char *zTab = 0;
drh8a1cd762015-04-14 19:01:08 +00001743 FILE *out = stdout;
1744 void (*xDiff)(const char*,FILE*) = diff_one_table;
drh9a9219f2015-05-04 13:25:56 +00001745 int nExt = 0;
drh33aa4db2015-05-04 15:04:47 +00001746 char **azExt = 0;
drhd62c0f42015-04-09 13:34:29 +00001747
1748 g.zArgv0 = argv[0];
drhaa62e482015-05-12 00:46:40 +00001749 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
drhd62c0f42015-04-09 13:34:29 +00001750 for(i=1; i<argc; i++){
1751 const char *z = argv[i];
1752 if( z[0]=='-' ){
1753 z++;
1754 if( z[0]=='-' ) z++;
drh83e63dc2015-04-10 19:41:18 +00001755 if( strcmp(z,"changeset")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001756 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drh83e63dc2015-04-10 19:41:18 +00001757 out = fopen(argv[++i], "wb");
1758 if( out==0 ) cmdlineError("cannot open: %s", argv[i]);
drh8a1cd762015-04-14 19:01:08 +00001759 xDiff = changeset_one_table;
drh83e63dc2015-04-10 19:41:18 +00001760 }else
drhd62c0f42015-04-09 13:34:29 +00001761 if( strcmp(z,"debug")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001762 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drhd62c0f42015-04-09 13:34:29 +00001763 g.fDebug = strtol(argv[++i], 0, 0);
1764 }else
1765 if( strcmp(z,"help")==0 ){
1766 showHelp();
1767 return 0;
1768 }else
drh6582ae52015-05-12 12:24:50 +00001769#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh9a9219f2015-05-04 13:25:56 +00001770 if( strcmp(z,"lib")==0 || strcmp(z,"L")==0 ){
1771 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
1772 azExt = realloc(azExt, sizeof(azExt[0])*(nExt+1));
1773 if( azExt==0 ) cmdlineError("out of memory");
1774 azExt[nExt++] = argv[++i];
1775 }else
drh6582ae52015-05-12 12:24:50 +00001776#endif
drha37591c2015-04-09 18:14:03 +00001777 if( strcmp(z,"primarykey")==0 ){
1778 g.bSchemaPK = 1;
1779 }else
dan99461852015-07-30 20:26:16 +00001780 if( strcmp(z,"rbu")==0 ){
1781 xDiff = rbudiff_one_table;
1782 }else
drhd62c0f42015-04-09 13:34:29 +00001783 if( strcmp(z,"schema")==0 ){
1784 g.bSchemaOnly = 1;
1785 }else
drh8a1cd762015-04-14 19:01:08 +00001786 if( strcmp(z,"summary")==0 ){
1787 xDiff = summarize_one_table;
1788 }else
drhd62c0f42015-04-09 13:34:29 +00001789 if( strcmp(z,"table")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001790 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drhd62c0f42015-04-09 13:34:29 +00001791 zTab = argv[++i];
1792 }else
1793 {
1794 cmdlineError("unknown option: %s", argv[i]);
1795 }
1796 }else if( zDb1==0 ){
1797 zDb1 = argv[i];
1798 }else if( zDb2==0 ){
1799 zDb2 = argv[i];
1800 }else{
1801 cmdlineError("unknown argument: %s", argv[i]);
1802 }
1803 }
1804 if( zDb2==0 ){
1805 cmdlineError("two database arguments required");
1806 }
1807 rc = sqlite3_open(zDb1, &g.db);
1808 if( rc ){
1809 cmdlineError("cannot open database file \"%s\"", zDb1);
1810 }
1811 rc = sqlite3_exec(g.db, "SELECT * FROM sqlite_master", 0, 0, &zErrMsg);
1812 if( rc || zErrMsg ){
1813 cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb1);
1814 }
drh6582ae52015-05-12 12:24:50 +00001815#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh9a9219f2015-05-04 13:25:56 +00001816 sqlite3_enable_load_extension(g.db, 1);
1817 for(i=0; i<nExt; i++){
1818 rc = sqlite3_load_extension(g.db, azExt[i], 0, &zErrMsg);
1819 if( rc || zErrMsg ){
1820 cmdlineError("error loading %s: %s", azExt[i], zErrMsg);
1821 }
1822 }
drh6582ae52015-05-12 12:24:50 +00001823#endif
drh9a9219f2015-05-04 13:25:56 +00001824 free(azExt);
drhd62c0f42015-04-09 13:34:29 +00001825 zSql = sqlite3_mprintf("ATTACH %Q as aux;", zDb2);
1826 rc = sqlite3_exec(g.db, zSql, 0, 0, &zErrMsg);
1827 if( rc || zErrMsg ){
1828 cmdlineError("cannot attach database \"%s\"", zDb2);
1829 }
1830 rc = sqlite3_exec(g.db, "SELECT * FROM aux.sqlite_master", 0, 0, &zErrMsg);
1831 if( rc || zErrMsg ){
1832 cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb2);
1833 }
1834
1835 if( zTab ){
drh8a1cd762015-04-14 19:01:08 +00001836 xDiff(zTab, out);
drhd62c0f42015-04-09 13:34:29 +00001837 }else{
1838 /* Handle tables one by one */
1839 pStmt = db_prepare(
1840 "SELECT name FROM main.sqlite_master\n"
1841 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1842 " UNION\n"
1843 "SELECT name FROM aux.sqlite_master\n"
1844 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1845 " ORDER BY name"
1846 );
1847 while( SQLITE_ROW==sqlite3_step(pStmt) ){
drh8a1cd762015-04-14 19:01:08 +00001848 xDiff((const char*)sqlite3_column_text(pStmt,0), out);
drhd62c0f42015-04-09 13:34:29 +00001849 }
1850 sqlite3_finalize(pStmt);
1851 }
1852
1853 /* TBD: Handle trigger differences */
1854 /* TBD: Handle view differences */
1855 sqlite3_close(g.db);
1856 return 0;
1857}