blob: 944968fe0587dd50b1fedd304b57a7513e13c425 [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 ){
drhedd22602015-11-07 18:32:17 +0000561 for(n=0; az[n] && az2[n]; n++){
drhd62c0f42015-04-09 13:34:29 +0000562 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 */
drhedd22602015-11-07 18:32:17 +0000571 fprintf(out, "DROP TABLE %s; -- due to schema mismatch\n", zId);
drh8a1cd762015-04-14 19:01:08 +0000572 dump_table(zTab, out);
drhd62c0f42015-04-09 13:34:29 +0000573 goto end_diff_one_table;
574 }
575
576 /* Build the comparison query */
drhedd22602015-11-07 18:32:17 +0000577 for(n2=n; az2[n2]; n2++){
578 fprintf(out, "ALTER TABLE %s ADD COLUMN %s;\n", zId, safeId(az2[n2]));
579 }
drhd62c0f42015-04-09 13:34:29 +0000580 nQ = nPk2+1+2*(n2-nPk2);
581 if( n2>nPk2 ){
582 zSep = "SELECT ";
583 for(i=0; i<nPk; i++){
584 strPrintf(&sql, "%sB.%s", zSep, az[i]);
585 zSep = ", ";
586 }
587 strPrintf(&sql, ", 1%s -- changed row\n", nPk==n ? "" : ",");
588 while( az[i] ){
589 strPrintf(&sql, " A.%s IS NOT B.%s, B.%s%s\n",
drhedd22602015-11-07 18:32:17 +0000590 az[i], az2[i], az2[i], az2[i+1]==0 ? "" : ",");
591 i++;
592 }
593 while( az2[i] ){
594 strPrintf(&sql, " B.%s IS NOT NULL, B.%s%s\n",
595 az2[i], az2[i], az2[i+1]==0 ? "" : ",");
drhd62c0f42015-04-09 13:34:29 +0000596 i++;
597 }
598 strPrintf(&sql, " FROM main.%s A, aux.%s B\n", zId, zId);
599 zSep = " WHERE";
600 for(i=0; i<nPk; i++){
601 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
602 zSep = " AND";
603 }
604 zSep = "\n AND (";
605 while( az[i] ){
606 strPrintf(&sql, "%sA.%s IS NOT B.%s%s\n",
drhedd22602015-11-07 18:32:17 +0000607 zSep, az[i], az2[i], az2[i+1]==0 ? ")" : "");
608 zSep = " OR ";
609 i++;
610 }
611 while( az2[i] ){
612 strPrintf(&sql, "%sB.%s IS NOT NULL%s\n",
613 zSep, az2[i], az2[i+1]==0 ? ")" : "");
drhd62c0f42015-04-09 13:34:29 +0000614 zSep = " OR ";
615 i++;
616 }
617 strPrintf(&sql, " UNION ALL\n");
618 }
619 zSep = "SELECT ";
620 for(i=0; i<nPk; i++){
621 strPrintf(&sql, "%sA.%s", zSep, az[i]);
622 zSep = ", ";
623 }
624 strPrintf(&sql, ", 2%s -- deleted row\n", nPk==n ? "" : ",");
drhedd22602015-11-07 18:32:17 +0000625 while( az2[i] ){
drhd62c0f42015-04-09 13:34:29 +0000626 strPrintf(&sql, " NULL, NULL%s\n", i==n2-1 ? "" : ",");
627 i++;
628 }
629 strPrintf(&sql, " FROM main.%s A\n", zId);
630 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B\n", zId);
631 zSep = " WHERE";
632 for(i=0; i<nPk; i++){
633 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
634 zSep = " AND";
635 }
636 strPrintf(&sql, ")\n");
637 zSep = " UNION ALL\nSELECT ";
638 for(i=0; i<nPk; i++){
639 strPrintf(&sql, "%sB.%s", zSep, az[i]);
640 zSep = ", ";
641 }
642 strPrintf(&sql, ", 3%s -- inserted row\n", nPk==n ? "" : ",");
643 while( az2[i] ){
drhedd22602015-11-07 18:32:17 +0000644 strPrintf(&sql, " 1, B.%s%s\n", az2[i], az2[i+1]==0 ? "" : ",");
drhd62c0f42015-04-09 13:34:29 +0000645 i++;
646 }
647 strPrintf(&sql, " FROM aux.%s B\n", zId);
648 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A\n", zId);
649 zSep = " WHERE";
650 for(i=0; i<nPk; i++){
651 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
652 zSep = " AND";
653 }
654 strPrintf(&sql, ")\n ORDER BY");
655 zSep = " ";
656 for(i=1; i<=nPk; i++){
657 strPrintf(&sql, "%s%d", zSep, i);
658 zSep = ", ";
659 }
660 strPrintf(&sql, ";\n");
661
662 if( g.fDebug & DEBUG_DIFF_SQL ){
663 printf("SQL for %s:\n%s\n", zId, sql.z);
664 goto end_diff_one_table;
665 }
666
667 /* Drop indexes that are missing in the destination */
668 pStmt = db_prepare(
669 "SELECT name FROM main.sqlite_master"
670 " WHERE type='index' AND tbl_name=%Q"
671 " AND sql IS NOT NULL"
672 " AND sql NOT IN (SELECT sql FROM aux.sqlite_master"
673 " WHERE type='index' AND tbl_name=%Q"
674 " AND sql IS NOT NULL)",
675 zTab, zTab);
676 while( SQLITE_ROW==sqlite3_step(pStmt) ){
677 char *z = safeId((const char*)sqlite3_column_text(pStmt,0));
drh8a1cd762015-04-14 19:01:08 +0000678 fprintf(out, "DROP INDEX %s;\n", z);
drhd62c0f42015-04-09 13:34:29 +0000679 sqlite3_free(z);
680 }
681 sqlite3_finalize(pStmt);
682
683 /* Run the query and output differences */
684 if( !g.bSchemaOnly ){
685 pStmt = db_prepare(sql.z);
686 while( SQLITE_ROW==sqlite3_step(pStmt) ){
687 int iType = sqlite3_column_int(pStmt, nPk);
688 if( iType==1 || iType==2 ){
689 if( iType==1 ){ /* Change the content of a row */
drh8a1cd762015-04-14 19:01:08 +0000690 fprintf(out, "UPDATE %s", zId);
drhd62c0f42015-04-09 13:34:29 +0000691 zSep = " SET";
692 for(i=nPk+1; i<nQ; i+=2){
693 if( sqlite3_column_int(pStmt,i)==0 ) continue;
drh8a1cd762015-04-14 19:01:08 +0000694 fprintf(out, "%s %s=", zSep, az2[(i+nPk-1)/2]);
drhd62c0f42015-04-09 13:34:29 +0000695 zSep = ",";
drh8a1cd762015-04-14 19:01:08 +0000696 printQuoted(out, sqlite3_column_value(pStmt,i+1));
drhd62c0f42015-04-09 13:34:29 +0000697 }
698 }else{ /* Delete a row */
drh8a1cd762015-04-14 19:01:08 +0000699 fprintf(out, "DELETE FROM %s", zId);
drhd62c0f42015-04-09 13:34:29 +0000700 }
701 zSep = " WHERE";
702 for(i=0; i<nPk; i++){
drh8a1cd762015-04-14 19:01:08 +0000703 fprintf(out, "%s %s=", zSep, az2[i]);
704 printQuoted(out, sqlite3_column_value(pStmt,i));
drhd62c0f42015-04-09 13:34:29 +0000705 zSep = ",";
706 }
drh8a1cd762015-04-14 19:01:08 +0000707 fprintf(out, ";\n");
drhd62c0f42015-04-09 13:34:29 +0000708 }else{ /* Insert a row */
drh8a1cd762015-04-14 19:01:08 +0000709 fprintf(out, "INSERT INTO %s(%s", zId, az2[0]);
710 for(i=1; az2[i]; i++) fprintf(out, ",%s", az2[i]);
711 fprintf(out, ") VALUES");
drhd62c0f42015-04-09 13:34:29 +0000712 zSep = "(";
713 for(i=0; i<nPk2; i++){
drh8a1cd762015-04-14 19:01:08 +0000714 fprintf(out, "%s", zSep);
drhd62c0f42015-04-09 13:34:29 +0000715 zSep = ",";
drh8a1cd762015-04-14 19:01:08 +0000716 printQuoted(out, sqlite3_column_value(pStmt,i));
drhd62c0f42015-04-09 13:34:29 +0000717 }
718 for(i=nPk2+2; i<nQ; i+=2){
drh8a1cd762015-04-14 19:01:08 +0000719 fprintf(out, ",");
720 printQuoted(out, sqlite3_column_value(pStmt,i));
drhd62c0f42015-04-09 13:34:29 +0000721 }
drh8a1cd762015-04-14 19:01:08 +0000722 fprintf(out, ");\n");
drhd62c0f42015-04-09 13:34:29 +0000723 }
724 }
725 sqlite3_finalize(pStmt);
726 } /* endif !g.bSchemaOnly */
727
728 /* Create indexes that are missing in the source */
729 pStmt = db_prepare(
730 "SELECT sql FROM aux.sqlite_master"
731 " WHERE type='index' AND tbl_name=%Q"
732 " AND sql IS NOT NULL"
733 " AND sql NOT IN (SELECT sql FROM main.sqlite_master"
734 " WHERE type='index' AND tbl_name=%Q"
735 " AND sql IS NOT NULL)",
736 zTab, zTab);
737 while( SQLITE_ROW==sqlite3_step(pStmt) ){
drh8a1cd762015-04-14 19:01:08 +0000738 fprintf(out, "%s;\n", sqlite3_column_text(pStmt,0));
drhd62c0f42015-04-09 13:34:29 +0000739 }
740 sqlite3_finalize(pStmt);
741
742end_diff_one_table:
743 strFree(&sql);
744 sqlite3_free(zId);
745 namelistFree(az);
746 namelistFree(az2);
747 return;
748}
749
750/*
dan99461852015-07-30 20:26:16 +0000751** Check that table zTab exists and has the same schema in both the "main"
752** and "aux" databases currently opened by the global db handle. If they
753** do not, output an error message on stderr and exit(1). Otherwise, if
754** the schemas do match, return control to the caller.
755*/
756static void checkSchemasMatch(const char *zTab){
757 sqlite3_stmt *pStmt = db_prepare(
758 "SELECT A.sql=B.sql FROM main.sqlite_master A, aux.sqlite_master B"
759 " WHERE A.name=%Q AND B.name=%Q", zTab, zTab
760 );
761 if( SQLITE_ROW==sqlite3_step(pStmt) ){
762 if( sqlite3_column_int(pStmt,0)==0 ){
763 runtimeError("schema changes for table %s", safeId(zTab));
764 }
765 }else{
766 runtimeError("table %s missing from one or both databases", safeId(zTab));
767 }
768 sqlite3_finalize(pStmt);
769}
770
dana9ca8af2015-07-31 19:52:03 +0000771/**************************************************************************
772** The following code is copied from fossil. It is used to generate the
773** fossil delta blobs sometimes used in RBU update records.
774*/
775
776typedef unsigned short u16;
777typedef unsigned int u32;
778typedef unsigned char u8;
779
780/*
781** The width of a hash window in bytes. The algorithm only works if this
782** is a power of 2.
783*/
784#define NHASH 16
785
786/*
787** The current state of the rolling hash.
788**
789** z[] holds the values that have been hashed. z[] is a circular buffer.
790** z[i] is the first entry and z[(i+NHASH-1)%NHASH] is the last entry of
791** the window.
792**
793** Hash.a is the sum of all elements of hash.z[]. Hash.b is a weighted
794** sum. Hash.b is z[i]*NHASH + z[i+1]*(NHASH-1) + ... + z[i+NHASH-1]*1.
795** (Each index for z[] should be module NHASH, of course. The %NHASH operator
796** is omitted in the prior expression for brevity.)
797*/
798typedef struct hash hash;
799struct hash {
800 u16 a, b; /* Hash values */
801 u16 i; /* Start of the hash window */
802 char z[NHASH]; /* The values that have been hashed */
803};
804
805/*
806** Initialize the rolling hash using the first NHASH characters of z[]
807*/
808static void hash_init(hash *pHash, const char *z){
809 u16 a, b, i;
810 a = b = 0;
811 for(i=0; i<NHASH; i++){
812 a += z[i];
813 b += (NHASH-i)*z[i];
814 pHash->z[i] = z[i];
815 }
816 pHash->a = a & 0xffff;
817 pHash->b = b & 0xffff;
818 pHash->i = 0;
819}
820
821/*
822** Advance the rolling hash by a single character "c"
823*/
824static void hash_next(hash *pHash, int c){
825 u16 old = pHash->z[pHash->i];
mistachkin1abbe282015-08-20 21:09:32 +0000826 pHash->z[pHash->i] = (char)c;
dana9ca8af2015-07-31 19:52:03 +0000827 pHash->i = (pHash->i+1)&(NHASH-1);
mistachkin1abbe282015-08-20 21:09:32 +0000828 pHash->a = pHash->a - old + (char)c;
dana9ca8af2015-07-31 19:52:03 +0000829 pHash->b = pHash->b - NHASH*old + pHash->a;
830}
831
832/*
833** Return a 32-bit hash value
834*/
835static u32 hash_32bit(hash *pHash){
836 return (pHash->a & 0xffff) | (((u32)(pHash->b & 0xffff))<<16);
837}
838
839/*
840** Write an base-64 integer into the given buffer.
841*/
842static void putInt(unsigned int v, char **pz){
843 static const char zDigits[] =
844 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~";
845 /* 123456789 123456789 123456789 123456789 123456789 123456789 123 */
846 int i, j;
847 char zBuf[20];
848 if( v==0 ){
849 *(*pz)++ = '0';
850 return;
851 }
852 for(i=0; v>0; i++, v>>=6){
853 zBuf[i] = zDigits[v&0x3f];
854 }
855 for(j=i-1; j>=0; j--){
856 *(*pz)++ = zBuf[j];
857 }
858}
859
860/*
dana9ca8af2015-07-31 19:52:03 +0000861** Return the number digits in the base-64 representation of a positive integer
862*/
863static int digit_count(int v){
864 unsigned int i, x;
mistachkin1abbe282015-08-20 21:09:32 +0000865 for(i=1, x=64; (unsigned int)v>=x; i++, x <<= 6){}
dana9ca8af2015-07-31 19:52:03 +0000866 return i;
867}
868
869/*
870** Compute a 32-bit checksum on the N-byte buffer. Return the result.
871*/
872static unsigned int checksum(const char *zIn, size_t N){
873 const unsigned char *z = (const unsigned char *)zIn;
874 unsigned sum0 = 0;
875 unsigned sum1 = 0;
876 unsigned sum2 = 0;
877 unsigned sum3 = 0;
878 while(N >= 16){
879 sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
880 sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
881 sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
882 sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
883 z += 16;
884 N -= 16;
885 }
886 while(N >= 4){
887 sum0 += z[0];
888 sum1 += z[1];
889 sum2 += z[2];
890 sum3 += z[3];
891 z += 4;
892 N -= 4;
893 }
894 sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
895 switch(N){
896 case 3: sum3 += (z[2] << 8);
897 case 2: sum3 += (z[1] << 16);
898 case 1: sum3 += (z[0] << 24);
899 default: ;
900 }
901 return sum3;
902}
903
904/*
905** Create a new delta.
906**
907** The delta is written into a preallocated buffer, zDelta, which
908** should be at least 60 bytes longer than the target file, zOut.
909** The delta string will be NUL-terminated, but it might also contain
910** embedded NUL characters if either the zSrc or zOut files are
911** binary. This function returns the length of the delta string
912** in bytes, excluding the final NUL terminator character.
913**
914** Output Format:
915**
916** The delta begins with a base64 number followed by a newline. This
917** number is the number of bytes in the TARGET file. Thus, given a
918** delta file z, a program can compute the size of the output file
919** simply by reading the first line and decoding the base-64 number
920** found there. The delta_output_size() routine does exactly this.
921**
922** After the initial size number, the delta consists of a series of
923** literal text segments and commands to copy from the SOURCE file.
924** A copy command looks like this:
925**
926** NNN@MMM,
927**
928** where NNN is the number of bytes to be copied and MMM is the offset
929** into the source file of the first byte (both base-64). If NNN is 0
930** it means copy the rest of the input file. Literal text is like this:
931**
932** NNN:TTTTT
933**
934** where NNN is the number of bytes of text (base-64) and TTTTT is the text.
935**
936** The last term is of the form
937**
938** NNN;
939**
940** In this case, NNN is a 32-bit bigendian checksum of the output file
941** that can be used to verify that the delta applied correctly. All
942** numbers are in base-64.
943**
944** Pure text files generate a pure text delta. Binary files generate a
945** delta that may contain some binary data.
946**
947** Algorithm:
948**
949** The encoder first builds a hash table to help it find matching
950** patterns in the source file. 16-byte chunks of the source file
951** sampled at evenly spaced intervals are used to populate the hash
952** table.
953**
954** Next we begin scanning the target file using a sliding 16-byte
955** window. The hash of the 16-byte window in the target is used to
956** search for a matching section in the source file. When a match
957** is found, a copy command is added to the delta. An effort is
958** made to extend the matching section to regions that come before
959** and after the 16-byte hash window. A copy command is only issued
960** if the result would use less space that just quoting the text
961** literally. Literal text is added to the delta for sections that
962** do not match or which can not be encoded efficiently using copy
963** commands.
964*/
965static int rbuDeltaCreate(
966 const char *zSrc, /* The source or pattern file */
967 unsigned int lenSrc, /* Length of the source file */
968 const char *zOut, /* The target file */
969 unsigned int lenOut, /* Length of the target file */
970 char *zDelta /* Write the delta into this buffer */
971){
mistachkin1abbe282015-08-20 21:09:32 +0000972 unsigned int i, base;
dana9ca8af2015-07-31 19:52:03 +0000973 char *zOrigDelta = zDelta;
974 hash h;
975 int nHash; /* Number of hash table entries */
976 int *landmark; /* Primary hash table */
977 int *collide; /* Collision chain */
978 int lastRead = -1; /* Last byte of zSrc read by a COPY command */
979
980 /* Add the target file size to the beginning of the delta
981 */
982 putInt(lenOut, &zDelta);
983 *(zDelta++) = '\n';
984
985 /* If the source file is very small, it means that we have no
986 ** chance of ever doing a copy command. Just output a single
987 ** literal segment for the entire target and exit.
988 */
989 if( lenSrc<=NHASH ){
990 putInt(lenOut, &zDelta);
991 *(zDelta++) = ':';
992 memcpy(zDelta, zOut, lenOut);
993 zDelta += lenOut;
994 putInt(checksum(zOut, lenOut), &zDelta);
995 *(zDelta++) = ';';
996 return zDelta - zOrigDelta;
997 }
998
999 /* Compute the hash table used to locate matching sections in the
1000 ** source file.
1001 */
1002 nHash = lenSrc/NHASH;
1003 collide = sqlite3_malloc( nHash*2*sizeof(int) );
1004 landmark = &collide[nHash];
1005 memset(landmark, -1, nHash*sizeof(int));
1006 memset(collide, -1, nHash*sizeof(int));
1007 for(i=0; i<lenSrc-NHASH; i+=NHASH){
1008 int hv;
1009 hash_init(&h, &zSrc[i]);
1010 hv = hash_32bit(&h) % nHash;
1011 collide[i/NHASH] = landmark[hv];
1012 landmark[hv] = i/NHASH;
1013 }
1014
1015 /* Begin scanning the target file and generating copy commands and
1016 ** literal sections of the delta.
1017 */
1018 base = 0; /* We have already generated everything before zOut[base] */
1019 while( base+NHASH<lenOut ){
1020 int iSrc, iBlock;
mistachkin1abbe282015-08-20 21:09:32 +00001021 int bestCnt, bestOfst=0, bestLitsz=0;
dana9ca8af2015-07-31 19:52:03 +00001022 hash_init(&h, &zOut[base]);
1023 i = 0; /* Trying to match a landmark against zOut[base+i] */
1024 bestCnt = 0;
1025 while( 1 ){
1026 int hv;
1027 int limit = 250;
1028
1029 hv = hash_32bit(&h) % nHash;
1030 iBlock = landmark[hv];
1031 while( iBlock>=0 && (limit--)>0 ){
1032 /*
1033 ** The hash window has identified a potential match against
1034 ** landmark block iBlock. But we need to investigate further.
1035 **
1036 ** Look for a region in zOut that matches zSrc. Anchor the search
1037 ** at zSrc[iSrc] and zOut[base+i]. Do not include anything prior to
1038 ** zOut[base] or after zOut[outLen] nor anything after zSrc[srcLen].
1039 **
1040 ** Set cnt equal to the length of the match and set ofst so that
1041 ** zSrc[ofst] is the first element of the match. litsz is the number
1042 ** of characters between zOut[base] and the beginning of the match.
1043 ** sz will be the overhead (in bytes) needed to encode the copy
1044 ** command. Only generate copy command if the overhead of the
1045 ** copy command is less than the amount of literal text to be copied.
1046 */
1047 int cnt, ofst, litsz;
1048 int j, k, x, y;
1049 int sz;
1050
1051 /* Beginning at iSrc, match forwards as far as we can. j counts
1052 ** the number of characters that match */
1053 iSrc = iBlock*NHASH;
mistachkin1abbe282015-08-20 21:09:32 +00001054 for(
1055 j=0, x=iSrc, y=base+i;
1056 (unsigned int)x<lenSrc && (unsigned int)y<lenOut;
1057 j++, x++, y++
1058 ){
dana9ca8af2015-07-31 19:52:03 +00001059 if( zSrc[x]!=zOut[y] ) break;
1060 }
1061 j--;
1062
1063 /* Beginning at iSrc-1, match backwards as far as we can. k counts
1064 ** the number of characters that match */
mistachkin1abbe282015-08-20 21:09:32 +00001065 for(k=1; k<iSrc && (unsigned int)k<=i; k++){
dana9ca8af2015-07-31 19:52:03 +00001066 if( zSrc[iSrc-k]!=zOut[base+i-k] ) break;
1067 }
1068 k--;
1069
1070 /* Compute the offset and size of the matching region */
1071 ofst = iSrc-k;
1072 cnt = j+k+1;
1073 litsz = i-k; /* Number of bytes of literal text before the copy */
1074 /* sz will hold the number of bytes needed to encode the "insert"
1075 ** command and the copy command, not counting the "insert" text */
1076 sz = digit_count(i-k)+digit_count(cnt)+digit_count(ofst)+3;
1077 if( cnt>=sz && cnt>bestCnt ){
1078 /* Remember this match only if it is the best so far and it
1079 ** does not increase the file size */
1080 bestCnt = cnt;
1081 bestOfst = iSrc-k;
1082 bestLitsz = litsz;
1083 }
1084
1085 /* Check the next matching block */
1086 iBlock = collide[iBlock];
1087 }
1088
1089 /* We have a copy command that does not cause the delta to be larger
1090 ** than a literal insert. So add the copy command to the delta.
1091 */
1092 if( bestCnt>0 ){
1093 if( bestLitsz>0 ){
1094 /* Add an insert command before the copy */
1095 putInt(bestLitsz,&zDelta);
1096 *(zDelta++) = ':';
1097 memcpy(zDelta, &zOut[base], bestLitsz);
1098 zDelta += bestLitsz;
1099 base += bestLitsz;
1100 }
1101 base += bestCnt;
1102 putInt(bestCnt, &zDelta);
1103 *(zDelta++) = '@';
1104 putInt(bestOfst, &zDelta);
1105 *(zDelta++) = ',';
1106 if( bestOfst + bestCnt -1 > lastRead ){
1107 lastRead = bestOfst + bestCnt - 1;
1108 }
1109 bestCnt = 0;
1110 break;
1111 }
1112
1113 /* If we reach this point, it means no match is found so far */
1114 if( base+i+NHASH>=lenOut ){
1115 /* We have reached the end of the file and have not found any
1116 ** matches. Do an "insert" for everything that does not match */
1117 putInt(lenOut-base, &zDelta);
1118 *(zDelta++) = ':';
1119 memcpy(zDelta, &zOut[base], lenOut-base);
1120 zDelta += lenOut-base;
1121 base = lenOut;
1122 break;
1123 }
1124
1125 /* Advance the hash by one character. Keep looking for a match */
1126 hash_next(&h, zOut[base+i+NHASH]);
1127 i++;
1128 }
1129 }
1130 /* Output a final "insert" record to get all the text at the end of
1131 ** the file that does not match anything in the source file.
1132 */
1133 if( base<lenOut ){
1134 putInt(lenOut-base, &zDelta);
1135 *(zDelta++) = ':';
1136 memcpy(zDelta, &zOut[base], lenOut-base);
1137 zDelta += lenOut-base;
1138 }
1139 /* Output the final checksum record. */
1140 putInt(checksum(zOut, lenOut), &zDelta);
1141 *(zDelta++) = ';';
1142 sqlite3_free(collide);
1143 return zDelta - zOrigDelta;
1144}
1145
1146/*
1147** End of code copied from fossil.
1148**************************************************************************/
1149
dan99461852015-07-30 20:26:16 +00001150static void strPrintfArray(
1151 Str *pStr, /* String object to append to */
1152 const char *zSep, /* Separator string */
1153 const char *zFmt, /* Format for each entry */
1154 char **az, int n /* Array of strings & its size (or -1) */
1155){
1156 int i;
1157 for(i=0; az[i] && (i<n || n<0); i++){
1158 if( i!=0 ) strPrintf(pStr, "%s", zSep);
1159 strPrintf(pStr, zFmt, az[i], az[i], az[i]);
1160 }
1161}
1162
1163static void getRbudiffQuery(
1164 const char *zTab,
1165 char **azCol,
1166 int nPK,
1167 int bOtaRowid,
1168 Str *pSql
1169){
1170 int i;
1171
1172 /* First the newly inserted rows: **/
1173 strPrintf(pSql, "SELECT ");
1174 strPrintfArray(pSql, ", ", "%s", azCol, -1);
dana9ca8af2015-07-31 19:52:03 +00001175 strPrintf(pSql, ", 0, "); /* Set ota_control to 0 for an insert */
1176 strPrintfArray(pSql, ", ", "NULL", azCol, -1);
dan99461852015-07-30 20:26:16 +00001177 strPrintf(pSql, " FROM aux.%Q AS n WHERE NOT EXISTS (\n", zTab);
1178 strPrintf(pSql, " SELECT 1 FROM ", zTab);
1179 strPrintf(pSql, " main.%Q AS o WHERE ", zTab);
1180 strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
1181 strPrintf(pSql, "\n)");
1182
1183 /* Deleted rows: */
1184 strPrintf(pSql, "\nUNION ALL\nSELECT ");
1185 strPrintfArray(pSql, ", ", "%s", azCol, nPK);
dandd688e72015-07-31 15:13:29 +00001186 if( azCol[nPK] ){
1187 strPrintf(pSql, ", ");
1188 strPrintfArray(pSql, ", ", "NULL", &azCol[nPK], -1);
1189 }
dana9ca8af2015-07-31 19:52:03 +00001190 strPrintf(pSql, ", 1, "); /* Set ota_control to 1 for a delete */
1191 strPrintfArray(pSql, ", ", "NULL", azCol, -1);
dan99461852015-07-30 20:26:16 +00001192 strPrintf(pSql, " FROM main.%Q AS n WHERE NOT EXISTS (\n", zTab);
1193 strPrintf(pSql, " SELECT 1 FROM ", zTab);
1194 strPrintf(pSql, " aux.%Q AS o WHERE ", zTab);
1195 strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
1196 strPrintf(pSql, "\n) ");
1197
dandd688e72015-07-31 15:13:29 +00001198 /* Updated rows. If all table columns are part of the primary key, there
1199 ** can be no updates. In this case this part of the compound SELECT can
1200 ** be omitted altogether. */
1201 if( azCol[nPK] ){
1202 strPrintf(pSql, "\nUNION ALL\nSELECT ");
1203 strPrintfArray(pSql, ", ", "n.%s", azCol, nPK);
dan99461852015-07-30 20:26:16 +00001204 strPrintf(pSql, ",\n");
dandd688e72015-07-31 15:13:29 +00001205 strPrintfArray(pSql, " ,\n",
1206 " CASE WHEN n.%s IS o.%s THEN NULL ELSE n.%s END", &azCol[nPK], -1
1207 );
dan99461852015-07-30 20:26:16 +00001208
dandd688e72015-07-31 15:13:29 +00001209 if( bOtaRowid==0 ){
1210 strPrintf(pSql, ", '");
1211 strPrintfArray(pSql, "", ".", azCol, nPK);
1212 strPrintf(pSql, "' ||\n");
1213 }else{
1214 strPrintf(pSql, ",\n");
1215 }
1216 strPrintfArray(pSql, " ||\n",
1217 " CASE WHEN n.%s IS o.%s THEN '.' ELSE 'x' END", &azCol[nPK], -1
1218 );
dana9ca8af2015-07-31 19:52:03 +00001219 strPrintf(pSql, "\nAS ota_control, ");
1220 strPrintfArray(pSql, ", ", "NULL", azCol, nPK);
1221 strPrintf(pSql, ",\n");
1222 strPrintfArray(pSql, " ,\n",
1223 " CASE WHEN n.%s IS o.%s THEN NULL ELSE o.%s END", &azCol[nPK], -1
1224 );
dandd688e72015-07-31 15:13:29 +00001225
1226 strPrintf(pSql, "\nFROM main.%Q AS o, aux.%Q AS n\nWHERE ", zTab, zTab);
1227 strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
1228 strPrintf(pSql, " AND ota_control LIKE '%%x%%'");
1229 }
dan99461852015-07-30 20:26:16 +00001230
1231 /* Now add an ORDER BY clause to sort everything by PK. */
1232 strPrintf(pSql, "\nORDER BY ");
1233 for(i=1; i<=nPK; i++) strPrintf(pSql, "%s%d", ((i>1)?", ":""), i);
1234}
1235
1236static void rbudiff_one_table(const char *zTab, FILE *out){
1237 int bOtaRowid; /* True to use an ota_rowid column */
1238 int nPK; /* Number of primary key columns in table */
1239 char **azCol; /* NULL terminated array of col names */
1240 int i;
1241 int nCol;
1242 Str ct = {0, 0, 0}; /* The "CREATE TABLE data_xxx" statement */
1243 Str sql = {0, 0, 0}; /* Query to find differences */
1244 Str insert = {0, 0, 0}; /* First part of output INSERT statement */
1245 sqlite3_stmt *pStmt = 0;
1246
1247 /* --rbu mode must use real primary keys. */
1248 g.bSchemaPK = 1;
1249
1250 /* Check that the schemas of the two tables match. Exit early otherwise. */
1251 checkSchemasMatch(zTab);
1252
1253 /* Grab the column names and PK details for the table(s). If no usable PK
1254 ** columns are found, bail out early. */
1255 azCol = columnNames("main", zTab, &nPK, &bOtaRowid);
1256 if( azCol==0 ){
1257 runtimeError("table %s has no usable PK columns", zTab);
1258 }
dana9ca8af2015-07-31 19:52:03 +00001259 for(nCol=0; azCol[nCol]; nCol++);
dan99461852015-07-30 20:26:16 +00001260
1261 /* Build and output the CREATE TABLE statement for the data_xxx table */
1262 strPrintf(&ct, "CREATE TABLE IF NOT EXISTS 'data_%q'(", zTab);
1263 if( bOtaRowid ) strPrintf(&ct, "rbu_rowid, ");
1264 strPrintfArray(&ct, ", ", "%s", &azCol[bOtaRowid], -1);
1265 strPrintf(&ct, ", rbu_control);");
1266
dan99461852015-07-30 20:26:16 +00001267 /* Get the SQL for the query to retrieve data from the two databases */
1268 getRbudiffQuery(zTab, azCol, nPK, bOtaRowid, &sql);
1269
1270 /* Build the first part of the INSERT statement output for each row
1271 ** in the data_xxx table. */
1272 strPrintf(&insert, "INSERT INTO 'data_%q' (", zTab);
1273 if( bOtaRowid ) strPrintf(&insert, "rbu_rowid, ");
1274 strPrintfArray(&insert, ", ", "%s", &azCol[bOtaRowid], -1);
1275 strPrintf(&insert, ", rbu_control) VALUES(");
1276
1277 pStmt = db_prepare("%s", sql.z);
dana9ca8af2015-07-31 19:52:03 +00001278
dan99461852015-07-30 20:26:16 +00001279 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dana9ca8af2015-07-31 19:52:03 +00001280
1281 /* If this is the first row output, print out the CREATE TABLE
1282 ** statement first. And then set ct.z to NULL so that it is not
1283 ** printed again. */
dan99461852015-07-30 20:26:16 +00001284 if( ct.z ){
1285 fprintf(out, "%s\n", ct.z);
1286 strFree(&ct);
1287 }
1288
dana9ca8af2015-07-31 19:52:03 +00001289 /* Output the first part of the INSERT statement */
dan99461852015-07-30 20:26:16 +00001290 fprintf(out, "%s", insert.z);
dana9ca8af2015-07-31 19:52:03 +00001291
1292 if( sqlite3_column_type(pStmt, nCol)==SQLITE_INTEGER ){
1293 for(i=0; i<=nCol; i++){
1294 if( i>0 ) fprintf(out, ", ");
1295 printQuoted(out, sqlite3_column_value(pStmt, i));
1296 }
1297 }else{
1298 char *zOtaControl;
1299 int nOtaControl = sqlite3_column_bytes(pStmt, nCol);
1300
1301 zOtaControl = (char*)sqlite3_malloc(nOtaControl);
1302 memcpy(zOtaControl, sqlite3_column_text(pStmt, nCol), nOtaControl+1);
1303
1304 for(i=0; i<nCol; i++){
1305 int bDone = 0;
1306 if( i>=nPK
1307 && sqlite3_column_type(pStmt, i)==SQLITE_BLOB
1308 && sqlite3_column_type(pStmt, nCol+1+i)==SQLITE_BLOB
1309 ){
1310 const char *aSrc = sqlite3_column_blob(pStmt, nCol+1+i);
1311 int nSrc = sqlite3_column_bytes(pStmt, nCol+1+i);
1312 const char *aFinal = sqlite3_column_blob(pStmt, i);
1313 int nFinal = sqlite3_column_bytes(pStmt, i);
1314 char *aDelta;
1315 int nDelta;
1316
1317 aDelta = sqlite3_malloc(nFinal + 60);
1318 nDelta = rbuDeltaCreate(aSrc, nSrc, aFinal, nFinal, aDelta);
1319 if( nDelta<nFinal ){
1320 int j;
1321 fprintf(out, "x'");
1322 for(j=0; j<nDelta; j++) fprintf(out, "%02x", (u8)aDelta[j]);
1323 fprintf(out, "'");
1324 zOtaControl[i-bOtaRowid] = 'f';
1325 bDone = 1;
1326 }
1327 sqlite3_free(aDelta);
1328 }
1329
1330 if( bDone==0 ){
1331 printQuoted(out, sqlite3_column_value(pStmt, i));
1332 }
1333 fprintf(out, ", ");
1334 }
1335 fprintf(out, "'%s'", zOtaControl);
1336 sqlite3_free(zOtaControl);
dan99461852015-07-30 20:26:16 +00001337 }
dana9ca8af2015-07-31 19:52:03 +00001338
1339 /* And the closing bracket of the insert statement */
dan99461852015-07-30 20:26:16 +00001340 fprintf(out, ");\n");
1341 }
1342
1343 sqlite3_finalize(pStmt);
1344
1345 strFree(&ct);
1346 strFree(&sql);
1347 strFree(&insert);
1348}
1349
1350/*
drh8a1cd762015-04-14 19:01:08 +00001351** Display a summary of differences between two versions of the same
1352** table table.
1353**
1354** * Number of rows changed
1355** * Number of rows added
1356** * Number of rows deleted
1357** * Number of identical rows
1358*/
1359static void summarize_one_table(const char *zTab, FILE *out){
1360 char *zId = safeId(zTab); /* Name of table (translated for us in SQL) */
1361 char **az = 0; /* Columns in main */
1362 char **az2 = 0; /* Columns in aux */
1363 int nPk; /* Primary key columns in main */
1364 int nPk2; /* Primary key columns in aux */
drhb3f3d642015-04-25 18:39:21 +00001365 int n = 0; /* Number of columns in main */
drh8a1cd762015-04-14 19:01:08 +00001366 int n2; /* Number of columns in aux */
1367 int i; /* Loop counter */
1368 const char *zSep; /* Separator string */
1369 Str sql; /* Comparison query */
1370 sqlite3_stmt *pStmt; /* Query statement to do the diff */
1371 sqlite3_int64 nUpdate; /* Number of updated rows */
1372 sqlite3_int64 nUnchanged; /* Number of unmodified rows */
1373 sqlite3_int64 nDelete; /* Number of deleted rows */
1374 sqlite3_int64 nInsert; /* Number of inserted rows */
1375
1376 strInit(&sql);
1377 if( sqlite3_table_column_metadata(g.db,"aux",zTab,0,0,0,0,0,0) ){
1378 if( !sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
1379 /* Table missing from second database. */
1380 fprintf(out, "%s: missing from second database\n", zTab);
1381 }
1382 goto end_summarize_one_table;
1383 }
1384
1385 if( sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
1386 /* Table missing from source */
1387 fprintf(out, "%s: missing from first database\n", zTab);
1388 goto end_summarize_one_table;
1389 }
1390
dan99461852015-07-30 20:26:16 +00001391 az = columnNames("main", zTab, &nPk, 0);
1392 az2 = columnNames("aux", zTab, &nPk2, 0);
drh8a1cd762015-04-14 19:01:08 +00001393 if( az && az2 ){
1394 for(n=0; az[n]; n++){
1395 if( sqlite3_stricmp(az[n],az2[n])!=0 ) break;
1396 }
1397 }
1398 if( az==0
1399 || az2==0
1400 || nPk!=nPk2
1401 || az[n]
1402 ){
1403 /* Schema mismatch */
1404 fprintf(out, "%s: incompatible schema\n", zTab);
1405 goto end_summarize_one_table;
1406 }
1407
1408 /* Build the comparison query */
1409 for(n2=n; az[n2]; n2++){}
1410 strPrintf(&sql, "SELECT 1, count(*)");
1411 if( n2==nPk2 ){
1412 strPrintf(&sql, ", 0\n");
1413 }else{
1414 zSep = ", sum(";
1415 for(i=nPk; az[i]; i++){
1416 strPrintf(&sql, "%sA.%s IS NOT B.%s", zSep, az[i], az[i]);
1417 zSep = " OR ";
1418 }
1419 strPrintf(&sql, ")\n");
1420 }
1421 strPrintf(&sql, " FROM main.%s A, aux.%s B\n", zId, zId);
1422 zSep = " WHERE";
1423 for(i=0; i<nPk; i++){
1424 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1425 zSep = " AND";
1426 }
1427 strPrintf(&sql, " UNION ALL\n");
1428 strPrintf(&sql, "SELECT 2, count(*), 0\n");
1429 strPrintf(&sql, " FROM main.%s A\n", zId);
1430 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B ", zId);
1431 zSep = "WHERE";
1432 for(i=0; i<nPk; i++){
1433 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1434 zSep = " AND";
1435 }
1436 strPrintf(&sql, ")\n");
1437 strPrintf(&sql, " UNION ALL\n");
1438 strPrintf(&sql, "SELECT 3, count(*), 0\n");
1439 strPrintf(&sql, " FROM aux.%s B\n", zId);
1440 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A ", zId);
1441 zSep = "WHERE";
1442 for(i=0; i<nPk; i++){
1443 strPrintf(&sql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1444 zSep = " AND";
1445 }
1446 strPrintf(&sql, ")\n ORDER BY 1;\n");
1447
1448 if( (g.fDebug & DEBUG_DIFF_SQL)!=0 ){
1449 printf("SQL for %s:\n%s\n", zId, sql.z);
1450 goto end_summarize_one_table;
1451 }
1452
1453 /* Run the query and output difference summary */
1454 pStmt = db_prepare(sql.z);
1455 nUpdate = 0;
1456 nInsert = 0;
1457 nDelete = 0;
1458 nUnchanged = 0;
1459 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1460 switch( sqlite3_column_int(pStmt,0) ){
1461 case 1:
1462 nUpdate = sqlite3_column_int64(pStmt,2);
1463 nUnchanged = sqlite3_column_int64(pStmt,1) - nUpdate;
1464 break;
1465 case 2:
1466 nDelete = sqlite3_column_int64(pStmt,1);
1467 break;
1468 case 3:
1469 nInsert = sqlite3_column_int64(pStmt,1);
1470 break;
1471 }
1472 }
1473 sqlite3_finalize(pStmt);
1474 fprintf(out, "%s: %lld changes, %lld inserts, %lld deletes, %lld unchanged\n",
1475 zTab, nUpdate, nInsert, nDelete, nUnchanged);
1476
1477end_summarize_one_table:
1478 strFree(&sql);
1479 sqlite3_free(zId);
1480 namelistFree(az);
1481 namelistFree(az2);
1482 return;
1483}
1484
1485/*
drh697e5db2015-04-11 12:07:40 +00001486** Write a 64-bit signed integer as a varint onto out
1487*/
1488static void putsVarint(FILE *out, sqlite3_uint64 v){
1489 int i, n;
drh6e42ce42015-04-11 13:48:01 +00001490 unsigned char p[12];
drh697e5db2015-04-11 12:07:40 +00001491 if( v & (((sqlite3_uint64)0xff000000)<<32) ){
1492 p[8] = (unsigned char)v;
1493 v >>= 8;
1494 for(i=7; i>=0; i--){
1495 p[i] = (unsigned char)((v & 0x7f) | 0x80);
1496 v >>= 7;
1497 }
1498 fwrite(p, 8, 1, out);
1499 }else{
1500 n = 9;
1501 do{
1502 p[n--] = (unsigned char)((v & 0x7f) | 0x80);
1503 v >>= 7;
1504 }while( v!=0 );
drh6e42ce42015-04-11 13:48:01 +00001505 p[9] &= 0x7f;
1506 fwrite(p+n+1, 9-n, 1, out);
1507 }
1508}
1509
1510/*
1511** Write an SQLite value onto out.
1512*/
1513static void putValue(FILE *out, sqlite3_value *pVal){
1514 int iDType = sqlite3_value_type(pVal);
1515 sqlite3_int64 iX;
1516 double rX;
1517 sqlite3_uint64 uX;
1518 int j;
1519
1520 putc(iDType, out);
1521 switch( iDType ){
1522 case SQLITE_INTEGER:
1523 iX = sqlite3_value_int64(pVal);
1524 memcpy(&uX, &iX, 8);
1525 for(j=56; j>=0; j-=8) putc((uX>>j)&0xff, out);
1526 break;
1527 case SQLITE_FLOAT:
drh33aa4db2015-05-04 15:04:47 +00001528 rX = sqlite3_value_double(pVal);
drh6e42ce42015-04-11 13:48:01 +00001529 memcpy(&uX, &rX, 8);
1530 for(j=56; j>=0; j-=8) putc((uX>>j)&0xff, out);
1531 break;
1532 case SQLITE_TEXT:
1533 iX = sqlite3_value_bytes(pVal);
1534 putsVarint(out, (sqlite3_uint64)iX);
drh33aa4db2015-05-04 15:04:47 +00001535 fwrite(sqlite3_value_text(pVal),1,(size_t)iX,out);
drh6e42ce42015-04-11 13:48:01 +00001536 break;
1537 case SQLITE_BLOB:
1538 iX = sqlite3_value_bytes(pVal);
1539 putsVarint(out, (sqlite3_uint64)iX);
drh33aa4db2015-05-04 15:04:47 +00001540 fwrite(sqlite3_value_blob(pVal),1,(size_t)iX,out);
drh6e42ce42015-04-11 13:48:01 +00001541 break;
1542 case SQLITE_NULL:
1543 break;
drh697e5db2015-04-11 12:07:40 +00001544 }
1545}
1546
1547/*
drh83e63dc2015-04-10 19:41:18 +00001548** Generate a CHANGESET for all differences from main.zTab to aux.zTab.
1549*/
1550static void changeset_one_table(const char *zTab, FILE *out){
1551 sqlite3_stmt *pStmt; /* SQL statment */
1552 char *zId = safeId(zTab); /* Escaped name of the table */
1553 char **azCol = 0; /* List of escaped column names */
1554 int nCol = 0; /* Number of columns */
1555 int *aiFlg = 0; /* 0 if column is not part of PK */
1556 int *aiPk = 0; /* Column numbers for each PK column */
1557 int nPk = 0; /* Number of PRIMARY KEY columns */
1558 Str sql; /* SQL for the diff query */
drh6e42ce42015-04-11 13:48:01 +00001559 int i, k; /* Loop counters */
drh83e63dc2015-04-10 19:41:18 +00001560 const char *zSep; /* List separator */
1561
dan99461852015-07-30 20:26:16 +00001562 /* Check that the schemas of the two tables match. Exit early otherwise. */
1563 checkSchemasMatch(zTab);
1564
drh83e63dc2015-04-10 19:41:18 +00001565 pStmt = db_prepare("PRAGMA main.table_info=%Q", zTab);
1566 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1567 nCol++;
1568 azCol = sqlite3_realloc(azCol, sizeof(char*)*nCol);
1569 if( azCol==0 ) runtimeError("out of memory");
1570 aiFlg = sqlite3_realloc(aiFlg, sizeof(int)*nCol);
1571 if( aiFlg==0 ) runtimeError("out of memory");
1572 azCol[nCol-1] = safeId((const char*)sqlite3_column_text(pStmt,1));
1573 aiFlg[nCol-1] = i = sqlite3_column_int(pStmt,5);
1574 if( i>0 ){
1575 if( i>nPk ){
1576 nPk = i;
1577 aiPk = sqlite3_realloc(aiPk, sizeof(int)*nPk);
1578 if( aiPk==0 ) runtimeError("out of memory");
1579 }
1580 aiPk[i-1] = nCol-1;
1581 }
1582 }
1583 sqlite3_finalize(pStmt);
1584 if( nPk==0 ) goto end_changeset_one_table;
1585 strInit(&sql);
1586 if( nCol>nPk ){
drh697e5db2015-04-11 12:07:40 +00001587 strPrintf(&sql, "SELECT %d", SQLITE_UPDATE);
drh6e42ce42015-04-11 13:48:01 +00001588 for(i=0; i<nCol; i++){
1589 if( aiFlg[i] ){
1590 strPrintf(&sql, ",\n A.%s", azCol[i]);
1591 }else{
1592 strPrintf(&sql, ",\n A.%s IS NOT B.%s, A.%s, B.%s",
1593 azCol[i], azCol[i], azCol[i], azCol[i]);
1594 }
1595 }
drh83e63dc2015-04-10 19:41:18 +00001596 strPrintf(&sql,"\n FROM main.%s A, aux.%s B\n", zId, zId);
1597 zSep = " WHERE";
1598 for(i=0; i<nPk; i++){
1599 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1600 zSep = " AND";
1601 }
1602 zSep = "\n AND (";
1603 for(i=0; i<nCol; i++){
1604 if( aiFlg[i] ) continue;
1605 strPrintf(&sql, "%sA.%s IS NOT B.%s", zSep, azCol[i], azCol[i]);
1606 zSep = " OR\n ";
1607 }
1608 strPrintf(&sql,")\n UNION ALL\n");
1609 }
drh697e5db2015-04-11 12:07:40 +00001610 strPrintf(&sql, "SELECT %d", SQLITE_DELETE);
drh6e42ce42015-04-11 13:48:01 +00001611 for(i=0; i<nCol; i++){
1612 if( aiFlg[i] ){
1613 strPrintf(&sql, ",\n A.%s", azCol[i]);
1614 }else{
1615 strPrintf(&sql, ",\n 1, A.%s, NULL", azCol[i]);
1616 }
1617 }
1618 strPrintf(&sql, "\n FROM main.%s A\n", zId);
drh83e63dc2015-04-10 19:41:18 +00001619 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B\n", zId);
1620 zSep = " WHERE";
1621 for(i=0; i<nPk; i++){
1622 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1623 zSep = " AND";
1624 }
1625 strPrintf(&sql, ")\n UNION ALL\n");
drh697e5db2015-04-11 12:07:40 +00001626 strPrintf(&sql, "SELECT %d", SQLITE_INSERT);
drh6e42ce42015-04-11 13:48:01 +00001627 for(i=0; i<nCol; i++){
1628 if( aiFlg[i] ){
1629 strPrintf(&sql, ",\n B.%s", azCol[i]);
1630 }else{
1631 strPrintf(&sql, ",\n 1, NULL, B.%s", azCol[i]);
1632 }
1633 }
1634 strPrintf(&sql, "\n FROM aux.%s B\n", zId);
drh83e63dc2015-04-10 19:41:18 +00001635 strPrintf(&sql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A\n", zId);
1636 zSep = " WHERE";
1637 for(i=0; i<nPk; i++){
1638 strPrintf(&sql, "%s A.%s=B.%s", zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1639 zSep = " AND";
1640 }
1641 strPrintf(&sql, ")\n");
1642 strPrintf(&sql, " ORDER BY");
1643 zSep = " ";
1644 for(i=0; i<nPk; i++){
drh6e42ce42015-04-11 13:48:01 +00001645 strPrintf(&sql, "%s %d", zSep, aiPk[i]+2);
drh83e63dc2015-04-10 19:41:18 +00001646 zSep = ",";
1647 }
1648 strPrintf(&sql, ";\n");
1649
drh697e5db2015-04-11 12:07:40 +00001650 if( g.fDebug & DEBUG_DIFF_SQL ){
1651 printf("SQL for %s:\n%s\n", zId, sql.z);
1652 goto end_changeset_one_table;
1653 }
1654
1655 putc('T', out);
1656 putsVarint(out, (sqlite3_uint64)nCol);
1657 for(i=0; i<nCol; i++) putc(aiFlg[i]!=0, out);
1658 fwrite(zTab, 1, strlen(zTab), out);
1659 putc(0, out);
1660
1661 pStmt = db_prepare("%s", sql.z);
1662 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1663 int iType = sqlite3_column_int(pStmt,0);
drh697e5db2015-04-11 12:07:40 +00001664 putc(iType, out);
1665 putc(0, out);
drh6e42ce42015-04-11 13:48:01 +00001666 switch( sqlite3_column_int(pStmt,0) ){
1667 case SQLITE_UPDATE: {
1668 for(k=1, i=0; i<nCol; i++){
1669 if( aiFlg[i] ){
1670 putValue(out, sqlite3_column_value(pStmt,k));
1671 k++;
1672 }else if( sqlite3_column_int(pStmt,k) ){
1673 putValue(out, sqlite3_column_value(pStmt,k+1));
1674 k += 3;
1675 }else{
1676 putc(0, out);
1677 k += 3;
1678 }
1679 }
1680 for(k=1, i=0; i<nCol; i++){
1681 if( aiFlg[i] ){
1682 putc(0, out);
1683 k++;
1684 }else if( sqlite3_column_int(pStmt,k) ){
1685 putValue(out, sqlite3_column_value(pStmt,k+2));
1686 k += 3;
1687 }else{
1688 putc(0, out);
1689 k += 3;
1690 }
1691 }
1692 break;
1693 }
1694 case SQLITE_INSERT: {
1695 for(k=1, i=0; i<nCol; i++){
1696 if( aiFlg[i] ){
1697 putValue(out, sqlite3_column_value(pStmt,k));
1698 k++;
1699 }else{
1700 putValue(out, sqlite3_column_value(pStmt,k+2));
1701 k += 3;
1702 }
1703 }
1704 break;
1705 }
1706 case SQLITE_DELETE: {
1707 for(k=1, i=0; i<nCol; i++){
1708 if( aiFlg[i] ){
1709 putValue(out, sqlite3_column_value(pStmt,k));
1710 k++;
1711 }else{
1712 putValue(out, sqlite3_column_value(pStmt,k+1));
1713 k += 3;
1714 }
1715 }
1716 break;
drh697e5db2015-04-11 12:07:40 +00001717 }
1718 }
1719 }
1720 sqlite3_finalize(pStmt);
drh83e63dc2015-04-10 19:41:18 +00001721
1722end_changeset_one_table:
1723 while( nCol>0 ) sqlite3_free(azCol[--nCol]);
1724 sqlite3_free(azCol);
1725 sqlite3_free(aiPk);
1726 sqlite3_free(zId);
1727}
1728
1729/*
drhd62c0f42015-04-09 13:34:29 +00001730** Print sketchy documentation for this utility program
1731*/
1732static void showHelp(void){
1733 printf("Usage: %s [options] DB1 DB2\n", g.zArgv0);
1734 printf(
1735"Output SQL text that would transform DB1 into DB2.\n"
1736"Options:\n"
drh83e63dc2015-04-10 19:41:18 +00001737" --changeset FILE Write a CHANGESET into FILE\n"
drh9a9219f2015-05-04 13:25:56 +00001738" -L|--lib LIBRARY Load an SQLite extension library\n"
drha37591c2015-04-09 18:14:03 +00001739" --primarykey Use schema-defined PRIMARY KEYs\n"
dan99461852015-07-30 20:26:16 +00001740" --rbu Output SQL to create/populate RBU table(s)\n"
drhd62c0f42015-04-09 13:34:29 +00001741" --schema Show only differences in the schema\n"
drh8a1cd762015-04-14 19:01:08 +00001742" --summary Show only a summary of the differences\n"
drhd62c0f42015-04-09 13:34:29 +00001743" --table TAB Show only differences in table TAB\n"
1744 );
1745}
1746
1747int main(int argc, char **argv){
1748 const char *zDb1 = 0;
1749 const char *zDb2 = 0;
1750 int i;
1751 int rc;
1752 char *zErrMsg = 0;
1753 char *zSql;
1754 sqlite3_stmt *pStmt;
1755 char *zTab = 0;
drh8a1cd762015-04-14 19:01:08 +00001756 FILE *out = stdout;
1757 void (*xDiff)(const char*,FILE*) = diff_one_table;
drh9a9219f2015-05-04 13:25:56 +00001758 int nExt = 0;
drh33aa4db2015-05-04 15:04:47 +00001759 char **azExt = 0;
drhd62c0f42015-04-09 13:34:29 +00001760
1761 g.zArgv0 = argv[0];
drhaa62e482015-05-12 00:46:40 +00001762 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
drhd62c0f42015-04-09 13:34:29 +00001763 for(i=1; i<argc; i++){
1764 const char *z = argv[i];
1765 if( z[0]=='-' ){
1766 z++;
1767 if( z[0]=='-' ) z++;
drh83e63dc2015-04-10 19:41:18 +00001768 if( strcmp(z,"changeset")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001769 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drh83e63dc2015-04-10 19:41:18 +00001770 out = fopen(argv[++i], "wb");
1771 if( out==0 ) cmdlineError("cannot open: %s", argv[i]);
drh8a1cd762015-04-14 19:01:08 +00001772 xDiff = changeset_one_table;
drh83e63dc2015-04-10 19:41:18 +00001773 }else
drhd62c0f42015-04-09 13:34:29 +00001774 if( strcmp(z,"debug")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001775 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drhd62c0f42015-04-09 13:34:29 +00001776 g.fDebug = strtol(argv[++i], 0, 0);
1777 }else
1778 if( strcmp(z,"help")==0 ){
1779 showHelp();
1780 return 0;
1781 }else
drh6582ae52015-05-12 12:24:50 +00001782#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh9a9219f2015-05-04 13:25:56 +00001783 if( strcmp(z,"lib")==0 || strcmp(z,"L")==0 ){
1784 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
1785 azExt = realloc(azExt, sizeof(azExt[0])*(nExt+1));
1786 if( azExt==0 ) cmdlineError("out of memory");
1787 azExt[nExt++] = argv[++i];
1788 }else
drh6582ae52015-05-12 12:24:50 +00001789#endif
drha37591c2015-04-09 18:14:03 +00001790 if( strcmp(z,"primarykey")==0 ){
1791 g.bSchemaPK = 1;
1792 }else
dan99461852015-07-30 20:26:16 +00001793 if( strcmp(z,"rbu")==0 ){
1794 xDiff = rbudiff_one_table;
1795 }else
drhd62c0f42015-04-09 13:34:29 +00001796 if( strcmp(z,"schema")==0 ){
1797 g.bSchemaOnly = 1;
1798 }else
drh8a1cd762015-04-14 19:01:08 +00001799 if( strcmp(z,"summary")==0 ){
1800 xDiff = summarize_one_table;
1801 }else
drhd62c0f42015-04-09 13:34:29 +00001802 if( strcmp(z,"table")==0 ){
drh9a9219f2015-05-04 13:25:56 +00001803 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
drhd62c0f42015-04-09 13:34:29 +00001804 zTab = argv[++i];
1805 }else
1806 {
1807 cmdlineError("unknown option: %s", argv[i]);
1808 }
1809 }else if( zDb1==0 ){
1810 zDb1 = argv[i];
1811 }else if( zDb2==0 ){
1812 zDb2 = argv[i];
1813 }else{
1814 cmdlineError("unknown argument: %s", argv[i]);
1815 }
1816 }
1817 if( zDb2==0 ){
1818 cmdlineError("two database arguments required");
1819 }
1820 rc = sqlite3_open(zDb1, &g.db);
1821 if( rc ){
1822 cmdlineError("cannot open database file \"%s\"", zDb1);
1823 }
1824 rc = sqlite3_exec(g.db, "SELECT * FROM sqlite_master", 0, 0, &zErrMsg);
1825 if( rc || zErrMsg ){
1826 cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb1);
1827 }
drh6582ae52015-05-12 12:24:50 +00001828#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh9a9219f2015-05-04 13:25:56 +00001829 sqlite3_enable_load_extension(g.db, 1);
1830 for(i=0; i<nExt; i++){
1831 rc = sqlite3_load_extension(g.db, azExt[i], 0, &zErrMsg);
1832 if( rc || zErrMsg ){
1833 cmdlineError("error loading %s: %s", azExt[i], zErrMsg);
1834 }
1835 }
drh6582ae52015-05-12 12:24:50 +00001836#endif
drh9a9219f2015-05-04 13:25:56 +00001837 free(azExt);
drhd62c0f42015-04-09 13:34:29 +00001838 zSql = sqlite3_mprintf("ATTACH %Q as aux;", zDb2);
1839 rc = sqlite3_exec(g.db, zSql, 0, 0, &zErrMsg);
1840 if( rc || zErrMsg ){
1841 cmdlineError("cannot attach database \"%s\"", zDb2);
1842 }
1843 rc = sqlite3_exec(g.db, "SELECT * FROM aux.sqlite_master", 0, 0, &zErrMsg);
1844 if( rc || zErrMsg ){
1845 cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb2);
1846 }
1847
1848 if( zTab ){
drh8a1cd762015-04-14 19:01:08 +00001849 xDiff(zTab, out);
drhd62c0f42015-04-09 13:34:29 +00001850 }else{
1851 /* Handle tables one by one */
1852 pStmt = db_prepare(
1853 "SELECT name FROM main.sqlite_master\n"
1854 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1855 " UNION\n"
1856 "SELECT name FROM aux.sqlite_master\n"
1857 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1858 " ORDER BY name"
1859 );
1860 while( SQLITE_ROW==sqlite3_step(pStmt) ){
drh8a1cd762015-04-14 19:01:08 +00001861 xDiff((const char*)sqlite3_column_text(pStmt,0), out);
drhd62c0f42015-04-09 13:34:29 +00001862 }
1863 sqlite3_finalize(pStmt);
1864 }
1865
1866 /* TBD: Handle trigger differences */
1867 /* TBD: Handle view differences */
1868 sqlite3_close(g.db);
1869 return 0;
1870}