blob: 3a5c4e4f7c1d8cd7b03e7b83831f24305509f84c [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];
813 pHash->z[pHash->i] = c;
814 pHash->i = (pHash->i+1)&(NHASH-1);
815 pHash->a = pHash->a - old + c;
816 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;
852 for(i=1, x=64; v>=x; i++, x <<= 6){}
853 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){
959 int i, base;
960 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;
1008 unsigned int bestCnt, bestOfst=0, bestLitsz=0;
1009 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;
1041 for(j=0, x=iSrc, y=base+i; x<lenSrc && y<lenOut; j++, x++, y++){
1042 if( zSrc[x]!=zOut[y] ) break;
1043 }
1044 j--;
1045
1046 /* Beginning at iSrc-1, match backwards as far as we can. k counts
1047 ** the number of characters that match */
1048 for(k=1; k<iSrc && k<=i; k++){
1049 if( zSrc[iSrc-k]!=zOut[base+i-k] ) break;
1050 }
1051 k--;
1052
1053 /* Compute the offset and size of the matching region */
1054 ofst = iSrc-k;
1055 cnt = j+k+1;
1056 litsz = i-k; /* Number of bytes of literal text before the copy */
1057 /* sz will hold the number of bytes needed to encode the "insert"
1058 ** command and the copy command, not counting the "insert" text */
1059 sz = digit_count(i-k)+digit_count(cnt)+digit_count(ofst)+3;
1060 if( cnt>=sz && cnt>bestCnt ){
1061 /* Remember this match only if it is the best so far and it
1062 ** does not increase the file size */
1063 bestCnt = cnt;
1064 bestOfst = iSrc-k;
1065 bestLitsz = litsz;
1066 }
1067
1068 /* Check the next matching block */
1069 iBlock = collide[iBlock];
1070 }
1071
1072 /* We have a copy command that does not cause the delta to be larger
1073 ** than a literal insert. So add the copy command to the delta.
1074 */
1075 if( bestCnt>0 ){
1076 if( bestLitsz>0 ){
1077 /* Add an insert command before the copy */
1078 putInt(bestLitsz,&zDelta);
1079 *(zDelta++) = ':';
1080 memcpy(zDelta, &zOut[base], bestLitsz);
1081 zDelta += bestLitsz;
1082 base += bestLitsz;
1083 }
1084 base += bestCnt;
1085 putInt(bestCnt, &zDelta);
1086 *(zDelta++) = '@';
1087 putInt(bestOfst, &zDelta);
1088 *(zDelta++) = ',';
1089 if( bestOfst + bestCnt -1 > lastRead ){
1090 lastRead = bestOfst + bestCnt - 1;
1091 }
1092 bestCnt = 0;
1093 break;
1094 }
1095
1096 /* If we reach this point, it means no match is found so far */
1097 if( base+i+NHASH>=lenOut ){
1098 /* We have reached the end of the file and have not found any
1099 ** matches. Do an "insert" for everything that does not match */
1100 putInt(lenOut-base, &zDelta);
1101 *(zDelta++) = ':';
1102 memcpy(zDelta, &zOut[base], lenOut-base);
1103 zDelta += lenOut-base;
1104 base = lenOut;
1105 break;
1106 }
1107
1108 /* Advance the hash by one character. Keep looking for a match */
1109 hash_next(&h, zOut[base+i+NHASH]);
1110 i++;
1111 }
1112 }
1113 /* Output a final "insert" record to get all the text at the end of
1114 ** the file that does not match anything in the source file.
1115 */
1116 if( base<lenOut ){
1117 putInt(lenOut-base, &zDelta);
1118 *(zDelta++) = ':';
1119 memcpy(zDelta, &zOut[base], lenOut-base);
1120 zDelta += lenOut-base;
1121 }
1122 /* Output the final checksum record. */
1123 putInt(checksum(zOut, lenOut), &zDelta);
1124 *(zDelta++) = ';';
1125 sqlite3_free(collide);
1126 return zDelta - zOrigDelta;
1127}
1128
1129/*
1130** End of code copied from fossil.
1131**************************************************************************/
1132
dan99461852015-07-30 20:26:16 +00001133static void strPrintfArray(
1134 Str *pStr, /* String object to append to */
1135 const char *zSep, /* Separator string */
1136 const char *zFmt, /* Format for each entry */
1137 char **az, int n /* Array of strings & its size (or -1) */
1138){
1139 int i;
1140 for(i=0; az[i] && (i<n || n<0); i++){
1141 if( i!=0 ) strPrintf(pStr, "%s", zSep);
1142 strPrintf(pStr, zFmt, az[i], az[i], az[i]);
1143 }
1144}
1145
1146static void getRbudiffQuery(
1147 const char *zTab,
1148 char **azCol,
1149 int nPK,
1150 int bOtaRowid,
1151 Str *pSql
1152){
1153 int i;
1154
1155 /* First the newly inserted rows: **/
1156 strPrintf(pSql, "SELECT ");
1157 strPrintfArray(pSql, ", ", "%s", azCol, -1);
dana9ca8af2015-07-31 19:52:03 +00001158 strPrintf(pSql, ", 0, "); /* Set ota_control to 0 for an insert */
1159 strPrintfArray(pSql, ", ", "NULL", azCol, -1);
dan99461852015-07-30 20:26:16 +00001160 strPrintf(pSql, " FROM aux.%Q AS n WHERE NOT EXISTS (\n", zTab);
1161 strPrintf(pSql, " SELECT 1 FROM ", zTab);
1162 strPrintf(pSql, " main.%Q AS o WHERE ", zTab);
1163 strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
1164 strPrintf(pSql, "\n)");
1165
1166 /* Deleted rows: */
1167 strPrintf(pSql, "\nUNION ALL\nSELECT ");
1168 strPrintfArray(pSql, ", ", "%s", azCol, nPK);
dandd688e72015-07-31 15:13:29 +00001169 if( azCol[nPK] ){
1170 strPrintf(pSql, ", ");
1171 strPrintfArray(pSql, ", ", "NULL", &azCol[nPK], -1);
1172 }
dana9ca8af2015-07-31 19:52:03 +00001173 strPrintf(pSql, ", 1, "); /* Set ota_control to 1 for a delete */
1174 strPrintfArray(pSql, ", ", "NULL", azCol, -1);
dan99461852015-07-30 20:26:16 +00001175 strPrintf(pSql, " FROM main.%Q AS n WHERE NOT EXISTS (\n", zTab);
1176 strPrintf(pSql, " SELECT 1 FROM ", zTab);
1177 strPrintf(pSql, " aux.%Q AS o WHERE ", zTab);
1178 strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
1179 strPrintf(pSql, "\n) ");
1180
dandd688e72015-07-31 15:13:29 +00001181 /* Updated rows. If all table columns are part of the primary key, there
1182 ** can be no updates. In this case this part of the compound SELECT can
1183 ** be omitted altogether. */
1184 if( azCol[nPK] ){
1185 strPrintf(pSql, "\nUNION ALL\nSELECT ");
1186 strPrintfArray(pSql, ", ", "n.%s", azCol, nPK);
dan99461852015-07-30 20:26:16 +00001187 strPrintf(pSql, ",\n");
dandd688e72015-07-31 15:13:29 +00001188 strPrintfArray(pSql, " ,\n",
1189 " CASE WHEN n.%s IS o.%s THEN NULL ELSE n.%s END", &azCol[nPK], -1
1190 );
dan99461852015-07-30 20:26:16 +00001191
dandd688e72015-07-31 15:13:29 +00001192 if( bOtaRowid==0 ){
1193 strPrintf(pSql, ", '");
1194 strPrintfArray(pSql, "", ".", azCol, nPK);
1195 strPrintf(pSql, "' ||\n");
1196 }else{
1197 strPrintf(pSql, ",\n");
1198 }
1199 strPrintfArray(pSql, " ||\n",
1200 " CASE WHEN n.%s IS o.%s THEN '.' ELSE 'x' END", &azCol[nPK], -1
1201 );
dana9ca8af2015-07-31 19:52:03 +00001202 strPrintf(pSql, "\nAS ota_control, ");
1203 strPrintfArray(pSql, ", ", "NULL", azCol, nPK);
1204 strPrintf(pSql, ",\n");
1205 strPrintfArray(pSql, " ,\n",
1206 " CASE WHEN n.%s IS o.%s THEN NULL ELSE o.%s END", &azCol[nPK], -1
1207 );
dandd688e72015-07-31 15:13:29 +00001208
1209 strPrintf(pSql, "\nFROM main.%Q AS o, aux.%Q AS n\nWHERE ", zTab, zTab);
1210 strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
1211 strPrintf(pSql, " AND ota_control LIKE '%%x%%'");
1212 }
dan99461852015-07-30 20:26:16 +00001213
1214 /* Now add an ORDER BY clause to sort everything by PK. */
1215 strPrintf(pSql, "\nORDER BY ");
1216 for(i=1; i<=nPK; i++) strPrintf(pSql, "%s%d", ((i>1)?", ":""), i);
1217}
1218
1219static void rbudiff_one_table(const char *zTab, FILE *out){
1220 int bOtaRowid; /* True to use an ota_rowid column */
1221 int nPK; /* Number of primary key columns in table */
1222 char **azCol; /* NULL terminated array of col names */
1223 int i;
1224 int nCol;
1225 Str ct = {0, 0, 0}; /* The "CREATE TABLE data_xxx" statement */
1226 Str sql = {0, 0, 0}; /* Query to find differences */
1227 Str insert = {0, 0, 0}; /* First part of output INSERT statement */
1228 sqlite3_stmt *pStmt = 0;
1229
1230 /* --rbu mode must use real primary keys. */
1231 g.bSchemaPK = 1;
1232
1233 /* Check that the schemas of the two tables match. Exit early otherwise. */
1234 checkSchemasMatch(zTab);
1235
1236 /* Grab the column names and PK details for the table(s). If no usable PK
1237 ** columns are found, bail out early. */
1238 azCol = columnNames("main", zTab, &nPK, &bOtaRowid);
1239 if( azCol==0 ){
1240 runtimeError("table %s has no usable PK columns", zTab);
1241 }
dana9ca8af2015-07-31 19:52:03 +00001242 for(nCol=0; azCol[nCol]; nCol++);
dan99461852015-07-30 20:26:16 +00001243
1244 /* Build and output the CREATE TABLE statement for the data_xxx table */
1245 strPrintf(&ct, "CREATE TABLE IF NOT EXISTS 'data_%q'(", zTab);
1246 if( bOtaRowid ) strPrintf(&ct, "rbu_rowid, ");
1247 strPrintfArray(&ct, ", ", "%s", &azCol[bOtaRowid], -1);
1248 strPrintf(&ct, ", rbu_control);");
1249
dan99461852015-07-30 20:26:16 +00001250 /* Get the SQL for the query to retrieve data from the two databases */
1251 getRbudiffQuery(zTab, azCol, nPK, bOtaRowid, &sql);
1252
1253 /* Build the first part of the INSERT statement output for each row
1254 ** in the data_xxx table. */
1255 strPrintf(&insert, "INSERT INTO 'data_%q' (", zTab);
1256 if( bOtaRowid ) strPrintf(&insert, "rbu_rowid, ");
1257 strPrintfArray(&insert, ", ", "%s", &azCol[bOtaRowid], -1);
1258 strPrintf(&insert, ", rbu_control) VALUES(");
1259
1260 pStmt = db_prepare("%s", sql.z);
dana9ca8af2015-07-31 19:52:03 +00001261
dan99461852015-07-30 20:26:16 +00001262 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dana9ca8af2015-07-31 19:52:03 +00001263
1264 /* If this is the first row output, print out the CREATE TABLE
1265 ** statement first. And then set ct.z to NULL so that it is not
1266 ** printed again. */
dan99461852015-07-30 20:26:16 +00001267 if( ct.z ){
1268 fprintf(out, "%s\n", ct.z);
1269 strFree(&ct);
1270 }
1271
dana9ca8af2015-07-31 19:52:03 +00001272 /* Output the first part of the INSERT statement */
dan99461852015-07-30 20:26:16 +00001273 fprintf(out, "%s", insert.z);
dana9ca8af2015-07-31 19:52:03 +00001274
1275 if( sqlite3_column_type(pStmt, nCol)==SQLITE_INTEGER ){
1276 for(i=0; i<=nCol; i++){
1277 if( i>0 ) fprintf(out, ", ");
1278 printQuoted(out, sqlite3_column_value(pStmt, i));
1279 }
1280 }else{
1281 char *zOtaControl;
1282 int nOtaControl = sqlite3_column_bytes(pStmt, nCol);
1283
1284 zOtaControl = (char*)sqlite3_malloc(nOtaControl);
1285 memcpy(zOtaControl, sqlite3_column_text(pStmt, nCol), nOtaControl+1);
1286
1287 for(i=0; i<nCol; i++){
1288 int bDone = 0;
1289 if( i>=nPK
1290 && sqlite3_column_type(pStmt, i)==SQLITE_BLOB
1291 && sqlite3_column_type(pStmt, nCol+1+i)==SQLITE_BLOB
1292 ){
1293 const char *aSrc = sqlite3_column_blob(pStmt, nCol+1+i);
1294 int nSrc = sqlite3_column_bytes(pStmt, nCol+1+i);
1295 const char *aFinal = sqlite3_column_blob(pStmt, i);
1296 int nFinal = sqlite3_column_bytes(pStmt, i);
1297 char *aDelta;
1298 int nDelta;
1299
1300 aDelta = sqlite3_malloc(nFinal + 60);
1301 nDelta = rbuDeltaCreate(aSrc, nSrc, aFinal, nFinal, aDelta);
1302 if( nDelta<nFinal ){
1303 int j;
1304 fprintf(out, "x'");
1305 for(j=0; j<nDelta; j++) fprintf(out, "%02x", (u8)aDelta[j]);
1306 fprintf(out, "'");
1307 zOtaControl[i-bOtaRowid] = 'f';
1308 bDone = 1;
1309 }
1310 sqlite3_free(aDelta);
1311 }
1312
1313 if( bDone==0 ){
1314 printQuoted(out, sqlite3_column_value(pStmt, i));
1315 }
1316 fprintf(out, ", ");
1317 }
1318 fprintf(out, "'%s'", zOtaControl);
1319 sqlite3_free(zOtaControl);
dan99461852015-07-30 20:26:16 +00001320 }
dana9ca8af2015-07-31 19:52:03 +00001321
1322 /* And the closing bracket of the insert statement */
dan99461852015-07-30 20:26:16 +00001323 fprintf(out, ");\n");
1324 }
1325
1326 sqlite3_finalize(pStmt);
1327
1328 strFree(&ct);
1329 strFree(&sql);
1330 strFree(&insert);
1331}
1332
1333/*
drh8a1cd762015-04-14 19:01:08 +00001334** Display a summary of differences between two versions of the same
1335** table table.
1336**
1337** * Number of rows changed
1338** * Number of rows added
1339** * Number of rows deleted
1340** * Number of identical rows
1341*/
1342static void summarize_one_table(const char *zTab, FILE *out){
1343 char *zId = safeId(zTab); /* Name of table (translated for us in SQL) */
1344 char **az = 0; /* Columns in main */
1345 char **az2 = 0; /* Columns in aux */
1346 int nPk; /* Primary key columns in main */
1347 int nPk2; /* Primary key columns in aux */
drhb3f3d642015-04-25 18:39:21 +00001348 int n = 0; /* Number of columns in main */
drh8a1cd762015-04-14 19:01:08 +00001349 int n2; /* Number of columns in aux */
1350 int i; /* Loop counter */
1351 const char *zSep; /* Separator string */
1352 Str sql; /* Comparison query */
1353 sqlite3_stmt *pStmt; /* Query statement to do the diff */
1354 sqlite3_int64 nUpdate; /* Number of updated rows */
1355 sqlite3_int64 nUnchanged; /* Number of unmodified rows */
1356 sqlite3_int64 nDelete; /* Number of deleted rows */
1357 sqlite3_int64 nInsert; /* Number of inserted rows */
1358
1359 strInit(&sql);
1360 if( sqlite3_table_column_metadata(g.db,"aux",zTab,0,0,0,0,0,0) ){
1361 if( !sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
1362 /* Table missing from second database. */
1363 fprintf(out, "%s: missing from second database\n", zTab);
1364 }
1365 goto end_summarize_one_table;
1366 }
1367
1368 if( sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
1369 /* Table missing from source */
1370 fprintf(out, "%s: missing from first database\n", zTab);
1371 goto end_summarize_one_table;
1372 }
1373
dan99461852015-07-30 20:26:16 +00001374 az = columnNames("main", zTab, &nPk, 0);
1375 az2 = columnNames("aux", zTab, &nPk2, 0);
drh8a1cd762015-04-14 19:01:08 +00001376 if( az && az2 ){
1377 for(n=0; az[n]; n++){
1378 if( sqlite3_stricmp(az[n],az2[n])!=0 ) break;
1379 }
1380 }
1381 if( az==0
1382 || az2==0
1383 || nPk!=nPk2
1384 || az[n]
1385 ){
1386 /* Schema mismatch */
1387 fprintf(out, "%s: incompatible schema\n", zTab);
1388 goto end_summarize_one_table;
1389 }
1390
1391 /* Build the comparison query */
1392 for(n2=n; az[n2]; n2++){}
1393 strPrintf(&sql, "SELECT 1, count(*)");
1394 if( n2==nPk2 ){
1395 strPrintf(&sql, ", 0\n");
1396 }else{
1397 zSep = ", sum(";
1398 for(i=nPk; az[i]; i++){
1399 strPrintf(&sql, "%sA.%s IS NOT B.%s", zSep, az[i], az[i]);
1400 zSep = " OR ";
1401 }
1402 strPrintf(&sql, ")\n");
1403 }
1404 strPrintf(&sql, " FROM main.%s A, aux.%s B\n", zId, zId);
1405 zSep = " WHERE";
1406 for(i=0; i<nPk; i++){
1407 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1408 zSep = " AND";
1409 }
1410 strPrintf(&sql, " UNION ALL\n");
1411 strPrintf(&sql, "SELECT 2, count(*), 0\n");
1412 strPrintf(&sql, " FROM main.%s A\n", zId);
1413 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B ", zId);
1414 zSep = "WHERE";
1415 for(i=0; i<nPk; i++){
1416 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1417 zSep = " AND";
1418 }
1419 strPrintf(&sql, ")\n");
1420 strPrintf(&sql, " UNION ALL\n");
1421 strPrintf(&sql, "SELECT 3, count(*), 0\n");
1422 strPrintf(&sql, " FROM aux.%s B\n", zId);
1423 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A ", zId);
1424 zSep = "WHERE";
1425 for(i=0; i<nPk; i++){
1426 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1427 zSep = " AND";
1428 }
1429 strPrintf(&sql, ")\n ORDER BY 1;\n");
1430
1431 if( (g.fDebug & DEBUG_DIFF_SQL)!=0 ){
1432 printf("SQL for %s:\n%s\n", zId, sql.z);
1433 goto end_summarize_one_table;
1434 }
1435
1436 /* Run the query and output difference summary */
1437 pStmt = db_prepare(sql.z);
1438 nUpdate = 0;
1439 nInsert = 0;
1440 nDelete = 0;
1441 nUnchanged = 0;
1442 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1443 switch( sqlite3_column_int(pStmt,0) ){
1444 case 1:
1445 nUpdate = sqlite3_column_int64(pStmt,2);
1446 nUnchanged = sqlite3_column_int64(pStmt,1) - nUpdate;
1447 break;
1448 case 2:
1449 nDelete = sqlite3_column_int64(pStmt,1);
1450 break;
1451 case 3:
1452 nInsert = sqlite3_column_int64(pStmt,1);
1453 break;
1454 }
1455 }
1456 sqlite3_finalize(pStmt);
1457 fprintf(out, "%s: %lld changes, %lld inserts, %lld deletes, %lld unchanged\n",
1458 zTab, nUpdate, nInsert, nDelete, nUnchanged);
1459
1460end_summarize_one_table:
1461 strFree(&sql);
1462 sqlite3_free(zId);
1463 namelistFree(az);
1464 namelistFree(az2);
1465 return;
1466}
1467
1468/*
drh697e5db2015-04-11 12:07:40 +00001469** Write a 64-bit signed integer as a varint onto out
1470*/
1471static void putsVarint(FILE *out, sqlite3_uint64 v){
1472 int i, n;
drh6e42ce42015-04-11 13:48:01 +00001473 unsigned char p[12];
drh697e5db2015-04-11 12:07:40 +00001474 if( v & (((sqlite3_uint64)0xff000000)<<32) ){
1475 p[8] = (unsigned char)v;
1476 v >>= 8;
1477 for(i=7; i>=0; i--){
1478 p[i] = (unsigned char)((v & 0x7f) | 0x80);
1479 v >>= 7;
1480 }
1481 fwrite(p, 8, 1, out);
1482 }else{
1483 n = 9;
1484 do{
1485 p[n--] = (unsigned char)((v & 0x7f) | 0x80);
1486 v >>= 7;
1487 }while( v!=0 );
drh6e42ce42015-04-11 13:48:01 +00001488 p[9] &= 0x7f;
1489 fwrite(p+n+1, 9-n, 1, out);
1490 }
1491}
1492
1493/*
1494** Write an SQLite value onto out.
1495*/
1496static void putValue(FILE *out, sqlite3_value *pVal){
1497 int iDType = sqlite3_value_type(pVal);
1498 sqlite3_int64 iX;
1499 double rX;
1500 sqlite3_uint64 uX;
1501 int j;
1502
1503 putc(iDType, out);
1504 switch( iDType ){
1505 case SQLITE_INTEGER:
1506 iX = sqlite3_value_int64(pVal);
1507 memcpy(&uX, &iX, 8);
1508 for(j=56; j>=0; j-=8) putc((uX>>j)&0xff, out);
1509 break;
1510 case SQLITE_FLOAT:
drh33aa4db2015-05-04 15:04:47 +00001511 rX = sqlite3_value_double(pVal);
drh6e42ce42015-04-11 13:48:01 +00001512 memcpy(&uX, &rX, 8);
1513 for(j=56; j>=0; j-=8) putc((uX>>j)&0xff, out);
1514 break;
1515 case SQLITE_TEXT:
1516 iX = sqlite3_value_bytes(pVal);
1517 putsVarint(out, (sqlite3_uint64)iX);
drh33aa4db2015-05-04 15:04:47 +00001518 fwrite(sqlite3_value_text(pVal),1,(size_t)iX,out);
drh6e42ce42015-04-11 13:48:01 +00001519 break;
1520 case SQLITE_BLOB:
1521 iX = sqlite3_value_bytes(pVal);
1522 putsVarint(out, (sqlite3_uint64)iX);
drh33aa4db2015-05-04 15:04:47 +00001523 fwrite(sqlite3_value_blob(pVal),1,(size_t)iX,out);
drh6e42ce42015-04-11 13:48:01 +00001524 break;
1525 case SQLITE_NULL:
1526 break;
drh697e5db2015-04-11 12:07:40 +00001527 }
1528}
1529
1530/*
drh83e63dc2015-04-10 19:41:18 +00001531** Generate a CHANGESET for all differences from main.zTab to aux.zTab.
1532*/
1533static void changeset_one_table(const char *zTab, FILE *out){
1534 sqlite3_stmt *pStmt; /* SQL statment */
1535 char *zId = safeId(zTab); /* Escaped name of the table */
1536 char **azCol = 0; /* List of escaped column names */
1537 int nCol = 0; /* Number of columns */
1538 int *aiFlg = 0; /* 0 if column is not part of PK */
1539 int *aiPk = 0; /* Column numbers for each PK column */
1540 int nPk = 0; /* Number of PRIMARY KEY columns */
1541 Str sql; /* SQL for the diff query */
drh6e42ce42015-04-11 13:48:01 +00001542 int i, k; /* Loop counters */
drh83e63dc2015-04-10 19:41:18 +00001543 const char *zSep; /* List separator */
1544
dan99461852015-07-30 20:26:16 +00001545 /* Check that the schemas of the two tables match. Exit early otherwise. */
1546 checkSchemasMatch(zTab);
1547
drh83e63dc2015-04-10 19:41:18 +00001548 pStmt = db_prepare("PRAGMA main.table_info=%Q", zTab);
1549 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1550 nCol++;
1551 azCol = sqlite3_realloc(azCol, sizeof(char*)*nCol);
1552 if( azCol==0 ) runtimeError("out of memory");
1553 aiFlg = sqlite3_realloc(aiFlg, sizeof(int)*nCol);
1554 if( aiFlg==0 ) runtimeError("out of memory");
1555 azCol[nCol-1] = safeId((const char*)sqlite3_column_text(pStmt,1));
1556 aiFlg[nCol-1] = i = sqlite3_column_int(pStmt,5);
1557 if( i>0 ){
1558 if( i>nPk ){
1559 nPk = i;
1560 aiPk = sqlite3_realloc(aiPk, sizeof(int)*nPk);
1561 if( aiPk==0 ) runtimeError("out of memory");
1562 }
1563 aiPk[i-1] = nCol-1;
1564 }
1565 }
1566 sqlite3_finalize(pStmt);
1567 if( nPk==0 ) goto end_changeset_one_table;
1568 strInit(&sql);
1569 if( nCol>nPk ){
drh697e5db2015-04-11 12:07:40 +00001570 strPrintf(&sql, "SELECT %d", SQLITE_UPDATE);
drh6e42ce42015-04-11 13:48:01 +00001571 for(i=0; i<nCol; i++){
1572 if( aiFlg[i] ){
1573 strPrintf(&sql, ",\n A.%s", azCol[i]);
1574 }else{
1575 strPrintf(&sql, ",\n A.%s IS NOT B.%s, A.%s, B.%s",
1576 azCol[i], azCol[i], azCol[i], azCol[i]);
1577 }
1578 }
drh83e63dc2015-04-10 19:41:18 +00001579 strPrintf(&sql,"\n FROM main.%s A, aux.%s B\n", zId, zId);
1580 zSep = " WHERE";
1581 for(i=0; i<nPk; i++){
1582 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1583 zSep = " AND";
1584 }
1585 zSep = "\n AND (";
1586 for(i=0; i<nCol; i++){
1587 if( aiFlg[i] ) continue;
1588 strPrintf(&sql, "%sA.%s IS NOT B.%s", zSep, azCol[i], azCol[i]);
1589 zSep = " OR\n ";
1590 }
1591 strPrintf(&sql,")\n UNION ALL\n");
1592 }
drh697e5db2015-04-11 12:07:40 +00001593 strPrintf(&sql, "SELECT %d", SQLITE_DELETE);
drh6e42ce42015-04-11 13:48:01 +00001594 for(i=0; i<nCol; i++){
1595 if( aiFlg[i] ){
1596 strPrintf(&sql, ",\n A.%s", azCol[i]);
1597 }else{
1598 strPrintf(&sql, ",\n 1, A.%s, NULL", azCol[i]);
1599 }
1600 }
1601 strPrintf(&sql, "\n FROM main.%s A\n", zId);
drh83e63dc2015-04-10 19:41:18 +00001602 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B\n", zId);
1603 zSep = " WHERE";
1604 for(i=0; i<nPk; i++){
1605 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1606 zSep = " AND";
1607 }
1608 strPrintf(&sql, ")\n UNION ALL\n");
drh697e5db2015-04-11 12:07:40 +00001609 strPrintf(&sql, "SELECT %d", SQLITE_INSERT);
drh6e42ce42015-04-11 13:48:01 +00001610 for(i=0; i<nCol; i++){
1611 if( aiFlg[i] ){
1612 strPrintf(&sql, ",\n B.%s", azCol[i]);
1613 }else{
1614 strPrintf(&sql, ",\n 1, NULL, B.%s", azCol[i]);
1615 }
1616 }
1617 strPrintf(&sql, "\n FROM aux.%s B\n", zId);
drh83e63dc2015-04-10 19:41:18 +00001618 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A\n", zId);
1619 zSep = " WHERE";
1620 for(i=0; i<nPk; i++){
1621 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1622 zSep = " AND";
1623 }
1624 strPrintf(&sql, ")\n");
1625 strPrintf(&sql, " ORDER BY");
1626 zSep = " ";
1627 for(i=0; i<nPk; i++){
drh6e42ce42015-04-11 13:48:01 +00001628 strPrintf(&sql, "%s %d", zSep, aiPk[i]+2);
drh83e63dc2015-04-10 19:41:18 +00001629 zSep = ",";
1630 }
1631 strPrintf(&sql, ";\n");
1632
drh697e5db2015-04-11 12:07:40 +00001633 if( g.fDebug & DEBUG_DIFF_SQL ){
1634 printf("SQL for %s:\n%s\n", zId, sql.z);
1635 goto end_changeset_one_table;
1636 }
1637
1638 putc('T', out);
1639 putsVarint(out, (sqlite3_uint64)nCol);
1640 for(i=0; i<nCol; i++) putc(aiFlg[i]!=0, out);
1641 fwrite(zTab, 1, strlen(zTab), out);
1642 putc(0, out);
1643
1644 pStmt = db_prepare("%s", sql.z);
1645 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1646 int iType = sqlite3_column_int(pStmt,0);
drh697e5db2015-04-11 12:07:40 +00001647 putc(iType, out);
1648 putc(0, out);
drh6e42ce42015-04-11 13:48:01 +00001649 switch( sqlite3_column_int(pStmt,0) ){
1650 case SQLITE_UPDATE: {
1651 for(k=1, i=0; i<nCol; i++){
1652 if( aiFlg[i] ){
1653 putValue(out, sqlite3_column_value(pStmt,k));
1654 k++;
1655 }else if( sqlite3_column_int(pStmt,k) ){
1656 putValue(out, sqlite3_column_value(pStmt,k+1));
1657 k += 3;
1658 }else{
1659 putc(0, out);
1660 k += 3;
1661 }
1662 }
1663 for(k=1, i=0; i<nCol; i++){
1664 if( aiFlg[i] ){
1665 putc(0, out);
1666 k++;
1667 }else if( sqlite3_column_int(pStmt,k) ){
1668 putValue(out, sqlite3_column_value(pStmt,k+2));
1669 k += 3;
1670 }else{
1671 putc(0, out);
1672 k += 3;
1673 }
1674 }
1675 break;
1676 }
1677 case SQLITE_INSERT: {
1678 for(k=1, i=0; i<nCol; i++){
1679 if( aiFlg[i] ){
1680 putValue(out, sqlite3_column_value(pStmt,k));
1681 k++;
1682 }else{
1683 putValue(out, sqlite3_column_value(pStmt,k+2));
1684 k += 3;
1685 }
1686 }
1687 break;
1688 }
1689 case SQLITE_DELETE: {
1690 for(k=1, i=0; i<nCol; i++){
1691 if( aiFlg[i] ){
1692 putValue(out, sqlite3_column_value(pStmt,k));
1693 k++;
1694 }else{
1695 putValue(out, sqlite3_column_value(pStmt,k+1));
1696 k += 3;
1697 }
1698 }
1699 break;
drh697e5db2015-04-11 12:07:40 +00001700 }
1701 }
1702 }
1703 sqlite3_finalize(pStmt);
drh83e63dc2015-04-10 19:41:18 +00001704
1705end_changeset_one_table:
1706 while( nCol>0 ) sqlite3_free(azCol[--nCol]);
1707 sqlite3_free(azCol);
1708 sqlite3_free(aiPk);
1709 sqlite3_free(zId);
1710}
1711
1712/*
drhd62c0f42015-04-09 13:34:29 +00001713** Print sketchy documentation for this utility program
1714*/
1715static void showHelp(void){
1716 printf("Usage: %s [options] DB1 DB2\n", g.zArgv0);
1717 printf(
1718"Output SQL text that would transform DB1 into DB2.\n"
1719"Options:\n"
drh83e63dc2015-04-10 19:41:18 +00001720" --changeset FILE Write a CHANGESET into FILE\n"
drh9a9219f2015-05-04 13:25:56 +00001721" -L|--lib LIBRARY Load an SQLite extension library\n"
drha37591c2015-04-09 18:14:03 +00001722" --primarykey Use schema-defined PRIMARY KEYs\n"
dan99461852015-07-30 20:26:16 +00001723" --rbu Output SQL to create/populate RBU table(s)\n"
drhd62c0f42015-04-09 13:34:29 +00001724" --schema Show only differences in the schema\n"
drh8a1cd762015-04-14 19:01:08 +00001725" --summary Show only a summary of the differences\n"
drhd62c0f42015-04-09 13:34:29 +00001726" --table TAB Show only differences in table TAB\n"
1727 );
1728}
1729
1730int main(int argc, char **argv){
1731 const char *zDb1 = 0;
1732 const char *zDb2 = 0;
1733 int i;
1734 int rc;
1735 char *zErrMsg = 0;
1736 char *zSql;
1737 sqlite3_stmt *pStmt;
1738 char *zTab = 0;
drh8a1cd762015-04-14 19:01:08 +00001739 FILE *out = stdout;
1740 void (*xDiff)(const char*,FILE*) = diff_one_table;
drh9a9219f2015-05-04 13:25:56 +00001741 int nExt = 0;
drh33aa4db2015-05-04 15:04:47 +00001742 char **azExt = 0;
drhd62c0f42015-04-09 13:34:29 +00001743
1744 g.zArgv0 = argv[0];
drhaa62e482015-05-12 00:46:40 +00001745 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
drhd62c0f42015-04-09 13:34:29 +00001746 for(i=1; i<argc; i++){
1747 const char *z = argv[i];
1748 if( z[0]=='-' ){
1749 z++;
1750 if( z[0]=='-' ) z++;
drh83e63dc2015-04-10 19:41:18 +00001751 if( strcmp(z,"changeset")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001752 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drh83e63dc2015-04-10 19:41:18 +00001753 out = fopen(argv[++i], "wb");
1754 if( out==0 ) cmdlineError("cannot open: %s", argv[i]);
drh8a1cd762015-04-14 19:01:08 +00001755 xDiff = changeset_one_table;
drh83e63dc2015-04-10 19:41:18 +00001756 }else
drhd62c0f42015-04-09 13:34:29 +00001757 if( strcmp(z,"debug")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001758 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drhd62c0f42015-04-09 13:34:29 +00001759 g.fDebug = strtol(argv[++i], 0, 0);
1760 }else
1761 if( strcmp(z,"help")==0 ){
1762 showHelp();
1763 return 0;
1764 }else
drh6582ae52015-05-12 12:24:50 +00001765#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh9a9219f2015-05-04 13:25:56 +00001766 if( strcmp(z,"lib")==0 || strcmp(z,"L")==0 ){
1767 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
1768 azExt = realloc(azExt, sizeof(azExt[0])*(nExt+1));
1769 if( azExt==0 ) cmdlineError("out of memory");
1770 azExt[nExt++] = argv[++i];
1771 }else
drh6582ae52015-05-12 12:24:50 +00001772#endif
drha37591c2015-04-09 18:14:03 +00001773 if( strcmp(z,"primarykey")==0 ){
1774 g.bSchemaPK = 1;
1775 }else
dan99461852015-07-30 20:26:16 +00001776 if( strcmp(z,"rbu")==0 ){
1777 xDiff = rbudiff_one_table;
1778 }else
drhd62c0f42015-04-09 13:34:29 +00001779 if( strcmp(z,"schema")==0 ){
1780 g.bSchemaOnly = 1;
1781 }else
drh8a1cd762015-04-14 19:01:08 +00001782 if( strcmp(z,"summary")==0 ){
1783 xDiff = summarize_one_table;
1784 }else
drhd62c0f42015-04-09 13:34:29 +00001785 if( strcmp(z,"table")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001786 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drhd62c0f42015-04-09 13:34:29 +00001787 zTab = argv[++i];
1788 }else
1789 {
1790 cmdlineError("unknown option: %s", argv[i]);
1791 }
1792 }else if( zDb1==0 ){
1793 zDb1 = argv[i];
1794 }else if( zDb2==0 ){
1795 zDb2 = argv[i];
1796 }else{
1797 cmdlineError("unknown argument: %s", argv[i]);
1798 }
1799 }
1800 if( zDb2==0 ){
1801 cmdlineError("two database arguments required");
1802 }
1803 rc = sqlite3_open(zDb1, &g.db);
1804 if( rc ){
1805 cmdlineError("cannot open database file \"%s\"", zDb1);
1806 }
1807 rc = sqlite3_exec(g.db, "SELECT * FROM sqlite_master", 0, 0, &zErrMsg);
1808 if( rc || zErrMsg ){
1809 cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb1);
1810 }
drh6582ae52015-05-12 12:24:50 +00001811#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh9a9219f2015-05-04 13:25:56 +00001812 sqlite3_enable_load_extension(g.db, 1);
1813 for(i=0; i<nExt; i++){
1814 rc = sqlite3_load_extension(g.db, azExt[i], 0, &zErrMsg);
1815 if( rc || zErrMsg ){
1816 cmdlineError("error loading %s: %s", azExt[i], zErrMsg);
1817 }
1818 }
drh6582ae52015-05-12 12:24:50 +00001819#endif
drh9a9219f2015-05-04 13:25:56 +00001820 free(azExt);
drhd62c0f42015-04-09 13:34:29 +00001821 zSql = sqlite3_mprintf("ATTACH %Q as aux;", zDb2);
1822 rc = sqlite3_exec(g.db, zSql, 0, 0, &zErrMsg);
1823 if( rc || zErrMsg ){
1824 cmdlineError("cannot attach database \"%s\"", zDb2);
1825 }
1826 rc = sqlite3_exec(g.db, "SELECT * FROM aux.sqlite_master", 0, 0, &zErrMsg);
1827 if( rc || zErrMsg ){
1828 cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb2);
1829 }
1830
1831 if( zTab ){
drh8a1cd762015-04-14 19:01:08 +00001832 xDiff(zTab, out);
drhd62c0f42015-04-09 13:34:29 +00001833 }else{
1834 /* Handle tables one by one */
1835 pStmt = db_prepare(
1836 "SELECT name FROM main.sqlite_master\n"
1837 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1838 " UNION\n"
1839 "SELECT name FROM aux.sqlite_master\n"
1840 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1841 " ORDER BY name"
1842 );
1843 while( SQLITE_ROW==sqlite3_step(pStmt) ){
drh8a1cd762015-04-14 19:01:08 +00001844 xDiff((const char*)sqlite3_column_text(pStmt,0), out);
drhd62c0f42015-04-09 13:34:29 +00001845 }
1846 sqlite3_finalize(pStmt);
1847 }
1848
1849 /* TBD: Handle trigger differences */
1850 /* TBD: Handle view differences */
1851 sqlite3_close(g.db);
1852 return 0;
1853}