sqldiff.c 65 KB

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