interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / tool / sqldiff.c

2157 lines · 70228 bytes Raw Blame History
1/*
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**
13** This is a utility program that computes the differences in content
14** between two SQLite databases.
15**
16** To compile, simply link against SQLite. (Windows builds must also link
17** against ext/misc/sqlite3_stdio.c.)
18**
19** See the showHelp() routine below for a brief description of how to
20** run the utility.
21*/
22#include <stdio.h>
23#include <stdlib.h>
24#include <stdarg.h>
25#include <ctype.h>
26#include <string.h>
27#include <assert.h>
28#include "sqlite3.h"
29#include "sqlite3_stdio.h"
30
31typedef sqlite3_int64 i64;
32typedef sqlite3_uint64 u64;
33
34/*
35** All global variables are gathered into the "g" singleton.
36*/
37struct GlobalVars {
38 const char *zArgv0; /* Name of program */
39 int bSchemaOnly; /* Only show schema differences */
40 int bSchemaPK; /* Use the schema-defined PK, not the true PK */
41 int bHandleVtab; /* Handle fts3, fts4, fts5 and rtree vtabs */
42 unsigned fDebug; /* Debug flags */
43 int bUnsafe; /* Try to work through corrupt databases */
44 int bSchemaCompare; /* Doing single-table sqlite_schema compare */
45 sqlite3 *db; /* The database connection */
46} g;
47
48/*
49** Allowed values for g.fDebug
50*/
51#define DEBUG_COLUMN_NAMES 0x000001
52#define DEBUG_DIFF_SQL 0x000002
53
54/*
55** Clear and free an sqlite3_str object
56*/
57static void strFree(sqlite3_str *pStr){
58 sqlite3_free(sqlite3_str_finish(pStr));
59}
60
61/*
62** Print an error resulting from faulting command-line arguments and
63** abort the program.
64*/
65static void cmdlineError(const char *zFormat, ...){
66 sqlite3_str *pOut = sqlite3_str_new(0);
67 va_list ap;
68 va_start(ap, zFormat);
69 sqlite3_str_vappendf(pOut, zFormat, ap);
70 va_end(ap);
71 sqlite3_fprintf(stderr, "%s: %s\n", g.zArgv0, sqlite3_str_value(pOut));
72 strFree(pOut);
73 sqlite3_fprintf(stderr, "\"%s --help\" for more help\n", g.zArgv0);
74 exit(1);
75}
76
77/*
78** Print an error message for an error that occurs at runtime, then
79** abort the program.
80*/
81static void runtimeError(const char *zFormat, ...){
82 sqlite3_str *pOut = sqlite3_str_new(0);
83 va_list ap;
84 va_start(ap, zFormat);
85 sqlite3_str_vappendf(pOut, zFormat, ap);
86 va_end(ap);
87 sqlite3_fprintf(stderr, "%s: %s\n", g.zArgv0, sqlite3_str_value(pOut));
88 strFree(pOut);
89 exit(1);
90}
91
92
93/* Safely quote an SQL identifier. Use the minimum amount of transformation
94** necessary to allow the string to be used with %s.
95**
96** Space to hold the returned string is obtained from sqlite3_malloc(). The
97** caller is responsible for ensuring this space is freed when no longer
98** needed.
99*/
100static char *safeId(const char *zId){
101 int i, x;
102 char c;
103 if( zId[0]==0 ) return sqlite3_mprintf("\"\"");
104 for(i=x=0; (c = zId[i])!=0; i++){
105 if( !isalpha(c) && c!='_' ){
106 if( i>0 && isdigit(c) ){
107 x++;
108 }else{
109 return sqlite3_mprintf("\"%w\"", zId);
110 }
111 }
112 }
113 if( x || !sqlite3_keyword_check(zId,i) ){
114 return sqlite3_mprintf("%s", zId);
115 }
116 return sqlite3_mprintf("\"%w\"", zId);
117}
118
119/*
120** Prepare a new SQL statement. Print an error and abort if anything
121** goes wrong.
122*/
123static sqlite3_stmt *db_vprepare(const char *zFormat, va_list ap){
124 char *zSql;
125 int rc;
126 sqlite3_stmt *pStmt;
127
128 zSql = sqlite3_vmprintf(zFormat, ap);
129 if( zSql==0 ) runtimeError("out of memory");
130 rc = sqlite3_prepare_v2(g.db, zSql, -1, &pStmt, 0);
131 if( rc ){
132 runtimeError("SQL statement error: %s\n\"%s\"", sqlite3_errmsg(g.db),
133 zSql);
134 }
135 sqlite3_free(zSql);
136 return pStmt;
137}
138static sqlite3_stmt *db_prepare(const char *zFormat, ...){
139 va_list ap;
140 sqlite3_stmt *pStmt;
141 va_start(ap, zFormat);
142 pStmt = db_vprepare(zFormat, ap);
143 va_end(ap);
144 return pStmt;
145}
146
147/*
148** Free a list of strings
149*/
150static void namelistFree(char **az){
151 if( az ){
152 int i;
153 for(i=0; az[i]; i++) sqlite3_free(az[i]);
154 sqlite3_free(az);
155 }
156}
157
158/*
159** Return a list of column names [a] for the table zDb.zTab. Space to
160** hold the list is obtained from sqlite3_malloc() and should released
161** using namelistFree() when no longer needed.
162**
163** Primary key columns are listed first, followed by data columns.
164** The number of columns in the primary key is returned in *pnPkey.
165**
166** Normally [a], the "primary key" in the previous sentence is the true
167** primary key - the rowid or INTEGER PRIMARY KEY for ordinary tables
168** or the declared PRIMARY KEY for WITHOUT ROWID tables. However, if
169** the g.bSchemaPK flag is set, then the schema-defined PRIMARY KEY is
170** used in all cases. In that case, entries that have NULL values in
171** any of their primary key fields will be excluded from the analysis.
172**
173** If the primary key for a table is the rowid but rowid is inaccessible,
174** then this routine returns a NULL pointer.
175**
176** [a. If the lone, named table is "sqlite_schema", "rootpage" column is
177** omitted and the "type" and "name" columns are made to be the PK.]
178**
179** Examples:
180** CREATE TABLE t1(a INT UNIQUE, b INTEGER, c TEXT, PRIMARY KEY(c));
181** *pnPKey = 1;
182** az = { "rowid", "a", "b", "c", 0 } // Normal case
183** az = { "c", "a", "b", 0 } // g.bSchemaPK==1
184**
185** CREATE TABLE t2(a INT UNIQUE, b INTEGER, c TEXT, PRIMARY KEY(b));
186** *pnPKey = 1;
187** az = { "b", "a", "c", 0 }
188**
189** CREATE TABLE t3(x,y,z,PRIMARY KEY(y,z));
190** *pnPKey = 1 // Normal case
191** az = { "rowid", "x", "y", "z", 0 } // Normal case
192** *pnPKey = 2 // g.bSchemaPK==1
193** az = { "y", "x", "z", 0 } // g.bSchemaPK==1
194**
195** CREATE TABLE t4(x,y,z,PRIMARY KEY(y,z)) WITHOUT ROWID;
196** *pnPKey = 2
197** az = { "y", "z", "x", 0 }
198**
199** CREATE TABLE t5(rowid,_rowid_,oid);
200** az = 0 // The rowid is not accessible
201*/
202static char **columnNames(
203 const char *zDb, /* Database ("main" or "aux") to query */
204 const char *zTab, /* Name of table to return details of */
205 int *pnPKey, /* OUT: Number of PK columns */
206 int *pbRowid /* OUT: True if PK is an implicit rowid */
207){
208 char **az = 0; /* List of column names to be returned */
209 i64 naz = 0; /* Number of entries in az[] */
210 sqlite3_stmt *pStmt; /* SQL statement being run */
211 char *zPkIdxName = 0; /* Name of the PRIMARY KEY index */
212 int truePk = 0; /* PRAGMA table_info identifies the PK to use */
213 i64 nPK = 0; /* Number of PRIMARY KEY columns */
214 i64 i, j; /* Loop counters */
215 int iPKey = 0; /* Primary key index */
216
217 if( g.bSchemaPK==0 ){
218 /* Normal case: Figure out what the true primary key is for the table.
219 ** * For WITHOUT ROWID tables, the true primary key is the same as
220 ** the schema PRIMARY KEY, which is guaranteed to be present.
221 ** * For rowid tables with an INTEGER PRIMARY KEY, the true primary
222 ** key is the INTEGER PRIMARY KEY.
223 ** * For all other rowid tables, the rowid is the true primary key.
224 */
225 pStmt = db_prepare("PRAGMA %s.index_list=%Q", zDb, zTab);
226 while( SQLITE_ROW==sqlite3_step(pStmt) ){
227 if( sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,3),"pk")==0 ){
228 zPkIdxName = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
229 break;
230 }
231 }
232 sqlite3_finalize(pStmt);
233 if( zPkIdxName ){
234 int nKey = 0;
235 int nCol = 0;
236 truePk = 0;
237 pStmt = db_prepare("PRAGMA %s.index_xinfo=%Q", zDb, zPkIdxName);
238 while( SQLITE_ROW==sqlite3_step(pStmt) ){
239 nCol++;
240 if( sqlite3_column_int(pStmt,5) ){ nKey++; continue; }
241 if( sqlite3_column_int(pStmt,1)>=0 ) truePk = 1;
242 }
243 if( nCol==nKey ) truePk = 1;
244 if( truePk ){
245 nPK = nKey;
246 }else{
247 nPK = 1;
248 }
249 sqlite3_finalize(pStmt);
250 sqlite3_free(zPkIdxName);
251 }else{
252 truePk = 1;
253 nPK = 1;
254 }
255 pStmt = db_prepare("PRAGMA %s.table_info=%Q", zDb, zTab);
256 }else{
257 /* The g.bSchemaPK==1 case: Use whatever primary key is declared
258 ** in the schema. The "rowid" will still be used as the primary key
259 ** if the table definition does not contain a PRIMARY KEY.
260 */
261 nPK = 0;
262 pStmt = db_prepare("PRAGMA %s.table_info=%Q", zDb, zTab);
263 while( SQLITE_ROW==sqlite3_step(pStmt) ){
264 if( sqlite3_column_int(pStmt,5)>0 ) nPK++;
265 }
266 sqlite3_reset(pStmt);
267 if( nPK==0 ) nPK = 1;
268 truePk = 1;
269 }
270 if( g.bSchemaCompare ){
271 assert( sqlite3_stricmp(zTab,"sqlite_schema")==0
272 || sqlite3_stricmp(zTab,"sqlite_master")==0 );
273 /* For sqlite_schema, will use type and name as the PK. */
274 nPK = 2;
275 truePk = 0;
276 }
277 *pnPKey = nPK;
278 naz = nPK;
279 az = sqlite3_malloc64( sizeof(char*)*(nPK+1) );
280 if( az==0 ) runtimeError("out of memory");
281 memset(az, 0, sizeof(char*)*(nPK+1));
282 if( g.bSchemaCompare ){
283 az[0] = sqlite3_mprintf("%s", "type");
284 az[1] = sqlite3_mprintf("%s", "name");
285 }
286 while( SQLITE_ROW==sqlite3_step(pStmt) ){
287 char * sid = safeId((char*)sqlite3_column_text(pStmt,1));
288 if( truePk && sqlite3_column_int(pStmt,5)>0 ){
289 assert( iPKey<naz );
290 az[iPKey++] = sid;
291 }else{
292 if( !g.bSchemaCompare
293 || !(strcmp(sid,"rootpage")==0
294 ||strcmp(sid,"name")==0
295 ||strcmp(sid,"type")==0)){
296 az = sqlite3_realloc64(az, sizeof(char*)*(naz+2) );
297 if( az==0 ) runtimeError("out of memory");
298 az[naz++] = sid;
299 }
300 }
301 }
302 sqlite3_finalize(pStmt);
303 if( az ) az[naz] = 0;
304
305 /* If it is non-NULL, set *pbRowid to indicate whether or not the PK of
306 ** this table is an implicit rowid (*pbRowid==1) or not (*pbRowid==0). */
307 if( pbRowid ) *pbRowid = (az[0]==0);
308
309 /* If this table has an implicit rowid for a PK, figure out how to refer
310 ** to it. There are usually three options - "rowid", "_rowid_" and "oid".
311 ** Any of these will work, unless the table has an explicit column of the
312 ** same name or the sqlite_schema tables are to be compared. In the latter
313 ** case, pretend that the "true" primary key is the name column, which
314 ** avoids extraneous diffs against the schemas due to rowid variance. */
315 if( az[0]==0 ){
316 const char *azRowid[] = { "rowid", "_rowid_", "oid" };
317 for(i=0; i<sizeof(azRowid)/sizeof(azRowid[0]); i++){
318 for(j=1; j<naz; j++){
319 if( sqlite3_stricmp(az[j], azRowid[i])==0 ) break;
320 }
321 if( j>=naz ){
322 az[0] = sqlite3_mprintf("%s", azRowid[i]);
323 break;
324 }
325 }
326 if( az[0]==0 ){
327 for(i=1; i<naz; i++) sqlite3_free(az[i]);
328 sqlite3_free(az);
329 az = 0;
330 }
331 }
332 return az;
333}
334
335/*
336** Print the sqlite3_value X as an SQL literal.
337*/
338static void printQuoted(FILE *out, sqlite3_value *X){
339 switch( sqlite3_value_type(X) ){
340 case SQLITE_FLOAT: {
341 double r1;
342 char zBuf[50];
343 r1 = sqlite3_value_double(X);
344 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!0.17g", r1);
345 sqlite3_fprintf(out, "%s", zBuf);
346 break;
347 }
348 case SQLITE_INTEGER: {
349 sqlite3_fprintf(out, "%lld", sqlite3_value_int64(X));
350 break;
351 }
352 case SQLITE_BLOB: {
353 const unsigned char *zBlob = sqlite3_value_blob(X);
354 int nBlob = sqlite3_value_bytes(X);
355 if( zBlob ){
356 int i;
357 sqlite3_fprintf(out, "x'");
358 for(i=0; i<nBlob; i++){
359 sqlite3_fprintf(out, "%02x", zBlob[i]);
360 }
361 sqlite3_fprintf(out, "'");
362 }else{
363 /* Could be an OOM, could be a zero-byte blob */
364 sqlite3_fprintf(out, "X''");
365 }
366 break;
367 }
368 case SQLITE_TEXT: {
369 const unsigned char *zArg = sqlite3_value_text(X);
370
371 if( zArg==0 ){
372 sqlite3_fprintf(out, "NULL");
373 }else{
374 int inctl = 0;
375 int i, j;
376 sqlite3_fprintf(out, "'");
377 for(i=j=0; zArg[i]; i++){
378 char c = zArg[i];
379 int ctl = iscntrl((unsigned char)c);
380 if( ctl>inctl ){
381 inctl = ctl;
382 sqlite3_fprintf(out, "%.*s'||X'%02x", i-j, &zArg[j], c);
383 j = i+1;
384 }else if( ctl ){
385 sqlite3_fprintf(out, "%02x", c);
386 j = i+1;
387 }else{
388 if( inctl ){
389 inctl = 0;
390 sqlite3_fprintf(out, "'\n||'");
391 }
392 if( c=='\'' ){
393 sqlite3_fprintf(out, "%.*s'", i-j+1, &zArg[j]);
394 j = i+1;
395 }
396 }
397 }
398 sqlite3_fprintf(out, "%s'", &zArg[j]);
399 }
400 break;
401 }
402 case SQLITE_NULL: {
403 sqlite3_fprintf(out, "NULL");
404 break;
405 }
406 }
407}
408
409/*
410** Output SQL that will recreate the aux.zTab table.
411*/
412static void dump_table(const char *zTab, FILE *out){
413 char *zId = safeId(zTab); /* Name of the table */
414 char **az = 0; /* List of columns */
415 int nPk; /* Number of true primary key columns */
416 int nCol; /* Number of data columns */
417 int i; /* Loop counter */
418 sqlite3_stmt *pStmt; /* SQL statement */
419 const char *zSep; /* Separator string */
420 sqlite3_str *pIns; /* Beginning of the INSERT statement */
421
422 pStmt = db_prepare("SELECT shell_complete_sql(sql) FROM aux.sqlite_schema"
423 " WHERE name=%Q COLLATE nocase", zTab);
424 if( SQLITE_ROW==sqlite3_step(pStmt) ){
425 sqlite3_fprintf(out, "%s;\n", sqlite3_column_text(pStmt,0));
426 }
427 sqlite3_finalize(pStmt);
428 if( !g.bSchemaOnly ){
429 az = columnNames("aux", zTab, &nPk, 0);
430 pIns = sqlite3_str_new(0);
431 if( az==0 ){
432 pStmt = db_prepare("SELECT * FROM aux.%s", zId);
433 sqlite3_str_appendf(pIns,"INSERT INTO %s VALUES", zId);
434 }else{
435 sqlite3_str *pSql = sqlite3_str_new(0);
436 zSep = "SELECT";
437 for(i=0; az[i]; i++){
438 sqlite3_str_appendf(pSql, "%s %s", zSep, az[i]);
439 zSep = ",";
440 }
441 sqlite3_str_appendf(pSql," FROM aux.%s", zId);
442 zSep = " ORDER BY";
443 for(i=1; i<=nPk; i++){
444 sqlite3_str_appendf(pSql, "%s %d", zSep, i);
445 zSep = ",";
446 }
447 pStmt = db_prepare("%s", sqlite3_str_value(pSql));
448 strFree(pSql);
449 sqlite3_str_appendf(pIns, "INSERT INTO %s", zId);
450 zSep = "(";
451 for(i=0; az[i]; i++){
452 sqlite3_str_appendf(pIns, "%s%s", zSep, az[i]);
453 zSep = ",";
454 }
455 sqlite3_str_appendf(pIns,") VALUES");
456 namelistFree(az);
457 }
458 nCol = sqlite3_column_count(pStmt);
459 while( SQLITE_ROW==sqlite3_step(pStmt) ){
460 sqlite3_fprintf(out, "%s",sqlite3_str_value(pIns));
461 zSep = "(";
462 for(i=0; i<nCol; i++){
463 sqlite3_fprintf(out, "%s",zSep);
464 printQuoted(out, sqlite3_column_value(pStmt,i));
465 zSep = ",";
466 }
467 sqlite3_fprintf(out, ");\n");
468 }
469 sqlite3_finalize(pStmt);
470 strFree(pIns);
471 } /* endif !g.bSchemaOnly */
472 pStmt = db_prepare("SELECT shell_complete_sql(sql) FROM aux.sqlite_schema"
473 " WHERE type='index' AND tbl_name=%Q COLLATE nocase"
474 " AND sql IS NOT NULL",
475 zTab);
476 while( SQLITE_ROW==sqlite3_step(pStmt) ){
477 sqlite3_fprintf(out, "%s;\n", sqlite3_column_text(pStmt,0));
478 }
479 sqlite3_finalize(pStmt);
480 sqlite3_free(zId);
481}
482
483
484/*
485** Compute all differences for a single table, except if the
486** table name is sqlite_schema, ignore the rootpage column.
487*/
488static void diff_one_table(const char *zTab, FILE *out){
489 char *zId = safeId(zTab); /* Name of table (translated for us in SQL) */
490 char **az = 0; /* Columns in main */
491 char **az2 = 0; /* Columns in aux */
492 int nPk; /* Primary key columns in main */
493 int nPk2; /* Primary key columns in aux */
494 int n = 0; /* Number of columns in main */
495 int n2; /* Number of columns in aux */
496 int nQ; /* Number of output columns in the diff query */
497 int i; /* Loop counter */
498 const char *zSep; /* Separator string */
499 sqlite3_str *pSql; /* Comparison query */
500 sqlite3_stmt *pStmt; /* Query statement to do the diff */
501 const char *zLead = /* Becomes line-comment for sqlite_schema */
502 (g.bSchemaCompare)? "-- " : "";
503
504 pSql = sqlite3_str_new(0);
505 if( g.fDebug==DEBUG_COLUMN_NAMES ){
506 /* Simply run columnNames() on all tables of the origin
507 ** database and show the results. This is used for testing
508 ** and debugging of the columnNames() function.
509 */
510 az = columnNames("aux",zTab, &nPk, 0);
511 if( az==0 ){
512 sqlite3_fprintf(stdout, "Rowid not accessible for %s\n", zId);
513 }else{
514 sqlite3_fprintf(stdout, "%s:", zId);
515 for(i=0; az[i]; i++){
516 sqlite3_fprintf(stdout, " %s", az[i]);
517 if( i+1==nPk ) sqlite3_fprintf(stdout, " *");
518 }
519 sqlite3_fprintf(stdout, "\n");
520 }
521 goto end_diff_one_table;
522 }
523
524 if( sqlite3_table_column_metadata(g.db,"aux",zTab,0,0,0,0,0,0) ){
525 if( !sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
526 /* Table missing from second database. */
527 if( g.bSchemaCompare )
528 sqlite3_fprintf(out, "-- 2nd DB has no %s table\n", zTab);
529 else
530 sqlite3_fprintf(out, "DROP TABLE %s;\n", zId);
531 }
532 goto end_diff_one_table;
533 }
534
535 if( sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
536 /* Table missing from source */
537 if( g.bSchemaCompare ){
538 sqlite3_fprintf(out, "-- 1st DB has no %s table\n", zTab);
539 }else{
540 dump_table(zTab, out);
541 }
542 goto end_diff_one_table;
543 }
544
545 az = columnNames("main", zTab, &nPk, 0);
546 az2 = columnNames("aux", zTab, &nPk2, 0);
547 if( az && az2 ){
548 for(n=0; az[n] && az2[n]; n++){
549 if( sqlite3_stricmp(az[n],az2[n])!=0 ) break;
550 }
551 }
552 if( az==0
553 || az2==0
554 || nPk!=nPk2
555 || az[n]
556 ){
557 /* Schema mismatch */
558 sqlite3_fprintf(out, "%sDROP TABLE %s; -- due to schema mismatch\n", zLead, zId);
559 dump_table(zTab, out);
560 goto end_diff_one_table;
561 }
562
563 /* Build the comparison query */
564 for(n2=n; az2[n2]; n2++){
565 char *zNTab = safeId(az2[n2]);
566 sqlite3_fprintf(out, "ALTER TABLE %s ADD COLUMN %s;\n", zId, zNTab);
567 sqlite3_free(zNTab);
568 }
569 nQ = nPk2+1+2*(n2-nPk2);
570 if( n2>nPk2 ){
571 zSep = "SELECT ";
572 for(i=0; i<nPk; i++){
573 sqlite3_str_appendf(pSql, "%sB.%s", zSep, az[i]);
574 zSep = ", ";
575 }
576 sqlite3_str_appendf(pSql, ", 1 /* changed row */");
577 while( az[i] ){
578 sqlite3_str_appendf(pSql, ", A.%s IS NOT B.%s, B.%s",
579 az[i], az2[i], az2[i]);
580 i++;
581 }
582 while( az2[i] ){
583 sqlite3_str_appendf(pSql, ", B.%s IS NOT NULL, B.%s",
584 az2[i], az2[i]);
585 i++;
586 }
587 sqlite3_str_appendf(pSql, "\n FROM main.%s A, aux.%s B\n", zId, zId);
588 zSep = " WHERE";
589 for(i=0; i<nPk; i++){
590 sqlite3_str_appendf(pSql, "%s A.%s=B.%s", zSep, az[i], az[i]);
591 zSep = " AND";
592 }
593 zSep = "\n AND (";
594 while( az[i] ){
595 sqlite3_str_appendf(pSql, "%sA.%s IS NOT B.%s%s\n",
596 zSep, az[i], az2[i], az2[i+1]==0 ? ")" : "");
597 zSep = " OR ";
598 i++;
599 }
600 while( az2[i] ){
601 sqlite3_str_appendf(pSql, "%sB.%s IS NOT NULL%s\n",
602 zSep, az2[i], az2[i+1]==0 ? ")" : "");
603 zSep = " OR ";
604 i++;
605 }
606 sqlite3_str_appendf(pSql, " UNION ALL\n");
607 }
608 zSep = "SELECT ";
609 for(i=0; i<nPk; i++){
610 sqlite3_str_appendf(pSql, "%sA.%s", zSep, az[i]);
611 zSep = ", ";
612 }
613 sqlite3_str_appendf(pSql, ", 2 /* deleted row */");
614 while( az2[i] ){
615 sqlite3_str_appendf(pSql, ", NULL, NULL");
616 i++;
617 }
618 sqlite3_str_appendf(pSql, "\n FROM main.%s A\n", zId);
619 sqlite3_str_appendf(pSql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B\n", zId);
620 zSep = " WHERE";
621 for(i=0; i<nPk; i++){
622 sqlite3_str_appendf(pSql, "%s A.%s=B.%s", zSep, az[i], az[i]);
623 zSep = " AND";
624 }
625 sqlite3_str_appendf(pSql, ")\n");
626 zSep = " UNION ALL\nSELECT ";
627 for(i=0; i<nPk; i++){
628 sqlite3_str_appendf(pSql, "%sB.%s", zSep, az[i]);
629 zSep = ", ";
630 }
631 sqlite3_str_appendf(pSql, ", 3 /* inserted row */");
632 while( az2[i] ){
633 sqlite3_str_appendf(pSql, ", 1, B.%s", az2[i]);
634 i++;
635 }
636 sqlite3_str_appendf(pSql, "\n FROM aux.%s B\n", zId);
637 sqlite3_str_appendf(pSql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A\n", zId);
638 zSep = " WHERE";
639 for(i=0; i<nPk; i++){
640 sqlite3_str_appendf(pSql, "%s A.%s=B.%s", zSep, az[i], az[i]);
641 zSep = " AND";
642 }
643 sqlite3_str_appendf(pSql, ")\n ORDER BY");
644 zSep = " ";
645 for(i=1; i<=nPk; i++){
646 sqlite3_str_appendf(pSql, "%s%d", zSep, i);
647 zSep = ", ";
648 }
649 sqlite3_str_appendf(pSql, ";\n");
650
651 if( g.fDebug & DEBUG_DIFF_SQL ){
652 printf("SQL for %s:\n%s\n", zId, sqlite3_str_value(pSql));
653 goto end_diff_one_table;
654 }
655
656 /* Drop indexes that are missing in the destination */
657 pStmt = db_prepare(
658 "SELECT name FROM main.sqlite_schema"
659 " WHERE type='index' AND tbl_name=%Q COLLATE nocase"
660 " AND sql IS NOT NULL"
661 " AND sql NOT IN (SELECT sql FROM aux.sqlite_schema"
662 " WHERE type='index' AND tbl_name=%Q COLLATE nocase"
663 " AND sql IS NOT NULL)",
664 zTab, zTab);
665 while( SQLITE_ROW==sqlite3_step(pStmt) ){
666 char *z = safeId((const char*)sqlite3_column_text(pStmt,0));
667 sqlite3_fprintf(out, "DROP INDEX %s;\n", z);
668 sqlite3_free(z);
669 }
670 sqlite3_finalize(pStmt);
671
672 /* Run the query and output differences */
673 if( !g.bSchemaOnly ){
674 pStmt = db_prepare("%s", sqlite3_str_value(pSql));
675 while( SQLITE_ROW==sqlite3_step(pStmt) ){
676 int iType = sqlite3_column_int(pStmt, nPk);
677 if( iType==1 || iType==2 ){
678 if( iType==1 ){ /* Change the content of a row */
679 sqlite3_fprintf(out, "%sUPDATE %s", zLead, zId);
680 zSep = " SET";
681 for(i=nPk+1; i<nQ; i+=2){
682 if( sqlite3_column_int(pStmt,i)==0 ) continue;
683 sqlite3_fprintf(out, "%s %s=", zSep, az2[(i+nPk-1)/2]);
684 zSep = ",";
685 printQuoted(out, sqlite3_column_value(pStmt,i+1));
686 }
687 }else{ /* Delete a row */
688 sqlite3_fprintf(out, "%sDELETE FROM %s", zLead, zId);
689 }
690 zSep = " WHERE";
691 for(i=0; i<nPk; i++){
692 sqlite3_fprintf(out, "%s %s=", zSep, az2[i]);
693 printQuoted(out, sqlite3_column_value(pStmt,i));
694 zSep = " AND";
695 }
696 sqlite3_fprintf(out, ";\n");
697 }else{ /* Insert a row */
698 sqlite3_fprintf(out, "%sINSERT INTO %s(%s", zLead, zId, az2[0]);
699 for(i=1; az2[i]; i++) sqlite3_fprintf(out, ",%s", az2[i]);
700 sqlite3_fprintf(out, ") VALUES");
701 zSep = "(";
702 for(i=0; i<nPk2; i++){
703 sqlite3_fprintf(out, "%s", zSep);
704 zSep = ",";
705 printQuoted(out, sqlite3_column_value(pStmt,i));
706 }
707 for(i=nPk2+2; i<nQ; i+=2){
708 sqlite3_fprintf(out, ",");
709 printQuoted(out, sqlite3_column_value(pStmt,i));
710 }
711 sqlite3_fprintf(out, ");\n");
712 }
713 }
714 sqlite3_finalize(pStmt);
715 } /* endif !g.bSchemaOnly */
716
717 /* Create indexes that are missing in the source */
718 pStmt = db_prepare(
719 "SELECT shell_complete_sql(sql) FROM aux.sqlite_schema"
720 " WHERE type='index' AND tbl_name=%Q COLLATE nocase"
721 " AND sql IS NOT NULL"
722 " AND sql NOT IN (SELECT sql FROM main.sqlite_schema"
723 " WHERE type='index' AND tbl_name=%Q COLLATE nocase"
724 " AND sql IS NOT NULL)",
725 zTab, zTab);
726 while( SQLITE_ROW==sqlite3_step(pStmt) ){
727 sqlite3_fprintf(out, "%s;\n", sqlite3_column_text(pStmt,0));
728 }
729 sqlite3_finalize(pStmt);
730
731end_diff_one_table:
732 strFree(pSql);
733 sqlite3_free(zId);
734 namelistFree(az);
735 namelistFree(az2);
736 return;
737}
738
739/*
740** Check that table zTab exists and has the same schema in both the "main"
741** and "aux" databases currently opened by the global db handle. If they
742** do not, output an error message on stderr and exit(1). Otherwise, if
743** the schemas do match, return control to the caller.
744*/
745static void checkSchemasMatch(const char *zTab){
746 sqlite3_stmt *pStmt = db_prepare(
747 "SELECT A.sql=B.sql FROM main.sqlite_schema A, aux.sqlite_schema B"
748 " WHERE A.name=%Q COLLATE nocase"
749 " AND B.name=%Q COLLATE nocase", zTab, zTab
750 );
751 if( SQLITE_ROW==sqlite3_step(pStmt) ){
752 if( sqlite3_column_int(pStmt,0)==0 ){
753 runtimeError("schema changes for table %s", safeId(zTab));
754 }
755 }else{
756 runtimeError("table %s missing from one or both databases", safeId(zTab));
757 }
758 sqlite3_finalize(pStmt);
759}
760
761/**************************************************************************
762** The following code is copied from fossil. It is used to generate the
763** fossil delta blobs sometimes used in RBU update records.
764*/
765
766typedef unsigned short u16;
767typedef unsigned int u32;
768typedef unsigned char u8;
769
770/*
771** The width of a hash window in bytes. The algorithm only works if this
772** is a power of 2.
773*/
774#define NHASH 16
775
776/*
777** The current state of the rolling hash.
778**
779** z[] holds the values that have been hashed. z[] is a circular buffer.
780** z[i] is the first entry and z[(i+NHASH-1)%NHASH] is the last entry of
781** the window.
782**
783** Hash.a is the sum of all elements of hash.z[]. Hash.b is a weighted
784** sum. Hash.b is z[i]*NHASH + z[i+1]*(NHASH-1) + ... + z[i+NHASH-1]*1.
785** (Each index for z[] should be module NHASH, of course. The %NHASH operator
786** is omitted in the prior expression for brevity.)
787*/
788typedef struct hash hash;
789struct hash {
790 u16 a, b; /* Hash values */
791 u16 i; /* Start of the hash window */
792 char z[NHASH]; /* The values that have been hashed */
793};
794
795/*
796** Initialize the rolling hash using the first NHASH characters of z[]
797*/
798static void hash_init(hash *pHash, const char *z){
799 u16 a, b, i;
800 a = b = 0;
801 for(i=0; i<NHASH; i++){
802 a += z[i];
803 b += (NHASH-i)*z[i];
804 pHash->z[i] = z[i];
805 }
806 pHash->a = a & 0xffff;
807 pHash->b = b & 0xffff;
808 pHash->i = 0;
809}
810
811/*
812** Advance the rolling hash by a single character "c"
813*/
814static void hash_next(hash *pHash, int c){
815 u16 old = pHash->z[pHash->i];
816 pHash->z[pHash->i] = (char)c;
817 pHash->i = (pHash->i+1)&(NHASH-1);
818 pHash->a = pHash->a - old + (char)c;
819 pHash->b = pHash->b - NHASH*old + pHash->a;
820}
821
822/*
823** Return a 32-bit hash value
824*/
825static u32 hash_32bit(hash *pHash){
826 return (pHash->a & 0xffff) | (((u32)(pHash->b & 0xffff))<<16);
827}
828
829/*
830** Write an base-64 integer into the given buffer.
831*/
832static void putInt(unsigned int v, char **pz){
833 static const char zDigits[] =
834 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~";
835 /* 123456789 123456789 123456789 123456789 123456789 123456789 123 */
836 int i, j;
837 char zBuf[20];
838 if( v==0 ){
839 *(*pz)++ = '0';
840 return;
841 }
842 for(i=0; v>0; i++, v>>=6){
843 zBuf[i] = zDigits[v&0x3f];
844 }
845 for(j=i-1; j>=0; j--){
846 *(*pz)++ = zBuf[j];
847 }
848}
849
850/*
851** Return the number digits in the base-64 representation of a positive integer
852*/
853static int digit_count(int v){
854 unsigned int i, x;
855 for(i=1, x=64; (unsigned int)v>=x; i++, x <<= 6){}
856 return i;
857}
858
859/*
860** Compute a 32-bit checksum on the N-byte buffer. Return the result.
861*/
862static unsigned int checksum(const char *zIn, size_t N){
863 const unsigned char *z = (const unsigned char *)zIn;
864 unsigned sum0 = 0;
865 unsigned sum1 = 0;
866 unsigned sum2 = 0;
867 unsigned sum3 = 0;
868 while(N >= 16){
869 sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
870 sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
871 sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
872 sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
873 z += 16;
874 N -= 16;
875 }
876 while(N >= 4){
877 sum0 += z[0];
878 sum1 += z[1];
879 sum2 += z[2];
880 sum3 += z[3];
881 z += 4;
882 N -= 4;
883 }
884 sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
885 switch(N){
886 case 3: sum3 += (z[2] << 8);
887 case 2: sum3 += (z[1] << 16);
888 case 1: sum3 += (z[0] << 24);
889 default: ;
890 }
891 return sum3;
892}
893
894/*
895** Create a new delta.
896**
897** The delta is written into a preallocated buffer, zDelta, which
898** should be at least 60 bytes longer than the target file, zOut.
899** The delta string will be NUL-terminated, but it might also contain
900** embedded NUL characters if either the zSrc or zOut files are
901** binary. This function returns the length of the delta string
902** in bytes, excluding the final NUL terminator character. Return 0
903** if an OOM occurs.
904**
905** Output Format:
906**
907** The delta begins with a base64 number followed by a newline. This
908** number is the number of bytes in the TARGET file. Thus, given a
909** delta file z, a program can compute the size of the output file
910** simply by reading the first line and decoding the base-64 number
911** found there. The delta_output_size() routine does exactly this.
912**
913** After the initial size number, the delta consists of a series of
914** literal text segments and commands to copy from the SOURCE file.
915** A copy command looks like this:
916**
917** NNN@MMM,
918**
919** where NNN is the number of bytes to be copied and MMM is the offset
920** into the source file of the first byte (both base-64). If NNN is 0
921** it means copy the rest of the input file. Literal text is like this:
922**
923** NNN:TTTTT
924**
925** where NNN is the number of bytes of text (base-64) and TTTTT is the text.
926**
927** The last term is of the form
928**
929** NNN;
930**
931** In this case, NNN is a 32-bit bigendian checksum of the output file
932** that can be used to verify that the delta applied correctly. All
933** numbers are in base-64.
934**
935** Pure text files generate a pure text delta. Binary files generate a
936** delta that may contain some binary data.
937**
938** Algorithm:
939**
940** The encoder first builds a hash table to help it find matching
941** patterns in the source file. 16-byte chunks of the source file
942** sampled at evenly spaced intervals are used to populate the hash
943** table.
944**
945** Next we begin scanning the target file using a sliding 16-byte
946** window. The hash of the 16-byte window in the target is used to
947** search for a matching section in the source file. When a match
948** is found, a copy command is added to the delta. An effort is
949** made to extend the matching section to regions that come before
950** and after the 16-byte hash window. A copy command is only issued
951** if the result would use less space that just quoting the text
952** literally. Literal text is added to the delta for sections that
953** do not match or which can not be encoded efficiently using copy
954** commands.
955*/
956static int rbuDeltaCreate(
957 const char *zSrc, /* The source or pattern file */
958 unsigned int lenSrc, /* Length of the source file */
959 const char *zOut, /* The target file */
960 unsigned int lenOut, /* Length of the target file */
961 char *zDelta /* Write the delta into this buffer */
962){
963 unsigned int i, base;
964 char *zOrigDelta = zDelta;
965 hash h;
966 i64 nHash; /* Number of hash table entries */
967 int *landmark; /* Primary hash table */
968 int *collide; /* Collision chain */
969 int lastRead = -1; /* Last byte of zSrc read by a COPY command */
970
971 /* Add the target file size to the beginning of the delta
972 */
973 putInt(lenOut, &zDelta);
974 *(zDelta++) = '\n';
975
976 /* If the source file is very small, it means that we have no
977 ** chance of ever doing a copy command. Just output a single
978 ** literal segment for the entire target and exit.
979 */
980 if( lenSrc<=NHASH ){
981 putInt(lenOut, &zDelta);
982 *(zDelta++) = ':';
983 memcpy(zDelta, zOut, lenOut);
984 zDelta += lenOut;
985 putInt(checksum(zOut, lenOut), &zDelta);
986 *(zDelta++) = ';';
987 return (int)(zDelta - zOrigDelta);
988 }
989
990 /* Compute the hash table used to locate matching sections in the
991 ** source file.
992 */
993 nHash = lenSrc/NHASH;
994 collide = sqlite3_malloc64( nHash*2*sizeof(int) );
995 if( collide==0 ) return 0;
996 landmark = &collide[nHash];
997 memset(landmark, -1, nHash*sizeof(int));
998 memset(collide, -1, nHash*sizeof(int));
999 for(i=0; i<lenSrc-NHASH; i+=NHASH){
1000 int hv;
1001 hash_init(&h, &zSrc[i]);
1002 hv = hash_32bit(&h) % nHash;
1003 collide[i/NHASH] = landmark[hv];
1004 landmark[hv] = i/NHASH;
1005 }
1006
1007 /* Begin scanning the target file and generating copy commands and
1008 ** literal sections of the delta.
1009 */
1010 base = 0; /* We have already generated everything before zOut[base] */
1011 while( base+NHASH<lenOut ){
1012 int iSrc, iBlock;
1013 int bestCnt, bestOfst=0, bestLitsz=0;
1014 hash_init(&h, &zOut[base]);
1015 i = 0; /* Trying to match a landmark against zOut[base+i] */
1016 bestCnt = 0;
1017 while( 1 ){
1018 int hv;
1019 int limit = 250;
1020
1021 hv = hash_32bit(&h) % nHash;
1022 iBlock = landmark[hv];
1023 while( iBlock>=0 && (limit--)>0 ){
1024 /*
1025 ** The hash window has identified a potential match against
1026 ** landmark block iBlock. But we need to investigate further.
1027 **
1028 ** Look for a region in zOut that matches zSrc. Anchor the search
1029 ** at zSrc[iSrc] and zOut[base+i]. Do not include anything prior to
1030 ** zOut[base] or after zOut[outLen] nor anything after zSrc[srcLen].
1031 **
1032 ** Set cnt equal to the length of the match and set ofst so that
1033 ** zSrc[ofst] is the first element of the match. litsz is the number
1034 ** of characters between zOut[base] and the beginning of the match.
1035 ** sz will be the overhead (in bytes) needed to encode the copy
1036 ** command. Only generate copy command if the overhead of the
1037 ** copy command is less than the amount of literal text to be copied.
1038 */
1039 int cnt, ofst, litsz;
1040 int j, k, x, y;
1041 int sz;
1042
1043 /* Beginning at iSrc, match forwards as far as we can. j counts
1044 ** the number of characters that match */
1045 iSrc = iBlock*NHASH;
1046 for(
1047 j=0, x=iSrc, y=base+i;
1048 (unsigned int)x<lenSrc && (unsigned int)y<lenOut;
1049 j++, x++, y++
1050 ){
1051 if( zSrc[x]!=zOut[y] ) break;
1052 }
1053 j--;
1054
1055 /* Beginning at iSrc-1, match backwards as far as we can. k counts
1056 ** the number of characters that match */
1057 for(k=1; k<iSrc && (unsigned int)k<=i; k++){
1058 if( zSrc[iSrc-k]!=zOut[base+i-k] ) break;
1059 }
1060 k--;
1061
1062 /* Compute the offset and size of the matching region */
1063 ofst = iSrc-k;
1064 cnt = j+k+1;
1065 litsz = i-k; /* Number of bytes of literal text before the copy */
1066 /* sz will hold the number of bytes needed to encode the "insert"
1067 ** command and the copy command, not counting the "insert" text */
1068 sz = digit_count(i-k)+digit_count(cnt)+digit_count(ofst)+3;
1069 if( cnt>=sz && cnt>bestCnt ){
1070 /* Remember this match only if it is the best so far and it
1071 ** does not increase the file size */
1072 bestCnt = cnt;
1073 bestOfst = iSrc-k;
1074 bestLitsz = litsz;
1075 }
1076
1077 /* Check the next matching block */
1078 iBlock = collide[iBlock];
1079 }
1080
1081 /* We have a copy command that does not cause the delta to be larger
1082 ** than a literal insert. So add the copy command to the delta.
1083 */
1084 if( bestCnt>0 ){
1085 if( bestLitsz>0 ){
1086 /* Add an insert command before the copy */
1087 putInt(bestLitsz,&zDelta);
1088 *(zDelta++) = ':';
1089 memcpy(zDelta, &zOut[base], bestLitsz);
1090 zDelta += bestLitsz;
1091 base += bestLitsz;
1092 }
1093 base += bestCnt;
1094 putInt(bestCnt, &zDelta);
1095 *(zDelta++) = '@';
1096 putInt(bestOfst, &zDelta);
1097 *(zDelta++) = ',';
1098 if( bestOfst + bestCnt -1 > lastRead ){
1099 lastRead = bestOfst + bestCnt - 1;
1100 }
1101 bestCnt = 0;
1102 break;
1103 }
1104
1105 /* If we reach this point, it means no match is found so far */
1106 if( base+i+NHASH>=lenOut ){
1107 /* We have reached the end of the file and have not found any
1108 ** matches. Do an "insert" for everything that does not match */
1109 putInt(lenOut-base, &zDelta);
1110 *(zDelta++) = ':';
1111 memcpy(zDelta, &zOut[base], lenOut-base);
1112 zDelta += lenOut-base;
1113 base = lenOut;
1114 break;
1115 }
1116
1117 /* Advance the hash by one character. Keep looking for a match */
1118 hash_next(&h, zOut[base+i+NHASH]);
1119 i++;
1120 }
1121 }
1122 /* Output a final "insert" record to get all the text at the end of
1123 ** the file that does not match anything in the source file.
1124 */
1125 if( base<lenOut ){
1126 putInt(lenOut-base, &zDelta);
1127 *(zDelta++) = ':';
1128 memcpy(zDelta, &zOut[base], lenOut-base);
1129 zDelta += lenOut-base;
1130 }
1131 /* Output the final checksum record. */
1132 putInt(checksum(zOut, lenOut), &zDelta);
1133 *(zDelta++) = ';';
1134 sqlite3_free(collide);
1135 return (int)(zDelta - zOrigDelta);
1136}
1137
1138/*
1139** End of code copied from fossil.
1140**************************************************************************/
1141
1142static void strPrintfArray(
1143 sqlite3_str *pStr, /* String object to append to */
1144 const char *zSep, /* Separator string */
1145 const char *zFmt, /* Format for each entry */
1146 char **az, int n /* Array of strings & its size (or -1) */
1147){
1148 int i;
1149 for(i=0; az[i] && (i<n || n<0); i++){
1150 if( i!=0 ) sqlite3_str_appendf(pStr, "%s", zSep);
1151 sqlite3_str_appendf(pStr, zFmt, az[i], az[i], az[i]);
1152 }
1153}
1154
1155static void getRbudiffQuery(
1156 const char *zTab,
1157 char **azCol,
1158 int nPK,
1159 int bOtaRowid,
1160 sqlite3_str *pSql
1161){
1162 int i;
1163
1164 /* First the newly inserted rows: **/
1165 sqlite3_str_appendf(pSql, "SELECT ");
1166 strPrintfArray(pSql, ", ", "%s", azCol, -1);
1167 sqlite3_str_appendf(pSql, ", 0, "); /* Set ota_control to 0 for an insert */
1168 strPrintfArray(pSql, ", ", "NULL", azCol, -1);
1169 sqlite3_str_appendf(pSql, " FROM aux.%Q AS n WHERE NOT EXISTS (\n", zTab);
1170 sqlite3_str_appendf(pSql, " SELECT 1 FROM ", zTab);
1171 sqlite3_str_appendf(pSql, " main.%Q AS o WHERE ", zTab);
1172 strPrintfArray(pSql, " AND ", "(n.%Q = o.%Q)", azCol, nPK);
1173 sqlite3_str_appendf(pSql, "\n) AND ");
1174 strPrintfArray(pSql, " AND ", "(n.%Q IS NOT NULL)", azCol, nPK);
1175
1176 /* Deleted rows: */
1177 sqlite3_str_appendf(pSql, "\nUNION ALL\nSELECT ");
1178 strPrintfArray(pSql, ", ", "%s", azCol, nPK);
1179 if( azCol[nPK] ){
1180 sqlite3_str_appendf(pSql, ", ");
1181 strPrintfArray(pSql, ", ", "NULL", &azCol[nPK], -1);
1182 }
1183 sqlite3_str_appendf(pSql, ", 1, "); /* Set ota_control to 1 for a delete */
1184 strPrintfArray(pSql, ", ", "NULL", azCol, -1);
1185 sqlite3_str_appendf(pSql, " FROM main.%Q AS n WHERE NOT EXISTS (\n", zTab);
1186 sqlite3_str_appendf(pSql, " SELECT 1 FROM ", zTab);
1187 sqlite3_str_appendf(pSql, " aux.%Q AS o WHERE ", zTab);
1188 strPrintfArray(pSql, " AND ", "(n.%Q = o.%Q)", azCol, nPK);
1189 sqlite3_str_appendf(pSql, "\n) AND ");
1190 strPrintfArray(pSql, " AND ", "(n.%Q IS NOT NULL)", azCol, nPK);
1191
1192 /* Updated rows. If all table columns are part of the primary key, there
1193 ** can be no updates. In this case this part of the compound SELECT can
1194 ** be omitted altogether. */
1195 if( azCol[nPK] ){
1196 sqlite3_str_appendf(pSql, "\nUNION ALL\nSELECT ");
1197 strPrintfArray(pSql, ", ", "n.%s", azCol, nPK);
1198 sqlite3_str_appendf(pSql, ",\n");
1199 strPrintfArray(pSql, " ,\n",
1200 " CASE WHEN n.%s IS o.%s THEN NULL ELSE n.%s END", &azCol[nPK], -1
1201 );
1202
1203 if( bOtaRowid==0 ){
1204 sqlite3_str_appendf(pSql, ", '");
1205 strPrintfArray(pSql, "", ".", azCol, nPK);
1206 sqlite3_str_appendf(pSql, "' ||\n");
1207 }else{
1208 sqlite3_str_appendf(pSql, ",\n");
1209 }
1210 strPrintfArray(pSql, " ||\n",
1211 " CASE WHEN n.%s IS o.%s THEN '.' ELSE 'x' END", &azCol[nPK], -1
1212 );
1213 sqlite3_str_appendf(pSql, "\nAS ota_control, ");
1214 strPrintfArray(pSql, ", ", "NULL", azCol, nPK);
1215 sqlite3_str_appendf(pSql, ",\n");
1216 strPrintfArray(pSql, " ,\n",
1217 " CASE WHEN n.%s IS o.%s THEN NULL ELSE o.%s END", &azCol[nPK], -1
1218 );
1219
1220 sqlite3_str_appendf(pSql, "\nFROM main.%Q AS o, aux.%Q AS n\nWHERE ",
1221 zTab, zTab);
1222 strPrintfArray(pSql, " AND ", "(n.%Q = o.%Q)", azCol, nPK);
1223 sqlite3_str_appendf(pSql, " AND ota_control LIKE '%%x%%'");
1224 }
1225
1226 /* Now add an ORDER BY clause to sort everything by PK. */
1227 sqlite3_str_appendf(pSql, "\nORDER BY ");
1228 for(i=1; i<=nPK; i++) sqlite3_str_appendf(pSql, "%s%d", ((i>1)?", ":""), i);
1229}
1230
1231static void rbudiff_one_table(const char *zTab, FILE *out){
1232 int bOtaRowid; /* True to use an ota_rowid column */
1233 int nPK; /* Number of primary key columns in table */
1234 char **azCol; /* NULL terminated array of col names */
1235 int i;
1236 int nCol;
1237 sqlite3_str *pCt; /* The "CREATE TABLE data_xxx" statement */
1238 sqlite3_str *pSql; /* Query to find differences */
1239 sqlite3_str *pInsert; /* First part of output INSERT statement */
1240 sqlite3_stmt *pStmt = 0;
1241 int nRow = 0; /* Total rows in data_xxx table */
1242
1243 /* --rbu mode must use real primary keys. */
1244 g.bSchemaPK = 1;
1245 pCt = sqlite3_str_new(0);
1246 pSql = sqlite3_str_new(0);
1247 pInsert = sqlite3_str_new(0);
1248
1249 /* Check that the schemas of the two tables match. Exit early otherwise. */
1250 checkSchemasMatch(zTab);
1251
1252 /* Grab the column names and PK details for the table(s). If no usable PK
1253 ** columns are found, bail out early. */
1254 azCol = columnNames("main", zTab, &nPK, &bOtaRowid);
1255 if( azCol==0 ){
1256 runtimeError("table %s has no usable PK columns", zTab);
1257 }
1258 for(nCol=0; azCol[nCol]; nCol++);
1259
1260 /* Build and output the CREATE TABLE statement for the data_xxx table */
1261 sqlite3_str_appendf(pCt, "CREATE TABLE IF NOT EXISTS 'data_%q'(", zTab);
1262 if( bOtaRowid ) sqlite3_str_appendf(pCt, "rbu_rowid, ");
1263 strPrintfArray(pCt, ", ", "%s", &azCol[bOtaRowid], -1);
1264 sqlite3_str_appendf(pCt, ", rbu_control);");
1265
1266 /* Get the SQL for the query to retrieve data from the two databases */
1267 getRbudiffQuery(zTab, azCol, nPK, bOtaRowid, pSql);
1268
1269 /* Build the first part of the INSERT statement output for each row
1270 ** in the data_xxx table. */
1271 sqlite3_str_appendf(pInsert, "INSERT INTO 'data_%q' (", zTab);
1272 if( bOtaRowid ) sqlite3_str_appendf(pInsert, "rbu_rowid, ");
1273 strPrintfArray(pInsert, ", ", "%s", &azCol[bOtaRowid], -1);
1274 sqlite3_str_appendf(pInsert, ", rbu_control) VALUES(");
1275
1276 pStmt = db_prepare("%s", sqlite3_str_value(pSql));
1277
1278 while( sqlite3_step(pStmt)==SQLITE_ROW ){
1279
1280 /* If this is the first row output, print out the CREATE TABLE
1281 ** statement first. And reset pCt so that it will not be
1282 ** printed again. */
1283 if( sqlite3_str_length(pCt) ){
1284 sqlite3_fprintf(out, "%s\n", sqlite3_str_value(pCt));
1285 sqlite3_str_reset(pCt);
1286 }
1287
1288 /* Output the first part of the INSERT statement */
1289 sqlite3_fprintf(out, "%s", sqlite3_str_value(pInsert));
1290 nRow++;
1291
1292 if( sqlite3_column_type(pStmt, nCol)==SQLITE_INTEGER ){
1293 for(i=0; i<=nCol; i++){
1294 if( i>0 ) sqlite3_fprintf(out, ", ");
1295 printQuoted(out, sqlite3_column_value(pStmt, i));
1296 }
1297 }else{
1298 char *zOtaControl;
1299 i64 nOtaControl = sqlite3_column_bytes(pStmt, nCol);
1300
1301 zOtaControl = (char*)sqlite3_malloc64(nOtaControl+1);
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 i64 nFinal = sqlite3_column_bytes(pStmt, i);
1314 char *aDelta;
1315 int nDelta;
1316
1317 aDelta = sqlite3_malloc64(nFinal + 60);
1318 nDelta = rbuDeltaCreate(aSrc, nSrc, aFinal, nFinal, aDelta);
1319 if( nDelta>0 && nDelta<nFinal ){
1320 int j;
1321 sqlite3_fprintf(out, "x'");
1322 for(j=0; j<nDelta; j++) sqlite3_fprintf(out, "%02x", (u8)aDelta[j]);
1323 sqlite3_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 sqlite3_fprintf(out, ", ");
1334 }
1335 sqlite3_fprintf(out, "'%s'", zOtaControl);
1336 sqlite3_free(zOtaControl);
1337 }
1338
1339 /* And the closing bracket of the insert statement */
1340 sqlite3_fprintf(out, ");\n");
1341 }
1342
1343 sqlite3_finalize(pStmt);
1344 if( nRow>0 ){
1345 sqlite3_str *pCnt = sqlite3_str_new(0);
1346 sqlite3_str_appendf(pCnt,
1347 "INSERT INTO rbu_count VALUES('data_%q', %d);", zTab, nRow);
1348 sqlite3_fprintf(out, "%s\n", sqlite3_str_value(pCnt));
1349 strFree(pCnt);
1350 }
1351
1352 strFree(pCt);
1353 strFree(pSql);
1354 strFree(pInsert);
1355}
1356
1357/*
1358** Display a summary of differences between two versions of the same
1359** table table.
1360**
1361** * Number of rows changed
1362** * Number of rows added
1363** * Number of rows deleted
1364** * Number of identical rows
1365*/
1366static void summarize_one_table(const char *zTab, FILE *out){
1367 char *zId = safeId(zTab); /* Name of table (translated for us in SQL) */
1368 char **az = 0; /* Columns in main */
1369 char **az2 = 0; /* Columns in aux */
1370 int nPk; /* Primary key columns in main */
1371 int nPk2; /* Primary key columns in aux */
1372 int n = 0; /* Number of columns in main */
1373 int n2; /* Number of columns in aux */
1374 int i; /* Loop counter */
1375 const char *zSep; /* Separator string */
1376 sqlite3_str *pSql; /* Comparison query */
1377 sqlite3_stmt *pStmt; /* Query statement to do the diff */
1378 sqlite3_int64 nUpdate; /* Number of updated rows */
1379 sqlite3_int64 nUnchanged; /* Number of unmodified rows */
1380 sqlite3_int64 nDelete; /* Number of deleted rows */
1381 sqlite3_int64 nInsert; /* Number of inserted rows */
1382
1383 pSql = sqlite3_str_new(0);
1384 if( sqlite3_table_column_metadata(g.db,"aux",zTab,0,0,0,0,0,0) ){
1385 if( !sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
1386 /* Table missing from second database. */
1387 sqlite3_fprintf(out, "%s: missing from second database\n", zTab);
1388 }
1389 goto end_summarize_one_table;
1390 }
1391
1392 if( sqlite3_table_column_metadata(g.db,"main",zTab,0,0,0,0,0,0) ){
1393 /* Table missing from source */
1394 sqlite3_fprintf(out, "%s: missing from first database\n", zTab);
1395 goto end_summarize_one_table;
1396 }
1397
1398 az = columnNames("main", zTab, &nPk, 0);
1399 az2 = columnNames("aux", zTab, &nPk2, 0);
1400 if( az && az2 ){
1401 for(n=0; az[n]; n++){
1402 if( sqlite3_stricmp(az[n],az2[n])!=0 ) break;
1403 }
1404 }
1405 if( az==0
1406 || az2==0
1407 || nPk!=nPk2
1408 || az[n]
1409 ){
1410 /* Schema mismatch */
1411 sqlite3_fprintf(out, "%s: incompatible schema\n", zTab);
1412 goto end_summarize_one_table;
1413 }
1414
1415 /* Build the comparison query */
1416 for(n2=n; az[n2]; n2++){}
1417 sqlite3_str_appendf(pSql, "SELECT 1, count(*)");
1418 if( n2==nPk2 ){
1419 sqlite3_str_appendf(pSql, ", 0\n");
1420 }else{
1421 zSep = ", sum(";
1422 for(i=nPk; az[i]; i++){
1423 sqlite3_str_appendf(pSql, "%sA.%s IS NOT B.%s", zSep, az[i], az[i]);
1424 zSep = " OR ";
1425 }
1426 sqlite3_str_appendf(pSql, ")\n");
1427 }
1428 sqlite3_str_appendf(pSql, " FROM main.%s A, aux.%s B\n", zId, zId);
1429 zSep = " WHERE";
1430 for(i=0; i<nPk; i++){
1431 sqlite3_str_appendf(pSql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1432 zSep = " AND";
1433 }
1434 sqlite3_str_appendf(pSql, " UNION ALL\n");
1435 sqlite3_str_appendf(pSql, "SELECT 2, count(*), 0\n");
1436 sqlite3_str_appendf(pSql, " FROM main.%s A\n", zId);
1437 sqlite3_str_appendf(pSql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B ", zId);
1438 zSep = "WHERE";
1439 for(i=0; i<nPk; i++){
1440 sqlite3_str_appendf(pSql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1441 zSep = " AND";
1442 }
1443 sqlite3_str_appendf(pSql, ")\n");
1444 sqlite3_str_appendf(pSql, " UNION ALL\n");
1445 sqlite3_str_appendf(pSql, "SELECT 3, count(*), 0\n");
1446 sqlite3_str_appendf(pSql, " FROM aux.%s B\n", zId);
1447 sqlite3_str_appendf(pSql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A ", zId);
1448 zSep = "WHERE";
1449 for(i=0; i<nPk; i++){
1450 sqlite3_str_appendf(pSql, "%s A.%s=B.%s", zSep, az[i], az[i]);
1451 zSep = " AND";
1452 }
1453 sqlite3_str_appendf(pSql, ")\n ORDER BY 1;\n");
1454
1455 if( (g.fDebug & DEBUG_DIFF_SQL)!=0 ){
1456 sqlite3_fprintf(stdout, "SQL for %s:\n%s\n", zId, sqlite3_str_value(pSql));
1457 goto end_summarize_one_table;
1458 }
1459
1460 /* Run the query and output difference summary */
1461 pStmt = db_prepare("%s", sqlite3_str_value(pSql));
1462 nUpdate = 0;
1463 nInsert = 0;
1464 nDelete = 0;
1465 nUnchanged = 0;
1466 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1467 switch( sqlite3_column_int(pStmt,0) ){
1468 case 1:
1469 nUpdate = sqlite3_column_int64(pStmt,2);
1470 nUnchanged = sqlite3_column_int64(pStmt,1) - nUpdate;
1471 break;
1472 case 2:
1473 nDelete = sqlite3_column_int64(pStmt,1);
1474 break;
1475 case 3:
1476 nInsert = sqlite3_column_int64(pStmt,1);
1477 break;
1478 }
1479 }
1480 sqlite3_finalize(pStmt);
1481 sqlite3_fprintf(out,
1482 "%s: %lld changes, %lld inserts, %lld deletes, %lld unchanged\n",
1483 zTab, nUpdate, nInsert, nDelete, nUnchanged);
1484
1485end_summarize_one_table:
1486 strFree(pSql);
1487 sqlite3_free(zId);
1488 namelistFree(az);
1489 namelistFree(az2);
1490 return;
1491}
1492
1493/*
1494** Write a 64-bit signed integer as a varint onto out
1495*/
1496static void putsVarint(FILE *out, sqlite3_uint64 v){
1497 int i, n;
1498 unsigned char p[12];
1499 if( v & (((sqlite3_uint64)0xff000000)<<32) ){
1500 p[8] = (unsigned char)v;
1501 v >>= 8;
1502 for(i=7; i>=0; i--){
1503 p[i] = (unsigned char)((v & 0x7f) | 0x80);
1504 v >>= 7;
1505 }
1506 fwrite(p, 8, 1, out);
1507 }else{
1508 n = 9;
1509 do{
1510 p[n--] = (unsigned char)((v & 0x7f) | 0x80);
1511 v >>= 7;
1512 }while( v!=0 );
1513 p[9] &= 0x7f;
1514 fwrite(p+n+1, 9-n, 1, out);
1515 }
1516}
1517
1518/*
1519** Write an SQLite value onto out.
1520*/
1521static void putValue(FILE *out, sqlite3_stmt *pStmt, int k){
1522 int iDType = sqlite3_column_type(pStmt, k);
1523 sqlite3_int64 iX;
1524 double rX;
1525 sqlite3_uint64 uX;
1526 int j;
1527
1528 putc(iDType, out);
1529 switch( iDType ){
1530 case SQLITE_INTEGER:
1531 iX = sqlite3_column_int64(pStmt, k);
1532 memcpy(&uX, &iX, 8);
1533 for(j=56; j>=0; j-=8) putc((uX>>j)&0xff, out);
1534 break;
1535 case SQLITE_FLOAT:
1536 rX = sqlite3_column_double(pStmt, k);
1537 memcpy(&uX, &rX, 8);
1538 for(j=56; j>=0; j-=8) putc((uX>>j)&0xff, out);
1539 break;
1540 case SQLITE_TEXT:
1541 iX = sqlite3_column_bytes(pStmt, k);
1542 putsVarint(out, (sqlite3_uint64)iX);
1543 fwrite(sqlite3_column_text(pStmt, k),1,(size_t)iX,out);
1544 break;
1545 case SQLITE_BLOB:
1546 iX = sqlite3_column_bytes(pStmt, k);
1547 putsVarint(out, (sqlite3_uint64)iX);
1548 fwrite(sqlite3_column_blob(pStmt, k),1,(size_t)iX,out);
1549 break;
1550 case SQLITE_NULL:
1551 break;
1552 }
1553}
1554
1555/*
1556** Generate a CHANGESET for all differences from main.zTab to aux.zTab.
1557*/
1558static void changeset_one_table(const char *zTab, FILE *out){
1559 sqlite3_stmt *pStmt; /* SQL statment */
1560 char *zId = safeId(zTab); /* Escaped name of the table */
1561 char **azCol = 0; /* List of escaped column names */
1562 i64 nCol = 0; /* Number of columns */
1563 int *aiFlg = 0; /* 0 if column is not part of PK */
1564 int *aiPk = 0; /* Column numbers for each PK column */
1565 i64 nPk = 0; /* Number of PRIMARY KEY columns */
1566 sqlite3_str *pSql; /* SQL for the diff query */
1567 int i, k; /* Loop counters */
1568 const char *zSep; /* List separator */
1569
1570 /* Check that the schemas of the two tables match. Exit early otherwise. */
1571 checkSchemasMatch(zTab);
1572 pSql = sqlite3_str_new(0);
1573
1574 pStmt = db_prepare("PRAGMA main.table_info=%Q", zTab);
1575 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1576 nCol++;
1577 azCol = sqlite3_realloc64(azCol, sizeof(char*)*nCol);
1578 if( azCol==0 ) runtimeError("out of memory");
1579 aiFlg = sqlite3_realloc64(aiFlg, sizeof(int)*nCol);
1580 if( aiFlg==0 ) runtimeError("out of memory");
1581 azCol[nCol-1] = safeId((const char*)sqlite3_column_text(pStmt,1));
1582 aiFlg[nCol-1] = i = sqlite3_column_int(pStmt,5);
1583 if( i>0 ){
1584 if( i>nPk ){
1585 nPk = i;
1586 aiPk = sqlite3_realloc64(aiPk, sizeof(int)*nPk);
1587 if( aiPk==0 ) runtimeError("out of memory");
1588 }
1589 aiPk[i-1] = nCol-1;
1590 }
1591 }
1592 sqlite3_finalize(pStmt);
1593 if( nPk==0 ) goto end_changeset_one_table;
1594 if( nCol>nPk ){
1595 sqlite3_str_appendf(pSql, "SELECT %d", SQLITE_UPDATE);
1596 for(i=0; i<nCol; i++){
1597 if( aiFlg[i] ){
1598 sqlite3_str_appendf(pSql, ",\n A.%s", azCol[i]);
1599 }else{
1600 sqlite3_str_appendf(pSql, ",\n A.%s IS NOT B.%s, A.%s, B.%s",
1601 azCol[i], azCol[i], azCol[i], azCol[i]);
1602 }
1603 }
1604 sqlite3_str_appendf(pSql,"\n FROM main.%s A, aux.%s B\n", zId, zId);
1605 zSep = " WHERE";
1606 for(i=0; i<nPk; i++){
1607 sqlite3_str_appendf(pSql, "%s A.%s=B.%s",
1608 zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1609 zSep = " AND";
1610 }
1611 zSep = "\n AND (";
1612 for(i=0; i<nCol; i++){
1613 if( aiFlg[i] ) continue;
1614 sqlite3_str_appendf(pSql, "%sA.%s IS NOT B.%s", zSep, azCol[i], azCol[i]);
1615 zSep = " OR\n ";
1616 }
1617 sqlite3_str_appendf(pSql,")\n UNION ALL\n");
1618 }
1619 sqlite3_str_appendf(pSql, "SELECT %d", SQLITE_DELETE);
1620 for(i=0; i<nCol; i++){
1621 if( aiFlg[i] ){
1622 sqlite3_str_appendf(pSql, ",\n A.%s", azCol[i]);
1623 }else{
1624 sqlite3_str_appendf(pSql, ",\n 1, A.%s, NULL", azCol[i]);
1625 }
1626 }
1627 sqlite3_str_appendf(pSql, "\n FROM main.%s A\n", zId);
1628 sqlite3_str_appendf(pSql, " WHERE NOT EXISTS(SELECT 1 FROM aux.%s B\n", zId);
1629 zSep = " WHERE";
1630 for(i=0; i<nPk; i++){
1631 sqlite3_str_appendf(pSql, "%s A.%s=B.%s",
1632 zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1633 zSep = " AND";
1634 }
1635 sqlite3_str_appendf(pSql, ")\n UNION ALL\n");
1636 sqlite3_str_appendf(pSql, "SELECT %d", SQLITE_INSERT);
1637 for(i=0; i<nCol; i++){
1638 if( aiFlg[i] ){
1639 sqlite3_str_appendf(pSql, ",\n B.%s", azCol[i]);
1640 }else{
1641 sqlite3_str_appendf(pSql, ",\n 1, NULL, B.%s", azCol[i]);
1642 }
1643 }
1644 sqlite3_str_appendf(pSql, "\n FROM aux.%s B\n", zId);
1645 sqlite3_str_appendf(pSql, " WHERE NOT EXISTS(SELECT 1 FROM main.%s A\n", zId);
1646 zSep = " WHERE";
1647 for(i=0; i<nPk; i++){
1648 sqlite3_str_appendf(pSql, "%s A.%s=B.%s",
1649 zSep, azCol[aiPk[i]], azCol[aiPk[i]]);
1650 zSep = " AND";
1651 }
1652 sqlite3_str_appendf(pSql, ")\n");
1653 sqlite3_str_appendf(pSql, " ORDER BY");
1654 zSep = " ";
1655 for(i=0; i<nPk; i++){
1656 sqlite3_str_appendf(pSql, "%s %d", zSep, aiPk[i]+2);
1657 zSep = ",";
1658 }
1659 sqlite3_str_appendf(pSql, ";\n");
1660
1661 if( g.fDebug & DEBUG_DIFF_SQL ){
1662 sqlite3_fprintf(stdout, "SQL for %s:\n%s\n", zId, sqlite3_str_value(pSql));
1663 goto end_changeset_one_table;
1664 }
1665
1666 putc('T', out);
1667 putsVarint(out, (sqlite3_uint64)nCol);
1668 for(i=0; i<nCol; i++) putc(aiFlg[i], out);
1669 fwrite(zTab, 1, strlen(zTab), out);
1670 putc(0, out);
1671
1672 pStmt = db_prepare("%s", sqlite3_str_value(pSql));
1673 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1674 int iType = sqlite3_column_int(pStmt,0);
1675 putc(iType, out);
1676 putc(0, out);
1677 switch( sqlite3_column_int(pStmt,0) ){
1678 case SQLITE_UPDATE: {
1679 for(k=1, i=0; i<nCol; i++){
1680 if( aiFlg[i] ){
1681 putValue(out, pStmt, k);
1682 k++;
1683 }else if( sqlite3_column_int(pStmt,k) ){
1684 putValue(out, pStmt, k+1);
1685 k += 3;
1686 }else{
1687 putc(0, out);
1688 k += 3;
1689 }
1690 }
1691 for(k=1, i=0; i<nCol; i++){
1692 if( aiFlg[i] ){
1693 putc(0, out);
1694 k++;
1695 }else if( sqlite3_column_int(pStmt,k) ){
1696 putValue(out, pStmt, k+2);
1697 k += 3;
1698 }else{
1699 putc(0, out);
1700 k += 3;
1701 }
1702 }
1703 break;
1704 }
1705 case SQLITE_INSERT: {
1706 for(k=1, i=0; i<nCol; i++){
1707 if( aiFlg[i] ){
1708 putValue(out, pStmt, k);
1709 k++;
1710 }else{
1711 putValue(out, pStmt, k+2);
1712 k += 3;
1713 }
1714 }
1715 break;
1716 }
1717 case SQLITE_DELETE: {
1718 for(k=1, i=0; i<nCol; i++){
1719 if( aiFlg[i] ){
1720 putValue(out, pStmt, k);
1721 k++;
1722 }else{
1723 putValue(out, pStmt, k+1);
1724 k += 3;
1725 }
1726 }
1727 break;
1728 }
1729 }
1730 }
1731 sqlite3_finalize(pStmt);
1732
1733end_changeset_one_table:
1734 while( nCol>0 ) sqlite3_free(azCol[--nCol]);
1735 sqlite3_free(azCol);
1736 sqlite3_free(aiPk);
1737 sqlite3_free(zId);
1738 sqlite3_free(aiFlg);
1739 strFree(pSql);
1740}
1741
1742/*
1743** Return true if the ascii character passed as the only argument is a
1744** whitespace character. Otherwise return false.
1745*/
1746static int is_whitespace(char x){
1747 return (x==' ' || x=='\t' || x=='\n' || x=='\r');
1748}
1749
1750/*
1751** Extract the next SQL keyword or quoted string from buffer zIn and copy it
1752** (or a prefix of it if it will not fit) into buffer zBuf, size nBuf bytes.
1753** Return a pointer to the character within zIn immediately following
1754** the token or quoted string just extracted.
1755*/
1756static const char *gobble_token(const char *zIn, char *zBuf, int nBuf){
1757 const char *p = zIn;
1758 char *pOut = zBuf;
1759 char *pEnd = &pOut[nBuf-1];
1760 char q = 0; /* quote character, if any */
1761
1762 if( p==0 ) return 0;
1763 while( is_whitespace(*p) ) p++;
1764 switch( *p ){
1765 case '"': q = '"'; break;
1766 case '\'': q = '\''; break;
1767 case '`': q = '`'; break;
1768 case '[': q = ']'; break;
1769 }
1770
1771 if( q ){
1772 p++;
1773 while( *p && pOut<pEnd ){
1774 if( *p==q ){
1775 p++;
1776 if( *p!=q ) break;
1777 }
1778 if( pOut<pEnd ) *pOut++ = *p;
1779 p++;
1780 }
1781 }else{
1782 while( *p && !is_whitespace(*p) && *p!='(' ){
1783 if( pOut<pEnd ) *pOut++ = *p;
1784 p++;
1785 }
1786 }
1787
1788 *pOut = '\0';
1789 return p;
1790}
1791
1792/*
1793** This function is the implementation of SQL scalar function "module_name":
1794**
1795** module_name(SQL)
1796**
1797** The only argument should be an SQL statement of the type that may appear
1798** in the sqlite_schema table. If the statement is a "CREATE VIRTUAL TABLE"
1799** statement, then the value returned is the name of the module that it
1800** uses. Otherwise, if the statement is not a CVT, NULL is returned.
1801*/
1802static void module_name_func(
1803 sqlite3_context *pCtx,
1804 int nVal, sqlite3_value **apVal
1805){
1806 const char *zSql;
1807 char zToken[32];
1808
1809 assert( nVal==1 );
1810 zSql = (const char*)sqlite3_value_text(apVal[0]);
1811
1812 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1813 if( zSql==0 || sqlite3_stricmp(zToken, "create") ) return;
1814 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1815 if( zSql==0 || sqlite3_stricmp(zToken, "virtual") ) return;
1816 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1817 if( zSql==0 || sqlite3_stricmp(zToken, "table") ) return;
1818 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1819 if( zSql==0 ) return;
1820 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1821 if( zSql==0 || sqlite3_stricmp(zToken, "using") ) return;
1822 zSql = gobble_token(zSql, zToken, sizeof(zToken));
1823
1824 sqlite3_result_text(pCtx, zToken, -1, SQLITE_TRANSIENT);
1825}
1826
1827/*
1828** Append text on pOut that is sufficient to complete the statement zBase
1829** (according to sqlite3_complete()). eFlags:
1830**
1831** 0x01 Include the final ";" if needed
1832** 0x04 Assume zBase ends with '\n'
1833*/
1834static void appendCompletion(
1835 sqlite3_str *pOut, /* Append the completion here */
1836 const char *zBase, /* Existing SQL text */
1837 int eFlags /* 0x01: Include ";", 0x04: Assume '\n' */
1838){
1839 sqlite3_int64 R = zBase ? sqlite3_incomplete(zBase) : 0;
1840 int cc = (R>>16)&0xff;
1841 int nParen = R>>32;
1842 int eSemi = (R>>8)&0xff;
1843 int eStat = R&0xff;
1844 int bSemi = (eFlags & 0x01)!=0;
1845 if( cc==0 ){
1846 /* no-op */
1847 }else if( cc=='-' ){
1848 if( (eFlags & 0x04)==0 ) sqlite3_str_appendchar(pOut, 1, '\n');
1849 }else if( cc=='/' ){
1850 sqlite3_str_append(pOut,"*/",2);
1851 }else{
1852 sqlite3_str_appendchar(pOut, 1, cc);
1853 }
1854 if( nParen>0 ){
1855 sqlite3_str_appendf(pOut, "%.*c",nParen,')');
1856 }
1857 if( eStat==SQLITE_OK || eStat==SQLITE_EMPTY ){
1858 /* Nothing to add */
1859 }else if( eSemi==1 ){
1860 if( bSemi ) sqlite3_str_append(pOut, ";", 1);
1861 }else if( eSemi==2 ){
1862 sqlite3_str_append(pOut, "END;", 3+(bSemi!=0));
1863 }else if( eSemi==3 ){
1864 sqlite3_str_append(pOut, ";END;", 4+(bSemi!=0));
1865 }
1866}
1867
1868/*
1869** SQL function: shell_complete_sql(SQL)
1870** shell_complete_sql(SQL, FLAGS)
1871**
1872** NOTE: Only the first one-argument form is registered in this application.
1873**
1874** If the SQL input is a string, return a new string which is the same
1875** text with all pending quotes and comments finish, so that the
1876** SQL is ready to receive its final semicolon. The optional FLAGS
1877** parameter can be an integer where bits mean:
1878**
1879** 0x01 Include the final semicolon
1880** 0x02 Only return the completion text. Omit the original SQL.
1881** 0x04 Assume that SQL has a \n at the end.
1882**
1883** The /C substitution in the CLI prompt is computed using the
1884** equivalent of shell_complete_sql(SQL,3);
1885*/
1886static void shell_complete_sql(
1887 sqlite3_context *pCtx,
1888 int nVal,
1889 sqlite3_value **apVal
1890){
1891 const char *zSql; /* Input SQL text */
1892 sqlite3_str *pOut; /* Completed SQL */
1893 int flags;
1894
1895 if( nVal!=1 && nVal!=2 ) return;
1896 if( nVal==2 ){
1897 flags = 0x7 & sqlite3_value_int64(apVal[1]);
1898 }else{
1899 flags = 0;
1900 }
1901 zSql = (const char*)sqlite3_value_text(apVal[0]);
1902 if( zSql==0 ) return;
1903 pOut = sqlite3_str_new(sqlite3_context_db_handle(pCtx));
1904 if( (flags & 0x02)==0 ) sqlite3_str_appendall(pOut, zSql);
1905 appendCompletion(pOut, zSql, flags & 0x05);
1906 sqlite3_result_str(pCtx, pOut, SQLITE_FINISH);
1907}
1908
1909/*
1910** Return the text of an SQL statement that itself returns the list of
1911** tables to process within the database.
1912*/
1913const char *all_tables_sql(){
1914 if( g.bHandleVtab ){
1915 int rc;
1916
1917 rc = sqlite3_exec(g.db,
1918 "CREATE TEMP TABLE tblmap(module COLLATE nocase, postfix);"
1919 "INSERT INTO temp.tblmap VALUES"
1920 "('fts3', '_content'), ('fts3', '_segments'), ('fts3', '_segdir'),"
1921
1922 "('fts4', '_content'), ('fts4', '_segments'), ('fts4', '_segdir'),"
1923 "('fts4', '_docsize'), ('fts4', '_stat'),"
1924
1925 "('fts5', '_data'), ('fts5', '_idx'), ('fts5', '_content'),"
1926 "('fts5', '_docsize'), ('fts5', '_config'),"
1927
1928 "('rtree', '_node'), ('rtree', '_rowid'), ('rtree', '_parent');"
1929 , 0, 0, 0
1930 );
1931 assert( rc==SQLITE_OK );
1932
1933 rc = sqlite3_create_function(
1934 g.db, "module_name", 1, SQLITE_UTF8, 0, module_name_func, 0, 0
1935 );
1936 assert( rc==SQLITE_OK );
1937
1938 return
1939 "SELECT name FROM main.sqlite_schema\n"
1940 " WHERE type='table' AND (\n"
1941 " module_name(sql) IS NULL OR \n"
1942 " module_name(sql) IN (SELECT module FROM temp.tblmap)\n"
1943 " ) AND name NOT IN (\n"
1944 " SELECT a.name || b.postfix \n"
1945 "FROM main.sqlite_schema AS a, temp.tblmap AS b \n"
1946 "WHERE module_name(a.sql) = b.module\n"
1947 " )\n"
1948 "UNION \n"
1949 "SELECT name FROM aux.sqlite_schema\n"
1950 " WHERE type='table' AND (\n"
1951 " module_name(sql) IS NULL OR \n"
1952 " module_name(sql) IN (SELECT module FROM temp.tblmap)\n"
1953 " ) AND name NOT IN (\n"
1954 " SELECT a.name || b.postfix \n"
1955 "FROM aux.sqlite_schema AS a, temp.tblmap AS b \n"
1956 "WHERE module_name(a.sql) = b.module\n"
1957 " )\n"
1958 " ORDER BY name";
1959 }else{
1960 return
1961 "SELECT name FROM main.sqlite_schema\n"
1962 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1963 " UNION\n"
1964 "SELECT name FROM aux.sqlite_schema\n"
1965 " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
1966 " ORDER BY name";
1967 }
1968}
1969
1970/*
1971** Print sketchy documentation for this utility program
1972*/
1973static void showHelp(void){
1974 sqlite3_fprintf(stdout, "Usage: %s [options] DB1 DB2\n", g.zArgv0);
1975 sqlite3_fprintf(stdout,
1976"Output SQL text that would transform DB1 into DB2.\n"
1977"Options:\n"
1978" --changeset FILE Write a CHANGESET into FILE\n"
1979" -L|--lib LIBRARY Load an SQLite extension library\n"
1980" --primarykey Use schema-defined PRIMARY KEYs\n"
1981" --rbu Output SQL to create/populate RBU table(s)\n"
1982" --schema Show only differences in the schema\n"
1983" --summary Show only a summary of the differences\n"
1984" --table TAB Show only differences in table TAB\n"
1985" --transaction Show SQL output inside a transaction\n"
1986" --vtab Handle fts3, fts4, fts5 and rtree tables\n"
1987"See https://sqlite.org/sqldiff.html for detailed explanation.\n"
1988 );
1989}
1990
1991/* work-around the Microsoft "WorstFit" bug */
1992#if defined(_WIN32) && !defined(__MINGW32__) && !defined(main)
1993#define main utf8_main
1994#endif
1995
1996int main(int argc, char **argv){
1997 const char *zDb1 = 0;
1998 const char *zDb2 = 0;
1999 int i;
2000 int rc;
2001 char *zErrMsg = 0;
2002 char *zSql;
2003 sqlite3_stmt *pStmt;
2004 char *zTab = 0;
2005 FILE *out = stdout;
2006 void (*xDiff)(const char*,FILE*) = diff_one_table;
2007#ifndef SQLITE_OMIT_LOAD_EXTENSION
2008 i64 nExt = 0;
2009 char **azExt = 0;
2010#endif
2011 int useTransaction = 0;
2012 int neverUseTransaction = 0;
2013
2014 g.zArgv0 = argv[0];
2015 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
2016 for(i=1; i<argc; i++){
2017 const char *z = argv[i];
2018 if( z[0]=='-' ){
2019 z++;
2020 if( z[0]=='-' ) z++;
2021 if( strcmp(z,"changeset")==0 ){
2022 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
2023 out = sqlite3_fopen(argv[++i], "wb");
2024 if( out==0 ) cmdlineError("cannot open: %s", argv[i]);
2025 xDiff = changeset_one_table;
2026 neverUseTransaction = 1;
2027 }else
2028 if( strcmp(z,"debug")==0 ){
2029 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
2030 g.fDebug = strtol(argv[++i], 0, 0);
2031 }else
2032 if( strcmp(z,"help")==0 ){
2033 showHelp();
2034 return 0;
2035 }else
2036#ifndef SQLITE_OMIT_LOAD_EXTENSION
2037 if( strcmp(z,"lib")==0 || strcmp(z,"L")==0 ){
2038 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
2039 azExt = realloc(azExt, sizeof(azExt[0])*(nExt+1));
2040 if( azExt==0 ) cmdlineError("out of memory");
2041 azExt[nExt++] = argv[++i];
2042 }else
2043#endif
2044 if( strcmp(z,"primarykey")==0 ){
2045 g.bSchemaPK = 1;
2046 }else
2047 if( strcmp(z,"rbu")==0 ){
2048 xDiff = rbudiff_one_table;
2049 }else
2050 if( strcmp(z,"schema")==0 ){
2051 g.bSchemaOnly = 1;
2052 }else
2053 if( strcmp(z,"summary")==0 ){
2054 xDiff = summarize_one_table;
2055 }else
2056 if( strcmp(z,"table")==0 ){
2057 if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
2058 zTab = argv[++i];
2059 g.bSchemaCompare =
2060 sqlite3_stricmp(zTab, "sqlite_schema")==0
2061 || sqlite3_stricmp(zTab, "sqlite_master")==0;
2062 }else
2063 if( strcmp(z,"transaction")==0 ){
2064 useTransaction = 1;
2065 }else
2066 if( strcmp(z,"unsafe")==0 ){
2067 g.bUnsafe = 1;
2068 }else
2069 if( strcmp(z,"vtab")==0 ){
2070 g.bHandleVtab = 1;
2071 }else
2072 {
2073 cmdlineError("unknown option: %s", argv[i]);
2074 }
2075 }else if( zDb1==0 ){
2076 zDb1 = argv[i];
2077 }else if( zDb2==0 ){
2078 zDb2 = argv[i];
2079 }else{
2080 cmdlineError("unknown argument: %s", argv[i]);
2081 }
2082 }
2083 if( zDb2==0 ){
2084 cmdlineError("two database arguments required");
2085 }
2086 if( g.bSchemaOnly && g.bSchemaCompare ){
2087 cmdlineError("The --schema option is useless with --table %s .", zTab);
2088 }
2089 rc = sqlite3_open_v2(zDb1, &g.db, SQLITE_OPEN_READONLY, 0);
2090 if( rc ){
2091 cmdlineError("cannot open database file \"%s\"", zDb1);
2092 }
2093 if( g.bUnsafe ){
2094 sqlite3_db_config(g.db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
2095 }else{
2096 sqlite3_db_config(g.db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0);
2097 sqlite3_db_config(g.db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, 0, 0);
2098 }
2099 sqlite3_create_function(g.db, "shell_complete_sql", 1, SQLITE_UTF8, 0,
2100 shell_complete_sql, 0, 0);
2101 rc = sqlite3_exec(g.db, "SELECT * FROM sqlite_schema", 0, 0, &zErrMsg);
2102 if( rc || zErrMsg ){
2103 cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb1);
2104 }else{
2105 sqlite3 *db2 = 0;
2106 if( sqlite3_open_v2(zDb2, &db2, SQLITE_OPEN_READONLY, 0) ){
2107 cmdlineError("cannot open database file \"%s\"", zDb2);
2108 }
2109 sqlite3_close(db2);
2110 }
2111#ifndef SQLITE_OMIT_LOAD_EXTENSION
2112 sqlite3_enable_load_extension(g.db, 1);
2113 for(i=0; i<nExt; i++){
2114 rc = sqlite3_load_extension(g.db, azExt[i], 0, &zErrMsg);
2115 if( rc || zErrMsg ){
2116 cmdlineError("error loading %s: %s", azExt[i], zErrMsg);
2117 }
2118 }
2119 free(azExt);
2120#endif
2121 zSql = sqlite3_mprintf("ATTACH %Q as aux;", zDb2);
2122 rc = sqlite3_exec(g.db, zSql, 0, 0, &zErrMsg);
2123 sqlite3_free(zSql);
2124 zSql = 0;
2125 if( rc || zErrMsg ){
2126 cmdlineError("cannot attach database \"%s\"", zDb2);
2127 }
2128 rc = sqlite3_exec(g.db, "SELECT * FROM aux.sqlite_schema", 0, 0, &zErrMsg);
2129 if( rc || zErrMsg ){
2130 cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb2);
2131 }
2132
2133 if( neverUseTransaction ) useTransaction = 0;
2134 if( useTransaction ) sqlite3_fprintf(out, "BEGIN TRANSACTION;\n");
2135 if( xDiff==rbudiff_one_table ){
2136 sqlite3_fprintf(out, "CREATE TABLE IF NOT EXISTS rbu_count"
2137 "(tbl TEXT PRIMARY KEY COLLATE NOCASE, cnt INTEGER) "
2138 "WITHOUT ROWID;\n"
2139 );
2140 }
2141 if( zTab ){
2142 xDiff(zTab, out);
2143 }else{
2144 /* Handle tables one by one */
2145 pStmt = db_prepare("%s", all_tables_sql() );
2146 while( SQLITE_ROW==sqlite3_step(pStmt) ){
2147 xDiff((const char*)sqlite3_column_text(pStmt,0), out);
2148 }
2149 sqlite3_finalize(pStmt);
2150 }
2151 if( useTransaction ) sqlite3_fprintf(stdout,"COMMIT;\n");
2152
2153 /* TBD: Handle trigger differences */
2154 /* TBD: Handle view differences */
2155 sqlite3_close(g.db);
2156 return 0;
2157}