Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/tool/sqldiff.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers 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 23 #include 24 #include 25 #include 26 #include 27 #include 28 #include "sqlite3.h" 29 #include "sqlite3_stdio.h" 30 31 typedef sqlite3_int64 i64; 32 typedef sqlite3_uint64 u64; 33 34 /* 35 ** All global variables are gathered into the "g" singleton. 36 */ 37 struct 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 */ 57 static 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 */ 65 static 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 */ 81 static 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 */ 100 static 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 */ 123 static 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 } 138 static 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 */ 150 static 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 */ 202 static 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 ){ 322 az[0] = sqlite3_mprintf("%s", azRowid[i]); 323 break; 324 } 325 } 326 if( az[0]==0 ){ 327 for(i=1; iinctl ){ 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 */ 412 static 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; inPk2 ){ 571 zSep = "SELECT "; 572 for(i=0; iz[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 */ 814 static 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 */ 825 static 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 */ 832 static 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 */ 853 static 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 */ 862 static 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 */ 956 static 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=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=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( base1)?", ":""), i); 1229 } 1230 1231 static 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=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 && nDelta0 ){ 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 */ 1366 static 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>= 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 */ 1521 static 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 */ 1558 static 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; i0 ) 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 */ 1746 static 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 */ 1756 static 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>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 */ 1886 static 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 */ 1913 const 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 */ 1973 static 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 1996 int 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