blob: 82ef4ad150f1f01081011ee049d95ffec5d82eca [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/*
848** Read bytes from *pz and convert them into a positive integer. When
849** finished, leave *pz pointing to the first character past the end of
850** the integer. The *pLen parameter holds the length of the string
851** in *pz and is decremented once for each character in the integer.
852*/
853static unsigned int getInt(const char **pz, int *pLen){
854 static const signed char zValue[] = {
855 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
856 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
857 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
858 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
859 -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
860 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
861 -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
862 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
863 };
864 unsigned int v = 0;
865 int c;
866 unsigned char *z = (unsigned char*)*pz;
867 unsigned char *zStart = z;
868 while( (c = zValue[0x7f&*(z++)])>=0 ){
869 v = (v<<6) + c;
870 }
871 z--;
872 *pLen -= z - zStart;
873 *pz = (char*)z;
874 return v;
875}
876
877/*
878** Return the number digits in the base-64 representation of a positive integer
879*/
880static int digit_count(int v){
881 unsigned int i, x;
882 for(i=1, x=64; v>=x; i++, x <<= 6){}
883 return i;
884}
885
886/*
887** Compute a 32-bit checksum on the N-byte buffer. Return the result.
888*/
889static unsigned int checksum(const char *zIn, size_t N){
890 const unsigned char *z = (const unsigned char *)zIn;
891 unsigned sum0 = 0;
892 unsigned sum1 = 0;
893 unsigned sum2 = 0;
894 unsigned sum3 = 0;
895 while(N >= 16){
896 sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
897 sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
898 sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
899 sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
900 z += 16;
901 N -= 16;
902 }
903 while(N >= 4){
904 sum0 += z[0];
905 sum1 += z[1];
906 sum2 += z[2];
907 sum3 += z[3];
908 z += 4;
909 N -= 4;
910 }
911 sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
912 switch(N){
913 case 3: sum3 += (z[2] << 8);
914 case 2: sum3 += (z[1] << 16);
915 case 1: sum3 += (z[0] << 24);
916 default: ;
917 }
918 return sum3;
919}
920
921/*
922** Create a new delta.
923**
924** The delta is written into a preallocated buffer, zDelta, which
925** should be at least 60 bytes longer than the target file, zOut.
926** The delta string will be NUL-terminated, but it might also contain
927** embedded NUL characters if either the zSrc or zOut files are
928** binary. This function returns the length of the delta string
929** in bytes, excluding the final NUL terminator character.
930**
931** Output Format:
932**
933** The delta begins with a base64 number followed by a newline. This
934** number is the number of bytes in the TARGET file. Thus, given a
935** delta file z, a program can compute the size of the output file
936** simply by reading the first line and decoding the base-64 number
937** found there. The delta_output_size() routine does exactly this.
938**
939** After the initial size number, the delta consists of a series of
940** literal text segments and commands to copy from the SOURCE file.
941** A copy command looks like this:
942**
943** NNN@MMM,
944**
945** where NNN is the number of bytes to be copied and MMM is the offset
946** into the source file of the first byte (both base-64). If NNN is 0
947** it means copy the rest of the input file. Literal text is like this:
948**
949** NNN:TTTTT
950**
951** where NNN is the number of bytes of text (base-64) and TTTTT is the text.
952**
953** The last term is of the form
954**
955** NNN;
956**
957** In this case, NNN is a 32-bit bigendian checksum of the output file
958** that can be used to verify that the delta applied correctly. All
959** numbers are in base-64.
960**
961** Pure text files generate a pure text delta. Binary files generate a
962** delta that may contain some binary data.
963**
964** Algorithm:
965**
966** The encoder first builds a hash table to help it find matching
967** patterns in the source file. 16-byte chunks of the source file
968** sampled at evenly spaced intervals are used to populate the hash
969** table.
970**
971** Next we begin scanning the target file using a sliding 16-byte
972** window. The hash of the 16-byte window in the target is used to
973** search for a matching section in the source file. When a match
974** is found, a copy command is added to the delta. An effort is
975** made to extend the matching section to regions that come before
976** and after the 16-byte hash window. A copy command is only issued
977** if the result would use less space that just quoting the text
978** literally. Literal text is added to the delta for sections that
979** do not match or which can not be encoded efficiently using copy
980** commands.
981*/
982static int rbuDeltaCreate(
983 const char *zSrc, /* The source or pattern file */
984 unsigned int lenSrc, /* Length of the source file */
985 const char *zOut, /* The target file */
986 unsigned int lenOut, /* Length of the target file */
987 char *zDelta /* Write the delta into this buffer */
988){
989 int i, base;
990 char *zOrigDelta = zDelta;
991 hash h;
992 int nHash; /* Number of hash table entries */
993 int *landmark; /* Primary hash table */
994 int *collide; /* Collision chain */
995 int lastRead = -1; /* Last byte of zSrc read by a COPY command */
996
997 /* Add the target file size to the beginning of the delta
998 */
999 putInt(lenOut, &zDelta);
1000 *(zDelta++) = '\n';
1001
1002 /* If the source file is very small, it means that we have no
1003 ** chance of ever doing a copy command. Just output a single
1004 ** literal segment for the entire target and exit.
1005 */
1006 if( lenSrc<=NHASH ){
1007 putInt(lenOut, &zDelta);
1008 *(zDelta++) = ':';
1009 memcpy(zDelta, zOut, lenOut);
1010 zDelta += lenOut;
1011 putInt(checksum(zOut, lenOut), &zDelta);
1012 *(zDelta++) = ';';
1013 return zDelta - zOrigDelta;
1014 }
1015
1016 /* Compute the hash table used to locate matching sections in the
1017 ** source file.
1018 */
1019 nHash = lenSrc/NHASH;
1020 collide = sqlite3_malloc( nHash*2*sizeof(int) );
1021 landmark = &collide[nHash];
1022 memset(landmark, -1, nHash*sizeof(int));
1023 memset(collide, -1, nHash*sizeof(int));
1024 for(i=0; i<lenSrc-NHASH; i+=NHASH){
1025 int hv;
1026 hash_init(&h, &zSrc[i]);
1027 hv = hash_32bit(&h) % nHash;
1028 collide[i/NHASH] = landmark[hv];
1029 landmark[hv] = i/NHASH;
1030 }
1031
1032 /* Begin scanning the target file and generating copy commands and
1033 ** literal sections of the delta.
1034 */
1035 base = 0; /* We have already generated everything before zOut[base] */
1036 while( base+NHASH<lenOut ){
1037 int iSrc, iBlock;
1038 unsigned int bestCnt, bestOfst=0, bestLitsz=0;
1039 hash_init(&h, &zOut[base]);
1040 i = 0; /* Trying to match a landmark against zOut[base+i] */
1041 bestCnt = 0;
1042 while( 1 ){
1043 int hv;
1044 int limit = 250;
1045
1046 hv = hash_32bit(&h) % nHash;
1047 iBlock = landmark[hv];
1048 while( iBlock>=0 && (limit--)>0 ){
1049 /*
1050 ** The hash window has identified a potential match against
1051 ** landmark block iBlock. But we need to investigate further.
1052 **
1053 ** Look for a region in zOut that matches zSrc. Anchor the search
1054 ** at zSrc[iSrc] and zOut[base+i]. Do not include anything prior to
1055 ** zOut[base] or after zOut[outLen] nor anything after zSrc[srcLen].
1056 **
1057 ** Set cnt equal to the length of the match and set ofst so that
1058 ** zSrc[ofst] is the first element of the match. litsz is the number
1059 ** of characters between zOut[base] and the beginning of the match.
1060 ** sz will be the overhead (in bytes) needed to encode the copy
1061 ** command. Only generate copy command if the overhead of the
1062 ** copy command is less than the amount of literal text to be copied.
1063 */
1064 int cnt, ofst, litsz;
1065 int j, k, x, y;
1066 int sz;
1067
1068 /* Beginning at iSrc, match forwards as far as we can. j counts
1069 ** the number of characters that match */
1070 iSrc = iBlock*NHASH;
1071 for(j=0, x=iSrc, y=base+i; x<lenSrc && y<lenOut; j++, x++, y++){
1072 if( zSrc[x]!=zOut[y] ) break;
1073 }
1074 j--;
1075
1076 /* Beginning at iSrc-1, match backwards as far as we can. k counts
1077 ** the number of characters that match */
1078 for(k=1; k<iSrc && k<=i; k++){
1079 if( zSrc[iSrc-k]!=zOut[base+i-k] ) break;
1080 }
1081 k--;
1082
1083 /* Compute the offset and size of the matching region */
1084 ofst = iSrc-k;
1085 cnt = j+k+1;
1086 litsz = i-k; /* Number of bytes of literal text before the copy */
1087 /* sz will hold the number of bytes needed to encode the "insert"
1088 ** command and the copy command, not counting the "insert" text */
1089 sz = digit_count(i-k)+digit_count(cnt)+digit_count(ofst)+3;
1090 if( cnt>=sz && cnt>bestCnt ){
1091 /* Remember this match only if it is the best so far and it
1092 ** does not increase the file size */
1093 bestCnt = cnt;
1094 bestOfst = iSrc-k;
1095 bestLitsz = litsz;
1096 }
1097
1098 /* Check the next matching block */
1099 iBlock = collide[iBlock];
1100 }
1101
1102 /* We have a copy command that does not cause the delta to be larger
1103 ** than a literal insert. So add the copy command to the delta.
1104 */
1105 if( bestCnt>0 ){
1106 if( bestLitsz>0 ){
1107 /* Add an insert command before the copy */
1108 putInt(bestLitsz,&zDelta);
1109 *(zDelta++) = ':';
1110 memcpy(zDelta, &zOut[base], bestLitsz);
1111 zDelta += bestLitsz;
1112 base += bestLitsz;
1113 }
1114 base += bestCnt;
1115 putInt(bestCnt, &zDelta);
1116 *(zDelta++) = '@';
1117 putInt(bestOfst, &zDelta);
1118 *(zDelta++) = ',';
1119 if( bestOfst + bestCnt -1 > lastRead ){
1120 lastRead = bestOfst + bestCnt - 1;
1121 }
1122 bestCnt = 0;
1123 break;
1124 }
1125
1126 /* If we reach this point, it means no match is found so far */
1127 if( base+i+NHASH>=lenOut ){
1128 /* We have reached the end of the file and have not found any
1129 ** matches. Do an "insert" for everything that does not match */
1130 putInt(lenOut-base, &zDelta);
1131 *(zDelta++) = ':';
1132 memcpy(zDelta, &zOut[base], lenOut-base);
1133 zDelta += lenOut-base;
1134 base = lenOut;
1135 break;
1136 }
1137
1138 /* Advance the hash by one character. Keep looking for a match */
1139 hash_next(&h, zOut[base+i+NHASH]);
1140 i++;
1141 }
1142 }
1143 /* Output a final "insert" record to get all the text at the end of
1144 ** the file that does not match anything in the source file.
1145 */
1146 if( base<lenOut ){
1147 putInt(lenOut-base, &zDelta);
1148 *(zDelta++) = ':';
1149 memcpy(zDelta, &zOut[base], lenOut-base);
1150 zDelta += lenOut-base;
1151 }
1152 /* Output the final checksum record. */
1153 putInt(checksum(zOut, lenOut), &zDelta);
1154 *(zDelta++) = ';';
1155 sqlite3_free(collide);
1156 return zDelta - zOrigDelta;
1157}
1158
1159/*
1160** End of code copied from fossil.
1161**************************************************************************/
1162
dan99461852015-07-30 20:26:16 +00001163static void strPrintfArray(
1164 Str *pStr, /* String object to append to */
1165 const char *zSep, /* Separator string */
1166 const char *zFmt, /* Format for each entry */
1167 char **az, int n /* Array of strings & its size (or -1) */
1168){
1169 int i;
1170 for(i=0; az[i] && (i<n || n<0); i++){
1171 if( i!=0 ) strPrintf(pStr, "%s", zSep);
1172 strPrintf(pStr, zFmt, az[i], az[i], az[i]);
1173 }
1174}
1175
1176static void getRbudiffQuery(
1177 const char *zTab,
1178 char **azCol,
1179 int nPK,
1180 int bOtaRowid,
1181 Str *pSql
1182){
1183 int i;
1184
1185 /* First the newly inserted rows: **/
1186 strPrintf(pSql, "SELECT ");
1187 strPrintfArray(pSql, ", ", "%s", azCol, -1);
dana9ca8af2015-07-31 19:52:03 +00001188 strPrintf(pSql, ", 0, "); /* Set ota_control to 0 for an insert */
1189 strPrintfArray(pSql, ", ", "NULL", azCol, -1);
dan99461852015-07-30 20:26:16 +00001190 strPrintf(pSql, " FROM aux.%Q AS n WHERE NOT EXISTS (\n", zTab);
1191 strPrintf(pSql, " SELECT 1 FROM ", zTab);
1192 strPrintf(pSql, " main.%Q AS o WHERE ", zTab);
1193 strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
1194 strPrintf(pSql, "\n)");
1195
1196 /* Deleted rows: */
1197 strPrintf(pSql, "\nUNION ALL\nSELECT ");
1198 strPrintfArray(pSql, ", ", "%s", azCol, nPK);
dandd688e72015-07-31 15:13:29 +00001199 if( azCol[nPK] ){
1200 strPrintf(pSql, ", ");
1201 strPrintfArray(pSql, ", ", "NULL", &azCol[nPK], -1);
1202 }
dana9ca8af2015-07-31 19:52:03 +00001203 strPrintf(pSql, ", 1, "); /* Set ota_control to 1 for a delete */
1204 strPrintfArray(pSql, ", ", "NULL", azCol, -1);
dan99461852015-07-30 20:26:16 +00001205 strPrintf(pSql, " FROM main.%Q AS n WHERE NOT EXISTS (\n", zTab);
1206 strPrintf(pSql, " SELECT 1 FROM ", zTab);
1207 strPrintf(pSql, " aux.%Q AS o WHERE ", zTab);
1208 strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
1209 strPrintf(pSql, "\n) ");
1210
dandd688e72015-07-31 15:13:29 +00001211 /* Updated rows. If all table columns are part of the primary key, there
1212 ** can be no updates. In this case this part of the compound SELECT can
1213 ** be omitted altogether. */
1214 if( azCol[nPK] ){
1215 strPrintf(pSql, "\nUNION ALL\nSELECT ");
1216 strPrintfArray(pSql, ", ", "n.%s", azCol, nPK);
dan99461852015-07-30 20:26:16 +00001217 strPrintf(pSql, ",\n");
dandd688e72015-07-31 15:13:29 +00001218 strPrintfArray(pSql, " ,\n",
1219 " CASE WHEN n.%s IS o.%s THEN NULL ELSE n.%s END", &azCol[nPK], -1
1220 );
dan99461852015-07-30 20:26:16 +00001221
dandd688e72015-07-31 15:13:29 +00001222 if( bOtaRowid==0 ){
1223 strPrintf(pSql, ", '");
1224 strPrintfArray(pSql, "", ".", azCol, nPK);
1225 strPrintf(pSql, "' ||\n");
1226 }else{
1227 strPrintf(pSql, ",\n");
1228 }
1229 strPrintfArray(pSql, " ||\n",
1230 " CASE WHEN n.%s IS o.%s THEN '.' ELSE 'x' END", &azCol[nPK], -1
1231 );
dana9ca8af2015-07-31 19:52:03 +00001232 strPrintf(pSql, "\nAS ota_control, ");
1233 strPrintfArray(pSql, ", ", "NULL", azCol, nPK);
1234 strPrintf(pSql, ",\n");
1235 strPrintfArray(pSql, " ,\n",
1236 " CASE WHEN n.%s IS o.%s THEN NULL ELSE o.%s END", &azCol[nPK], -1
1237 );
dandd688e72015-07-31 15:13:29 +00001238
1239 strPrintf(pSql, "\nFROM main.%Q AS o, aux.%Q AS n\nWHERE ", zTab, zTab);
1240 strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
1241 strPrintf(pSql, " AND ota_control LIKE '%%x%%'");
1242 }
dan99461852015-07-30 20:26:16 +00001243
1244 /* Now add an ORDER BY clause to sort everything by PK. */
1245 strPrintf(pSql, "\nORDER BY ");
1246 for(i=1; i<=nPK; i++) strPrintf(pSql, "%s%d", ((i>1)?", ":""), i);
1247}
1248
1249static void rbudiff_one_table(const char *zTab, FILE *out){
1250 int bOtaRowid; /* True to use an ota_rowid column */
1251 int nPK; /* Number of primary key columns in table */
1252 char **azCol; /* NULL terminated array of col names */
1253 int i;
1254 int nCol;
1255 Str ct = {0, 0, 0}; /* The "CREATE TABLE data_xxx" statement */
1256 Str sql = {0, 0, 0}; /* Query to find differences */
1257 Str insert = {0, 0, 0}; /* First part of output INSERT statement */
1258 sqlite3_stmt *pStmt = 0;
1259
1260 /* --rbu mode must use real primary keys. */
1261 g.bSchemaPK = 1;
1262
1263 /* Check that the schemas of the two tables match. Exit early otherwise. */
1264 checkSchemasMatch(zTab);
1265
1266 /* Grab the column names and PK details for the table(s). If no usable PK
1267 ** columns are found, bail out early. */
1268 azCol = columnNames("main", zTab, &nPK, &bOtaRowid);
1269 if( azCol==0 ){
1270 runtimeError("table %s has no usable PK columns", zTab);
1271 }
dana9ca8af2015-07-31 19:52:03 +00001272 for(nCol=0; azCol[nCol]; nCol++);
dan99461852015-07-30 20:26:16 +00001273
1274 /* Build and output the CREATE TABLE statement for the data_xxx table */
1275 strPrintf(&ct, "CREATE TABLE IF NOT EXISTS 'data_%q'(", zTab);
1276 if( bOtaRowid ) strPrintf(&ct, "rbu_rowid, ");
1277 strPrintfArray(&ct, ", ", "%s", &azCol[bOtaRowid], -1);
1278 strPrintf(&ct, ", rbu_control);");
1279
dan99461852015-07-30 20:26:16 +00001280 /* Get the SQL for the query to retrieve data from the two databases */
1281 getRbudiffQuery(zTab, azCol, nPK, bOtaRowid, &sql);
1282
1283 /* Build the first part of the INSERT statement output for each row
1284 ** in the data_xxx table. */
1285 strPrintf(&insert, "INSERT INTO 'data_%q' (", zTab);
1286 if( bOtaRowid ) strPrintf(&insert, "rbu_rowid, ");
1287 strPrintfArray(&insert, ", ", "%s", &azCol[bOtaRowid], -1);
1288 strPrintf(&insert, ", rbu_control) VALUES(");
1289
1290 pStmt = db_prepare("%s", sql.z);
dana9ca8af2015-07-31 19:52:03 +00001291
dan99461852015-07-30 20:26:16 +00001292 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dana9ca8af2015-07-31 19:52:03 +00001293
1294 /* If this is the first row output, print out the CREATE TABLE
1295 ** statement first. And then set ct.z to NULL so that it is not
1296 ** printed again. */
dan99461852015-07-30 20:26:16 +00001297 if( ct.z ){
1298 fprintf(out, "%s\n", ct.z);
1299 strFree(&ct);
1300 }
1301
dana9ca8af2015-07-31 19:52:03 +00001302 /* Output the first part of the INSERT statement */
dan99461852015-07-30 20:26:16 +00001303 fprintf(out, "%s", insert.z);
dana9ca8af2015-07-31 19:52:03 +00001304
1305 if( sqlite3_column_type(pStmt, nCol)==SQLITE_INTEGER ){
1306 for(i=0; i<=nCol; i++){
1307 if( i>0 ) fprintf(out, ", ");
1308 printQuoted(out, sqlite3_column_value(pStmt, i));
1309 }
1310 }else{
1311 char *zOtaControl;
1312 int nOtaControl = sqlite3_column_bytes(pStmt, nCol);
1313
1314 zOtaControl = (char*)sqlite3_malloc(nOtaControl);
1315 memcpy(zOtaControl, sqlite3_column_text(pStmt, nCol), nOtaControl+1);
1316
1317 for(i=0; i<nCol; i++){
1318 int bDone = 0;
1319 if( i>=nPK
1320 && sqlite3_column_type(pStmt, i)==SQLITE_BLOB
1321 && sqlite3_column_type(pStmt, nCol+1+i)==SQLITE_BLOB
1322 ){
1323 const char *aSrc = sqlite3_column_blob(pStmt, nCol+1+i);
1324 int nSrc = sqlite3_column_bytes(pStmt, nCol+1+i);
1325 const char *aFinal = sqlite3_column_blob(pStmt, i);
1326 int nFinal = sqlite3_column_bytes(pStmt, i);
1327 char *aDelta;
1328 int nDelta;
1329
1330 aDelta = sqlite3_malloc(nFinal + 60);
1331 nDelta = rbuDeltaCreate(aSrc, nSrc, aFinal, nFinal, aDelta);
1332 if( nDelta<nFinal ){
1333 int j;
1334 fprintf(out, "x'");
1335 for(j=0; j<nDelta; j++) fprintf(out, "%02x", (u8)aDelta[j]);
1336 fprintf(out, "'");
1337 zOtaControl[i-bOtaRowid] = 'f';
1338 bDone = 1;
1339 }
1340 sqlite3_free(aDelta);
1341 }
1342
1343 if( bDone==0 ){
1344 printQuoted(out, sqlite3_column_value(pStmt, i));
1345 }
1346 fprintf(out, ", ");
1347 }
1348 fprintf(out, "'%s'", zOtaControl);
1349 sqlite3_free(zOtaControl);
dan99461852015-07-30 20:26:16 +00001350 }
dana9ca8af2015-07-31 19:52:03 +00001351
1352 /* And the closing bracket of the insert statement */
dan99461852015-07-30 20:26:16 +00001353 fprintf(out, ");\n");
1354 }
1355
1356 sqlite3_finalize(pStmt);
1357
1358 strFree(&ct);
1359 strFree(&sql);
1360 strFree(&insert);
1361}
1362
1363/*
drh8a1cd762015-04-14 19:01:08 +00001364** Display a summary of differences between two versions of the same
1365** table table.
1366**
1367** * Number of rows changed
1368** * Number of rows added
1369** * Number of rows deleted
1370** * Number of identical rows
1371*/
1372static void summarize_one_table(const char *zTab, FILE *out){
1373 char *zId = safeId(zTab); /* Name of table (translated for us in SQL) */
1374 char **az = 0; /* Columns in main */
1375 char **az2 = 0; /* Columns in aux */
1376 int nPk; /* Primary key columns in main */
1377 int nPk2; /* Primary key columns in aux */
drhb3f3d642015-04-25 18:39:21 +00001378 int n = 0; /* Number of columns in main */
drh8a1cd762015-04-14 19:01:08 +00001379 int n2; /* Number of columns in aux */
1380 int i; /* Loop counter */
1381 const char *zSep; /* Separator string */
1382 Str sql; /* Comparison query */
1383 sqlite3_stmt *pStmt; /* Query statement to do the diff */
1384 sqlite3_int64 nUpdate; /* Number of updated rows */
1385 sqlite3_int64 nUnchanged; /* Number of unmodified rows */
1386 sqlite3_int64 nDelete; /* Number of deleted rows */
1387 sqlite3_int64 nInsert; /* Number of inserted rows */
1388
1389 strInit(&sql);
1390 if( sqlite3_table_column_metadata(g.db,"aux",zTab,0,0,0,0,0,0) ){
1391 if( !sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
1392 /* Table missing from second database. */
1393 fprintf(out, "%s: missing from second database\n", zTab);
1394 }
1395 goto end_summarize_one_table;
1396 }
1397
1398 if( sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
1399 /* Table missing from source */
1400 fprintf(out, "%s: missing from first database\n", zTab);
1401 goto end_summarize_one_table;
1402 }
1403
dan99461852015-07-30 20:26:16 +00001404 az = columnNames("main", zTab, &nPk, 0);
1405 az2 = columnNames("aux", zTab, &nPk2, 0);
drh8a1cd762015-04-14 19:01:08 +00001406 if( az && az2 ){
1407 for(n=0; az[n]; n++){
1408 if( sqlite3_stricmp(az[n],az2[n])!=0 ) break;
1409 }
1410 }
1411 if( az==0
1412 || az2==0
1413 || nPk!=nPk2
1414 || az[n]
1415 ){
1416 /* Schema mismatch */
1417 fprintf(out, "%s: incompatible schema\n", zTab);
1418 goto end_summarize_one_table;
1419 }
1420
1421 /* Build the comparison query */
1422 for(n2=n; az[n2]; n2++){}
1423 strPrintf(&sql, "SELECT 1, count(*)");
1424 if( n2==nPk2 ){
1425 strPrintf(&sql, ", 0\n");
1426 }else{
1427 zSep = ", sum(";
1428 for(i=nPk; az[i]; i++){
1429 strPrintf(&sql, "%sA.%s IS NOT B.%s", zSep, az[i], az[i]);
1430 zSep = " OR ";
1431 }
1432 strPrintf(&sql, ")\n");
1433 }
1434 strPrintf(&sql, " FROM main.%s A, aux.%s B\n", zId, zId);
1435 zSep = " WHERE";
1436 for(i=0; i<nPk; i++){
1437 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1438 zSep = " AND";
1439 }
1440 strPrintf(&sql, " UNION ALL\n");
1441 strPrintf(&sql, "SELECT 2, count(*), 0\n");
1442 strPrintf(&sql, " FROM main.%s A\n", zId);
1443 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B ", zId);
1444 zSep = "WHERE";
1445 for(i=0; i<nPk; i++){
1446 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1447 zSep = " AND";
1448 }
1449 strPrintf(&sql, ")\n");
1450 strPrintf(&sql, " UNION ALL\n");
1451 strPrintf(&sql, "SELECT 3, count(*), 0\n");
1452 strPrintf(&sql, " FROM aux.%s B\n", zId);
1453 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A ", zId);
1454 zSep = "WHERE";
1455 for(i=0; i<nPk; i++){
1456 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1457 zSep = " AND";
1458 }
1459 strPrintf(&sql, ")\n ORDER BY 1;\n");
1460
1461 if( (g.fDebug & DEBUG_DIFF_SQL)!=0 ){
1462 printf("SQL for %s:\n%s\n", zId, sql.z);
1463 goto end_summarize_one_table;
1464 }
1465
1466 /* Run the query and output difference summary */
1467 pStmt = db_prepare(sql.z);
1468 nUpdate = 0;
1469 nInsert = 0;
1470 nDelete = 0;
1471 nUnchanged = 0;
1472 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1473 switch( sqlite3_column_int(pStmt,0) ){
1474 case 1:
1475 nUpdate = sqlite3_column_int64(pStmt,2);
1476 nUnchanged = sqlite3_column_int64(pStmt,1) - nUpdate;
1477 break;
1478 case 2:
1479 nDelete = sqlite3_column_int64(pStmt,1);
1480 break;
1481 case 3:
1482 nInsert = sqlite3_column_int64(pStmt,1);
1483 break;
1484 }
1485 }
1486 sqlite3_finalize(pStmt);
1487 fprintf(out, "%s: %lld changes, %lld inserts, %lld deletes, %lld unchanged\n",
1488 zTab, nUpdate, nInsert, nDelete, nUnchanged);
1489
1490end_summarize_one_table:
1491 strFree(&sql);
1492 sqlite3_free(zId);
1493 namelistFree(az);
1494 namelistFree(az2);
1495 return;
1496}
1497
1498/*
drh697e5db2015-04-11 12:07:40 +00001499** Write a 64-bit signed integer as a varint onto out
1500*/
1501static void putsVarint(FILE *out, sqlite3_uint64 v){
1502 int i, n;
drh6e42ce42015-04-11 13:48:01 +00001503 unsigned char p[12];
drh697e5db2015-04-11 12:07:40 +00001504 if( v & (((sqlite3_uint64)0xff000000)<<32) ){
1505 p[8] = (unsigned char)v;
1506 v >>= 8;
1507 for(i=7; i>=0; i--){
1508 p[i] = (unsigned char)((v & 0x7f) | 0x80);
1509 v >>= 7;
1510 }
1511 fwrite(p, 8, 1, out);
1512 }else{
1513 n = 9;
1514 do{
1515 p[n--] = (unsigned char)((v & 0x7f) | 0x80);
1516 v >>= 7;
1517 }while( v!=0 );
drh6e42ce42015-04-11 13:48:01 +00001518 p[9] &= 0x7f;
1519 fwrite(p+n+1, 9-n, 1, out);
1520 }
1521}
1522
1523/*
1524** Write an SQLite value onto out.
1525*/
1526static void putValue(FILE *out, sqlite3_value *pVal){
1527 int iDType = sqlite3_value_type(pVal);
1528 sqlite3_int64 iX;
1529 double rX;
1530 sqlite3_uint64 uX;
1531 int j;
1532
1533 putc(iDType, out);
1534 switch( iDType ){
1535 case SQLITE_INTEGER:
1536 iX = sqlite3_value_int64(pVal);
1537 memcpy(&uX, &iX, 8);
1538 for(j=56; j>=0; j-=8) putc((uX>>j)&0xff, out);
1539 break;
1540 case SQLITE_FLOAT:
drh33aa4db2015-05-04 15:04:47 +00001541 rX = sqlite3_value_double(pVal);
drh6e42ce42015-04-11 13:48:01 +00001542 memcpy(&uX, &rX, 8);
1543 for(j=56; j>=0; j-=8) putc((uX>>j)&0xff, out);
1544 break;
1545 case SQLITE_TEXT:
1546 iX = sqlite3_value_bytes(pVal);
1547 putsVarint(out, (sqlite3_uint64)iX);
drh33aa4db2015-05-04 15:04:47 +00001548 fwrite(sqlite3_value_text(pVal),1,(size_t)iX,out);
drh6e42ce42015-04-11 13:48:01 +00001549 break;
1550 case SQLITE_BLOB:
1551 iX = sqlite3_value_bytes(pVal);
1552 putsVarint(out, (sqlite3_uint64)iX);
drh33aa4db2015-05-04 15:04:47 +00001553 fwrite(sqlite3_value_blob(pVal),1,(size_t)iX,out);
drh6e42ce42015-04-11 13:48:01 +00001554 break;
1555 case SQLITE_NULL:
1556 break;
drh697e5db2015-04-11 12:07:40 +00001557 }
1558}
1559
1560/*
drh83e63dc2015-04-10 19:41:18 +00001561** Generate a CHANGESET for all differences from main.zTab to aux.zTab.
1562*/
1563static void changeset_one_table(const char *zTab, FILE *out){
1564 sqlite3_stmt *pStmt; /* SQL statment */
1565 char *zId = safeId(zTab); /* Escaped name of the table */
1566 char **azCol = 0; /* List of escaped column names */
1567 int nCol = 0; /* Number of columns */
1568 int *aiFlg = 0; /* 0 if column is not part of PK */
1569 int *aiPk = 0; /* Column numbers for each PK column */
1570 int nPk = 0; /* Number of PRIMARY KEY columns */
1571 Str sql; /* SQL for the diff query */
drh6e42ce42015-04-11 13:48:01 +00001572 int i, k; /* Loop counters */
drh83e63dc2015-04-10 19:41:18 +00001573 const char *zSep; /* List separator */
1574
dan99461852015-07-30 20:26:16 +00001575 /* Check that the schemas of the two tables match. Exit early otherwise. */
1576 checkSchemasMatch(zTab);
1577
drh83e63dc2015-04-10 19:41:18 +00001578 pStmt = db_prepare("PRAGMA main.table_info=%Q", zTab);
1579 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1580 nCol++;
1581 azCol = sqlite3_realloc(azCol, sizeof(char*)*nCol);
1582 if( azCol==0 ) runtimeError("out of memory");
1583 aiFlg = sqlite3_realloc(aiFlg, sizeof(int)*nCol);
1584 if( aiFlg==0 ) runtimeError("out of memory");
1585 azCol[nCol-1] = safeId((const char*)sqlite3_column_text(pStmt,1));
1586 aiFlg[nCol-1] = i = sqlite3_column_int(pStmt,5);
1587 if( i>0 ){
1588 if( i>nPk ){
1589 nPk = i;
1590 aiPk = sqlite3_realloc(aiPk, sizeof(int)*nPk);
1591 if( aiPk==0 ) runtimeError("out of memory");
1592 }
1593 aiPk[i-1] = nCol-1;
1594 }
1595 }
1596 sqlite3_finalize(pStmt);
1597 if( nPk==0 ) goto end_changeset_one_table;
1598 strInit(&sql);
1599 if( nCol>nPk ){
drh697e5db2015-04-11 12:07:40 +00001600 strPrintf(&sql, "SELECT %d", SQLITE_UPDATE);
drh6e42ce42015-04-11 13:48:01 +00001601 for(i=0; i<nCol; i++){
1602 if( aiFlg[i] ){
1603 strPrintf(&sql, ",\n A.%s", azCol[i]);
1604 }else{
1605 strPrintf(&sql, ",\n A.%s IS NOT B.%s, A.%s, B.%s",
1606 azCol[i], azCol[i], azCol[i], azCol[i]);
1607 }
1608 }
drh83e63dc2015-04-10 19:41:18 +00001609 strPrintf(&sql,"\n FROM main.%s A, aux.%s B\n", zId, zId);
1610 zSep = " WHERE";
1611 for(i=0; i<nPk; i++){
1612 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1613 zSep = " AND";
1614 }
1615 zSep = "\n AND (";
1616 for(i=0; i<nCol; i++){
1617 if( aiFlg[i] ) continue;
1618 strPrintf(&sql, "%sA.%s IS NOT B.%s", zSep, azCol[i], azCol[i]);
1619 zSep = " OR\n ";
1620 }
1621 strPrintf(&sql,")\n UNION ALL\n");
1622 }
drh697e5db2015-04-11 12:07:40 +00001623 strPrintf(&sql, "SELECT %d", SQLITE_DELETE);
drh6e42ce42015-04-11 13:48:01 +00001624 for(i=0; i<nCol; i++){
1625 if( aiFlg[i] ){
1626 strPrintf(&sql, ",\n A.%s", azCol[i]);
1627 }else{
1628 strPrintf(&sql, ",\n 1, A.%s, NULL", azCol[i]);
1629 }
1630 }
1631 strPrintf(&sql, "\n FROM main.%s A\n", zId);
drh83e63dc2015-04-10 19:41:18 +00001632 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B\n", zId);
1633 zSep = " WHERE";
1634 for(i=0; i<nPk; i++){
1635 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1636 zSep = " AND";
1637 }
1638 strPrintf(&sql, ")\n UNION ALL\n");
drh697e5db2015-04-11 12:07:40 +00001639 strPrintf(&sql, "SELECT %d", SQLITE_INSERT);
drh6e42ce42015-04-11 13:48:01 +00001640 for(i=0; i<nCol; i++){
1641 if( aiFlg[i] ){
1642 strPrintf(&sql, ",\n B.%s", azCol[i]);
1643 }else{
1644 strPrintf(&sql, ",\n 1, NULL, B.%s", azCol[i]);
1645 }
1646 }
1647 strPrintf(&sql, "\n FROM aux.%s B\n", zId);
drh83e63dc2015-04-10 19:41:18 +00001648 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A\n", zId);
1649 zSep = " WHERE";
1650 for(i=0; i<nPk; i++){
1651 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1652 zSep = " AND";
1653 }
1654 strPrintf(&sql, ")\n");
1655 strPrintf(&sql, " ORDER BY");
1656 zSep = " ";
1657 for(i=0; i<nPk; i++){
drh6e42ce42015-04-11 13:48:01 +00001658 strPrintf(&sql, "%s %d", zSep, aiPk[i]+2);
drh83e63dc2015-04-10 19:41:18 +00001659 zSep = ",";
1660 }
1661 strPrintf(&sql, ";\n");
1662
drh697e5db2015-04-11 12:07:40 +00001663 if( g.fDebug & DEBUG_DIFF_SQL ){
1664 printf("SQL for %s:\n%s\n", zId, sql.z);
1665 goto end_changeset_one_table;
1666 }
1667
1668 putc('T', out);
1669 putsVarint(out, (sqlite3_uint64)nCol);
1670 for(i=0; i<nCol; i++) putc(aiFlg[i]!=0, out);
1671 fwrite(zTab, 1, strlen(zTab), out);
1672 putc(0, out);
1673
1674 pStmt = db_prepare("%s", sql.z);
1675 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1676 int iType = sqlite3_column_int(pStmt,0);
drh697e5db2015-04-11 12:07:40 +00001677 putc(iType, out);
1678 putc(0, out);
drh6e42ce42015-04-11 13:48:01 +00001679 switch( sqlite3_column_int(pStmt,0) ){
1680 case SQLITE_UPDATE: {
1681 for(k=1, i=0; i<nCol; i++){
1682 if( aiFlg[i] ){
1683 putValue(out, sqlite3_column_value(pStmt,k));
1684 k++;
1685 }else if( sqlite3_column_int(pStmt,k) ){
1686 putValue(out, sqlite3_column_value(pStmt,k+1));
1687 k += 3;
1688 }else{
1689 putc(0, out);
1690 k += 3;
1691 }
1692 }
1693 for(k=1, i=0; i<nCol; i++){
1694 if( aiFlg[i] ){
1695 putc(0, out);
1696 k++;
1697 }else if( sqlite3_column_int(pStmt,k) ){
1698 putValue(out, sqlite3_column_value(pStmt,k+2));
1699 k += 3;
1700 }else{
1701 putc(0, out);
1702 k += 3;
1703 }
1704 }
1705 break;
1706 }
1707 case SQLITE_INSERT: {
1708 for(k=1, i=0; i<nCol; i++){
1709 if( aiFlg[i] ){
1710 putValue(out, sqlite3_column_value(pStmt,k));
1711 k++;
1712 }else{
1713 putValue(out, sqlite3_column_value(pStmt,k+2));
1714 k += 3;
1715 }
1716 }
1717 break;
1718 }
1719 case SQLITE_DELETE: {
1720 for(k=1, i=0; i<nCol; i++){
1721 if( aiFlg[i] ){
1722 putValue(out, sqlite3_column_value(pStmt,k));
1723 k++;
1724 }else{
1725 putValue(out, sqlite3_column_value(pStmt,k+1));
1726 k += 3;
1727 }
1728 }
1729 break;
drh697e5db2015-04-11 12:07:40 +00001730 }
1731 }
1732 }
1733 sqlite3_finalize(pStmt);
drh83e63dc2015-04-10 19:41:18 +00001734
1735end_changeset_one_table:
1736 while( nCol>0 ) sqlite3_free(azCol[--nCol]);
1737 sqlite3_free(azCol);
1738 sqlite3_free(aiPk);
1739 sqlite3_free(zId);
1740}
1741
1742/*
drhd62c0f42015-04-09 13:34:29 +00001743** Print sketchy documentation for this utility program
1744*/
1745static void showHelp(void){
1746 printf("Usage: %s [options] DB1 DB2\n", g.zArgv0);
1747 printf(
1748"Output SQL text that would transform DB1 into DB2.\n"
1749"Options:\n"
drh83e63dc2015-04-10 19:41:18 +00001750" --changeset FILE Write a CHANGESET into FILE\n"
drh9a9219f2015-05-04 13:25:56 +00001751" -L|--lib LIBRARY Load an SQLite extension library\n"
drha37591c2015-04-09 18:14:03 +00001752" --primarykey Use schema-defined PRIMARY KEYs\n"
dan99461852015-07-30 20:26:16 +00001753" --rbu Output SQL to create/populate RBU table(s)\n"
drhd62c0f42015-04-09 13:34:29 +00001754" --schema Show only differences in the schema\n"
drh8a1cd762015-04-14 19:01:08 +00001755" --summary Show only a summary of the differences\n"
drhd62c0f42015-04-09 13:34:29 +00001756" --table TAB Show only differences in table TAB\n"
1757 );
1758}
1759
1760int main(int argc, char **argv){
1761 const char *zDb1 = 0;
1762 const char *zDb2 = 0;
1763 int i;
1764 int rc;
1765 char *zErrMsg = 0;
1766 char *zSql;
1767 sqlite3_stmt *pStmt;
1768 char *zTab = 0;
drh8a1cd762015-04-14 19:01:08 +00001769 FILE *out = stdout;
1770 void (*xDiff)(const char*,FILE*) = diff_one_table;
drh9a9219f2015-05-04 13:25:56 +00001771 int nExt = 0;
drh33aa4db2015-05-04 15:04:47 +00001772 char **azExt = 0;
drhd62c0f42015-04-09 13:34:29 +00001773
1774 g.zArgv0 = argv[0];
drhaa62e482015-05-12 00:46:40 +00001775 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
drhd62c0f42015-04-09 13:34:29 +00001776 for(i=1; i<argc; i++){
1777 const char *z = argv[i];
1778 if( z[0]=='-' ){
1779 z++;
1780 if( z[0]=='-' ) z++;
drh83e63dc2015-04-10 19:41:18 +00001781 if( strcmp(z,"changeset")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001782 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drh83e63dc2015-04-10 19:41:18 +00001783 out = fopen(argv[++i], "wb");
1784 if( out==0 ) cmdlineError("cannot open: %s", argv[i]);
drh8a1cd762015-04-14 19:01:08 +00001785 xDiff = changeset_one_table;
drh83e63dc2015-04-10 19:41:18 +00001786 }else
drhd62c0f42015-04-09 13:34:29 +00001787 if( strcmp(z,"debug")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001788 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drhd62c0f42015-04-09 13:34:29 +00001789 g.fDebug = strtol(argv[++i], 0, 0);
1790 }else
1791 if( strcmp(z,"help")==0 ){
1792 showHelp();
1793 return 0;
1794 }else
drh6582ae52015-05-12 12:24:50 +00001795#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh9a9219f2015-05-04 13:25:56 +00001796 if( strcmp(z,"lib")==0 || strcmp(z,"L")==0 ){
1797 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
1798 azExt = realloc(azExt, sizeof(azExt[0])*(nExt+1));
1799 if( azExt==0 ) cmdlineError("out of memory");
1800 azExt[nExt++] = argv[++i];
1801 }else
drh6582ae52015-05-12 12:24:50 +00001802#endif
drha37591c2015-04-09 18:14:03 +00001803 if( strcmp(z,"primarykey")==0 ){
1804 g.bSchemaPK = 1;
1805 }else
dan99461852015-07-30 20:26:16 +00001806 if( strcmp(z,"rbu")==0 ){
1807 xDiff = rbudiff_one_table;
1808 }else
drhd62c0f42015-04-09 13:34:29 +00001809 if( strcmp(z,"schema")==0 ){
1810 g.bSchemaOnly = 1;
1811 }else
drh8a1cd762015-04-14 19:01:08 +00001812 if( strcmp(z,"summary")==0 ){
1813 xDiff = summarize_one_table;
1814 }else
drhd62c0f42015-04-09 13:34:29 +00001815 if( strcmp(z,"table")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001816 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drhd62c0f42015-04-09 13:34:29 +00001817 zTab = argv[++i];
1818 }else
1819 {
1820 cmdlineError("unknown option: %s", argv[i]);
1821 }
1822 }else if( zDb1==0 ){
1823 zDb1 = argv[i];
1824 }else if( zDb2==0 ){
1825 zDb2 = argv[i];
1826 }else{
1827 cmdlineError("unknown argument: %s", argv[i]);
1828 }
1829 }
1830 if( zDb2==0 ){
1831 cmdlineError("two database arguments required");
1832 }
1833 rc = sqlite3_open(zDb1, &g.db);
1834 if( rc ){
1835 cmdlineError("cannot open database file \"%s\"", zDb1);
1836 }
1837 rc = sqlite3_exec(g.db, "SELECT * FROM sqlite_master", 0, 0, &zErrMsg);
1838 if( rc || zErrMsg ){
1839 cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb1);
1840 }
drh6582ae52015-05-12 12:24:50 +00001841#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh9a9219f2015-05-04 13:25:56 +00001842 sqlite3_enable_load_extension(g.db, 1);
1843 for(i=0; i<nExt; i++){
1844 rc = sqlite3_load_extension(g.db, azExt[i], 0, &zErrMsg);
1845 if( rc || zErrMsg ){
1846 cmdlineError("error loading %s: %s", azExt[i], zErrMsg);
1847 }
1848 }
drh6582ae52015-05-12 12:24:50 +00001849#endif
drh9a9219f2015-05-04 13:25:56 +00001850 free(azExt);
drhd62c0f42015-04-09 13:34:29 +00001851 zSql = sqlite3_mprintf("ATTACH %Q as aux;", zDb2);
1852 rc = sqlite3_exec(g.db, zSql, 0, 0, &zErrMsg);
1853 if( rc || zErrMsg ){
1854 cmdlineError("cannot attach database \"%s\"", zDb2);
1855 }
1856 rc = sqlite3_exec(g.db, "SELECT * FROM aux.sqlite_master", 0, 0, &zErrMsg);
1857 if( rc || zErrMsg ){
1858 cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb2);
1859 }
1860
1861 if( zTab ){
drh8a1cd762015-04-14 19:01:08 +00001862 xDiff(zTab, out);
drhd62c0f42015-04-09 13:34:29 +00001863 }else{
1864 /* Handle tables one by one */
1865 pStmt = db_prepare(
1866 "SELECT name FROM main.sqlite_master\n"
1867 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1868 " UNION\n"
1869 "SELECT name FROM aux.sqlite_master\n"
1870 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1871 " ORDER BY name"
1872 );
1873 while( SQLITE_ROW==sqlite3_step(pStmt) ){
drh8a1cd762015-04-14 19:01:08 +00001874 xDiff((const char*)sqlite3_column_text(pStmt,0), out);
drhd62c0f42015-04-09 13:34:29 +00001875 }
1876 sqlite3_finalize(pStmt);
1877 }
1878
1879 /* TBD: Handle trigger differences */
1880 /* TBD: Handle view differences */
1881 sqlite3_close(g.db);
1882 return 0;
1883}