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/ext/misc/fossildelta.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 / ext / misc / fossildelta.c` 1148 lines ยท 35542 bytes Raw Blame History 1 /* 2 ** 2019-02-19 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 SQLite extension implements the delta functions used by the RBU 14 ** extension. Three scalar functions and one table-valued function are 15 ** implemented here: 16 ** 17 ** delta_apply(X,D) -- apply delta D to file X and return the result 18 ** delta_create(X,Y) -- compute and return a delta that carries X into Y 19 ** delta_output_size(D) -- blob size in bytes output from applying delta D 20 ** delta_parse(D) -- returns rows describing delta D 21 ** 22 ** The delta format is the Fossil delta format, described in a comment 23 ** on the delete_create() function implementation below, and also at 24 ** 25 ** https://fossil-scm.org/fossil/doc/trunk/www/delta_format.wiki 26 ** 27 ** This delta format is used by the RBU extension, which is the main 28 ** reason that these routines are included in the extension library. 29 ** RBU does not use this extension directly. Rather, this extension is 30 ** provided as a convenience to developers who want to analyze RBU files 31 ** that contain deltas. 32 ** 33 ** Typical build commands assuming 34 ** 35 ** DIR=ext/misc 36 * NAME=fossildelta 37 ** 38 ** First run "make sqlite3ext.h" then: 39 ** 40 ** linux: gcc -shared -I. -fPIC -o $NAME.so $DIR/$NAME.c 41 ** OS-X: gcc -dynamiclib -fPIC -I. -o $NAME.dylib $DIR/$NAME.c 42 ** Win11: cl -I. $DIR/$NAME.c -link -dll -out:$NAME.dll 43 */ 44 #include 45 #include 46 #include 47 #include 48 #include "sqlite3ext.h" 49 SQLITE_EXTENSION_INIT1 50 51 #ifndef SQLITE_AMALGAMATION 52 /* 53 ** The "u32" type must be an unsigned 32-bit integer. "u64" is 54 ** an unsigned 64-bit integer. 55 */ 56 typedef unsigned int u32; 57 typedef sqlite3_uint64 u64; 58 typedef sqlite3_int64 i64; 59 60 /* 61 ** Must be a 16-bit value 62 */ 63 typedef short int s16; 64 typedef unsigned short int u16; 65 66 #endif /* SQLITE_AMALGAMATION */ 67 68 69 /* 70 ** The width of a hash window in bytes. The algorithm only works if this 71 ** is a power of 2. 72 */ 73 #define NHASH 16 74 75 /* 76 ** The current state of the rolling hash. 77 ** 78 ** z[] holds the values that have been hashed. z[] is a circular buffer. 79 ** z[i] is the first entry and z[(i+NHASH-1)%NHASH] is the last entry of 80 ** the window. 81 ** 82 ** Hash.a is the sum of all elements of hash.z[]. Hash.b is a weighted 83 ** sum. Hash.b is z[i]*NHASH + z[i+1]*(NHASH-1) + ... + z[i+NHASH-1]*1. 84 ** (Each index for z[] should be module NHASH, of course. The %NHASH operator 85 ** is omitted in the prior expression for brevity.) 86 */ 87 typedef struct hash hash; 88 struct hash { 89 u16 a, b; /* Hash values */ 90 u16 i; /* Start of the hash window */ 91 char z[NHASH]; /* The values that have been hashed */ 92 }; 93 94 /* 95 ** Initialize the rolling hash using the first NHASH characters of z[] 96 */ 97 static void hash_init(hash *pHash, const char *z){ 98 u16 a, b, i; 99 a = b = z[0]; 100 for(i=1; iz, z, NHASH); 105 pHash->a = a & 0xffff; 106 pHash->b = b & 0xffff; 107 pHash->i = 0; 108 } 109 110 /* 111 ** Advance the rolling hash by a single character "c" 112 */ 113 static void hash_next(hash *pHash, int c){ 114 u16 old = pHash->z[pHash->i]; 115 pHash->z[pHash->i] = c; 116 pHash->i = (pHash->i+1)&(NHASH-1); 117 pHash->a = pHash->a - old + c; 118 pHash->b = pHash->b - NHASH*old + pHash->a; 119 } 120 121 /* 122 ** Return a 32-bit hash value 123 */ 124 static u32 hash_32bit(hash *pHash){ 125 return (pHash->a & 0xffff) | (((u32)(pHash->b & 0xffff))<<16); 126 } 127 128 /* 129 ** Compute a hash on NHASH bytes. 130 ** 131 ** This routine is intended to be equivalent to: 132 ** hash h; 133 ** hash_init(&h, zInput); 134 ** return hash_32bit(&h); 135 */ 136 static u32 hash_once(const char *z){ 137 u16 a, b, i; 138 a = b = z[0]; 139 for(i=1; i0; i++, v>>=6){ 160 zBuf[i] = zDigits[v&0x3f]; 161 } 162 for(j=i-1; j>=0; j--){ 163 *(*pz)++ = zBuf[j]; 164 } 165 } 166 167 /* 168 ** Read bytes from *pz and convert them into a positive integer. When 169 ** finished, leave *pz pointing to the first character past the end of 170 ** the integer. The *pLen parameter holds the length of the string 171 ** in *pz and is decremented once for each character in the integer. 172 */ 173 static unsigned int deltaGetInt(const char **pz, int *pLen){ 174 static const signed char zValue[] = { 175 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 176 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 177 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, 179 -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 180 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36, 181 -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 182 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1, 183 184 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 185 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 186 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 187 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 188 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 189 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 190 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 191 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192 }; 193 unsigned int v = 0; 194 int c; 195 unsigned char *z = (unsigned char*)*pz; 196 unsigned char *zEnd = z + (*pLen); 197 while( z=0 ){ 198 v = (v<<6) + c; 199 z++; 200 } 201 202 *pLen -= (int)(z - (unsigned char*)*pz); 203 *pz = (char*)z; 204 return v; 205 } 206 207 /* 208 ** Return the number digits in the base-64 representation of a positive integer 209 */ 210 static int digit_count(int v){ 211 unsigned int i, x; 212 for(i=1, x=64; v>=x; i++, x <<= 6){} 213 return i; 214 } 215 216 #ifdef __GNUC__ 217 # define GCC_VERSION (__GNUC__*`1000000`+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__) 218 #else 219 # define GCC_VERSION 0 220 #endif 221 222 /* 223 ** Compute a 32-bit big-endian checksum on the N-byte buffer. If the 224 ** buffer is not a multiple of 4 bytes length, compute the sum that would 225 ** have occurred if the buffer was padded with zeros to the next multiple 226 ** of four bytes. 227 */ 228 static unsigned int checksum(const char *zIn, size_t N){ 229 static const int byteOrderTest = 1; 230 const unsigned char *z = (const unsigned char *)zIn; 231 const unsigned char *zEnd = (const unsigned char*)&zIn[N&~3]; 232 unsigned sum = 0; 233 assert( (z - (const unsigned char*)0)%4==0 ); /* Four-byte alignment */ 234 if( 0==*(char*)&byteOrderTest ){ 235 /* This is a big-endian machine */ 236 while( z=`4003000` 243 while( z=1300 248 while( z= 16){ 257 sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]); 258 sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]); 259 sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]); 260 sum += ((unsigned)z[3] + z[7] + z[11]+ z[15]); 261 z += 16; 262 N -= 16; 263 } 264 while(N >= 4){ 265 sum0 += z[0]; 266 sum1 += z[1]; 267 sum2 += z[2]; 268 sum += z[3]; 269 z += 4; 270 N -= 4; 271 } 272 sum += (sum2 << 8) + (sum1 << 16) + (sum0 << 24); 273 #endif 274 } 275 switch(N&3){ 276 case 3: sum += (z[2] << 8); 277 case 2: sum += (z[1] << 16); 278 case 1: sum += (z[0] << 24); 279 default: ; 280 } 281 return sum; 282 } 283 284 /* 285 ** Create a new delta. 286 ** 287 ** The delta is written into a preallocated buffer, zDelta, which 288 ** should be at least 60 bytes longer than the target file, zOut. 289 ** The delta string will be NUL-terminated, but it might also contain 290 ** embedded NUL characters if either the zSrc or zOut files are 291 ** binary. This function returns the length of the delta string 292 ** in bytes, excluding the final NUL terminator character. It returns 293 ** 0 if an OOM occurs. 294 ** 295 ** Output Format: 296 ** 297 ** The delta begins with a base64 number followed by a newline. This 298 ** number is the number of bytes in the TARGET file. Thus, given a 299 ** delta file z, a program can compute the size of the output file 300 ** simply by reading the first line and decoding the base-64 number 301 ** found there. The delta_output_size() routine does exactly this. 302 ** 303 ** After the initial size number, the delta consists of a series of 304 ** literal text segments and commands to copy from the SOURCE file. 305 ** A copy command looks like this: 306 ** 307 ** NNN@MMM, 308 ** 309 ** where NNN is the number of bytes to be copied and MMM is the offset 310 ** into the source file of the first byte (both base-64). If NNN is 0 311 ** it means copy the rest of the input file. Literal text is like this: 312 ** 313 ** NNN:TTTTT 314 ** 315 ** where NNN is the number of bytes of text (base-64) and TTTTT is the text. 316 ** 317 ** The last term is of the form 318 ** 319 ** NNN; 320 ** 321 ** In this case, NNN is a 32-bit bigendian checksum of the output file 322 ** that can be used to verify that the delta applied correctly. All 323 ** numbers are in base-64. 324 ** 325 ** Pure text files generate a pure text delta. Binary files generate a 326 ** delta that may contain some binary data. 327 ** 328 ** Algorithm: 329 ** 330 ** The encoder first builds a hash table to help it find matching 331 ** patterns in the source file. 16-byte chunks of the source file 332 ** sampled at evenly spaced intervals are used to populate the hash 333 ** table. 334 ** 335 ** Next we begin scanning the target file using a sliding 16-byte 336 ** window. The hash of the 16-byte window in the target is used to 337 ** search for a matching section in the source file. When a match 338 ** is found, a copy command is added to the delta. An effort is 339 ** made to extend the matching section to regions that come before 340 ** and after the 16-byte hash window. A copy command is only issued 341 ** if the result would use less space that just quoting the text 342 ** literally. Literal text is added to the delta for sections that 343 ** do not match or which can not be encoded efficiently using copy 344 ** commands. 345 */ 346 static int delta_create( 347 const char *zSrc, /* The source or pattern file */ 348 unsigned int lenSrc, /* Length of the source file */ 349 const char *zOut, /* The target file */ 350 unsigned int lenOut, /* Length of the target file */ 351 char *zDelta /* Write the delta into this buffer */ 352 ){ 353 int i, base; 354 char *zOrigDelta = zDelta; 355 hash h; 356 int nHash; /* Number of hash table entries */ 357 int *landmark; /* Primary hash table */ 358 int *collide; /* Collision chain */ 359 int lastRead = -1; /* Last byte of zSrc read by a COPY command */ 360 361 /* Add the target file size to the beginning of the delta 362 */ 363 putInt(lenOut, &zDelta); 364 *(zDelta++) = '\n'; 365 366 /* If the source file is very small, it means that we have no 367 ** chance of ever doing a copy command. Just output a single 368 ** literal segment for the entire target and exit. 369 */ 370 if( lenSrc<=NHASH ){ 371 putInt(lenOut, &zDelta); 372 *(zDelta++) = ':'; 373 memcpy(zDelta, zOut, lenOut); 374 zDelta += lenOut; 375 putInt(checksum(zOut, lenOut), &zDelta); 376 *(zDelta++) = ';'; 377 return zDelta - zOrigDelta; 378 } 379 380 /* Compute the hash table used to locate matching sections in the 381 ** source file. 382 */ 383 nHash = lenSrc/NHASH; 384 collide = sqlite3_malloc64( (sqlite3_int64)nHash*2*sizeof(int) ); 385 if( collide==0 ) return 0; 386 memset(collide, -1, nHash*2*sizeof(int)); 387 landmark = &collide[nHash]; 388 for(i=0; i=0 && (limit--)>0 ){ 411 /* 412 ** The hash window has identified a potential match against 413 ** landmark block iBlock. But we need to investigate further. 414 ** 415 ** Look for a region in zOut that matches zSrc. Anchor the search 416 ** at zSrc[iSrc] and zOut[base+i]. Do not include anything prior to 417 ** zOut[base] or after zOut[outLen] nor anything after zSrc[srcLen]. 418 ** 419 ** Set cnt equal to the length of the match and set ofst so that 420 ** zSrc[ofst] is the first element of the match. litsz is the number 421 ** of characters between zOut[base] and the beginning of the match. 422 ** sz will be the overhead (in bytes) needed to encode the copy 423 ** command. Only generate copy command if the overhead of the 424 ** copy command is less than the amount of literal text to be copied. 425 */ 426 int cnt, ofst, litsz; 427 int j, k, x, y; 428 int sz; 429 int limitX; 430 431 /* Beginning at iSrc, match forwards as far as we can. j counts 432 ** the number of characters that match */ 433 iSrc = iBlock*NHASH; 434 y = base+i; 435 limitX = ( lenSrc-iSrc <= lenOut-y ) ? lenSrc : iSrc + lenOut - y; 436 for(x=iSrc; x=sz && cnt>bestCnt ){ 456 /* Remember this match only if it is the best so far and it 457 ** does not increase the file size */ 458 bestCnt = cnt; 459 bestOfst = iSrc-k; 460 bestLitsz = litsz; 461 } 462 463 /* Check the next matching block */ 464 iBlock = collide[iBlock]; 465 } 466 467 /* We have a copy command that does not cause the delta to be larger 468 ** than a literal insert. So add the copy command to the delta. 469 */ 470 if( bestCnt>0 ){ 471 if( bestLitsz>0 ){ 472 /* Add an insert command before the copy */ 473 putInt(bestLitsz,&zDelta); 474 *(zDelta++) = ':'; 475 memcpy(zDelta, &zOut[base], bestLitsz); 476 zDelta += bestLitsz; 477 base += bestLitsz; 478 } 479 base += bestCnt; 480 putInt(bestCnt, &zDelta); 481 *(zDelta++) = '@'; 482 putInt(bestOfst, &zDelta); 483 *(zDelta++) = ','; 484 if( bestOfst + bestCnt -1 > lastRead ){ 485 lastRead = bestOfst + bestCnt - 1; 486 } 487 bestCnt = 0; 488 break; 489 } 490 491 /* If we reach this point, it means no match is found so far */ 492 if( base+i+NHASH>=lenOut ){ 493 /* We have reached the end of the file and have not found any 494 ** matches. Do an "insert" for everything that does not match */ 495 putInt(lenOut-base, &zDelta); 496 *(zDelta++) = ':'; 497 memcpy(zDelta, &zOut[base], lenOut-base); 498 zDelta += lenOut-base; 499 base = lenOut; 500 break; 501 } 502 503 /* Advance the hash by one character. Keep looking for a match */ 504 hash_next(&h, zOut[base+i+NHASH]); 505 i++; 506 } 507 } 508 /* Output a final "insert" record to get all the text at the end of 509 ** the file that does not match anything in the source file. 510 */ 511 if( base0 && zDelta[0] ){ 584 unsigned int cnt, ofst; 585 cnt = deltaGetInt(&zDelta, &lenDelta); 586 if( lenDelta<=0 ) return -1; 587 switch( zDelta[0] ){ 588 case '@': { 589 zDelta++; lenDelta--; 590 ofst = deltaGetInt(&zDelta, &lenDelta); 591 if( lenDelta>0 && zDelta[0]!=',' ){ 592 /* ERROR: copy command not terminated by ',' */ 593 return -1; 594 } 595 zDelta++; lenDelta--; 596 total += cnt; 597 if( total>limit ){ 598 /* ERROR: copy exceeds output file size */ 599 return -1; 600 } 601 if( (u64)ofst+(u64)cnt > (u64)lenSrc ){ 602 /* ERROR: copy extends past end of input */ 603 return -1; 604 } 605 memcpy(zOut, &zSrc[ofst], cnt); 606 zOut += cnt; 607 break; 608 } 609 case ':': { 610 zDelta++; lenDelta--; 611 total += cnt; 612 if( total>limit ){ 613 /* ERROR: insert command gives an output larger than predicted */ 614 return -1; 615 } 616 if( cnt>lenDelta ){ 617 /* ERROR: insert count exceeds size of delta */ 618 return -1; 619 } 620 memcpy(zOut, zDelta, cnt); 621 zOut += cnt; 622 zDelta += cnt; 623 lenDelta -= cnt; 624 break; 625 } 626 case ';': { 627 zDelta++; lenDelta--; 628 zOut[0] = 0; 629 #ifdef FOSSIL_ENABLE_DELTA_CKSUM_TEST 630 if( cnt!=checksum(zOrigOut, total) ){ 631 /* ERROR: bad checksum */ 632 return -1; 633 } 634 #endif 635 if( total!=limit ){ 636 /* ERROR: generated size does not match predicted size */ 637 return -1; 638 } 639 return total; 640 } 641 default: { 642 /* ERROR: unknown delta operator */ 643 return -1; 644 } 645 } 646 } 647 /* ERROR: unterminated delta */ 648 return -1; 649 } 650 651 /* 652 ** SQL functions: delta_create(X,Y) 653 ** 654 ** Return a delta for carrying X into Y. 655 */ 656 static void deltaCreateFunc( 657 sqlite3_context *context, 658 int argc, 659 sqlite3_value **argv 660 ){ 661 const char *aOrig; int nOrig; /* old blob */ 662 const char *aNew; int nNew; /* new blob */ 663 char *aOut; int nOut; /* output delta */ 664 665 assert( argc==2 ); 666 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 667 if( sqlite3_value_type(argv[1])==SQLITE_NULL ) return; 668 nOrig = sqlite3_value_bytes(argv[0]); 669 aOrig = (const char*)sqlite3_value_blob(argv[0]); 670 nNew = sqlite3_value_bytes(argv[1]); 671 aNew = (const char*)sqlite3_value_blob(argv[1]); 672 aOut = sqlite3_malloc64(nNew+70); 673 if( aOut==0 ){ 674 sqlite3_result_error_nomem(context); 675 }else{ 676 nOut = delta_create(aOrig, nOrig, aNew, nNew, aOut); 677 if( nOut<0 ){ 678 sqlite3_free(aOut); 679 sqlite3_result_error(context, "cannot create fossil delta", -1); 680 }else{ 681 sqlite3_result_blob(context, aOut, nOut, sqlite3_free); 682 } 683 } 684 } 685 686 /* 687 ** SQL functions: delta_apply(X,D) 688 ** 689 ** Return the result of applying delta D to input X. 690 */ 691 static void deltaApplyFunc( 692 sqlite3_context *context, 693 int argc, 694 sqlite3_value **argv 695 ){ 696 const char *aOrig; int nOrig; /* The X input */ 697 const char *aDelta; int nDelta; /* The input delta (D) */ 698 char *aOut; sqlite3_int64 nOut; /* The output */ 699 700 assert( argc==2 ); 701 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 702 if( sqlite3_value_type(argv[1])==SQLITE_NULL ) return; 703 nOrig = sqlite3_value_bytes(argv[0]); 704 aOrig = (const char*)sqlite3_value_blob(argv[0]); 705 nDelta = sqlite3_value_bytes(argv[1]); 706 aDelta = (const char*)sqlite3_value_blob(argv[1]); 707 708 /* Figure out the size of the output */ 709 nOut = delta_output_size(aDelta, nDelta); 710 if( nOut<0 ){ 711 sqlite3_result_error(context, "corrupt fossil delta", -1); 712 return; 713 } 714 if( nOut > 0x7fffffff ){ 715 sqlite3_result_error_toobig(context); 716 return; 717 } 718 aOut = sqlite3_malloc64(nOut+1); 719 if( aOut==0 ){ 720 sqlite3_result_error_nomem(context); 721 }else{ 722 const int nOut2 = delta_apply(aOrig, nOrig, aDelta, nDelta, aOut); 723 if( nOut2!=nOut ){ 724 sqlite3_free(aOut); 725 sqlite3_result_error(context, "corrupt fossil delta", -1); 726 }else{ 727 sqlite3_result_blob(context, aOut, nOut, sqlite3_free); 728 } 729 } 730 } 731 732 733 /* 734 ** SQL functions: delta_output_size(D) 735 ** 736 ** Return the size of the output that results from applying delta D. 737 */ 738 static void deltaOutputSizeFunc( 739 sqlite3_context *context, 740 int argc, 741 sqlite3_value **argv 742 ){ 743 const char *aDelta; int nDelta; /* The input delta (D) */ 744 sqlite3_int64 nOut; /* Size of output */ 745 assert( argc==1 ); 746 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 747 nDelta = sqlite3_value_bytes(argv[0]); 748 aDelta = (const char*)sqlite3_value_blob(argv[0]); 749 750 /* Figure out the size of the output */ 751 nOut = delta_output_size(aDelta, nDelta); 752 if( nOut<0 ){ 753 sqlite3_result_error(context, "corrupt fossil delta", -1); 754 return; 755 }else{ 756 sqlite3_result_int64(context, nOut); 757 } 758 } 759 760 /***************************************************************************** 761 ** Table-valued SQL function: delta_parse(DELTA) 762 ** 763 ** Schema: 764 ** 765 ** CREATE TABLE delta_parse( 766 ** op TEXT, 767 ** a1 INT, 768 ** a2 ANY, 769 ** delta HIDDEN BLOB 770 ** ); 771 ** 772 ** Given an input DELTA, this function parses the delta and returns 773 ** rows for each entry in the delta. The op column has one of the 774 ** values SIZE, COPY, INSERT, CHECKSUM, ERROR. 775 ** 776 ** Assuming no errors, the first row has op='SIZE'. a1 is the size of 777 ** the output in bytes and a2 is NULL. 778 ** 779 ** After the initial SIZE row, there are zero or more 'COPY' and/or 'INSERT' 780 ** rows. A COPY row means content is copied from the source into the 781 ** output. Column a1 is the number of bytes to copy and a2 is the offset 782 ** into source from which to begin copying. An INSERT row means to 783 ** insert text into the output stream. Column a1 is the number of bytes 784 ** to insert and column is a BLOB that contains the text to be inserted. 785 ** 786 ** The last row of a well-formed delta will have an op value of 'CHECKSUM'. 787 ** The a1 column will be the value of the checksum and a2 will be NULL. 788 ** 789 ** If the input delta is not well-formed, then a row with an op value 790 ** of 'ERROR' is returned. The a1 value of the ERROR row is the offset 791 ** into the delta where the error was encountered and a2 is NULL. 792 */ 793 typedef struct deltaparsevtab_vtab deltaparsevtab_vtab; 794 typedef struct deltaparsevtab_cursor deltaparsevtab_cursor; 795 struct deltaparsevtab_vtab { 796 sqlite3_vtab base; /* Base class - must be first */ 797 /* No additional information needed */ 798 }; 799 struct deltaparsevtab_cursor { 800 sqlite3_vtab_cursor base; /* Base class - must be first */ 801 char *aDelta; /* The delta being parsed */ 802 i64 iCursor; /* Current cursor location */ 803 i64 iNext; /* Next cursor value */ 804 i64 nDelta; /* Number of bytes in the delta */ 805 int eOp; /* Name of current operator */ 806 unsigned int a1, a2; /* Arguments to current operator */ 807 }; 808 809 /* Operator names: 810 */ 811 static const char *azOp[] = { 812 "SIZE", "COPY", "INSERT", "CHECKSUM", "ERROR", "EOF" 813 }; 814 #define DELTAPARSE_OP_SIZE 0 815 #define DELTAPARSE_OP_COPY 1 816 #define DELTAPARSE_OP_INSERT 2 817 #define DELTAPARSE_OP_CHECKSUM 3 818 #define DELTAPARSE_OP_ERROR 4 819 #define DELTAPARSE_OP_EOF 5 820 821 /* 822 ** The deltaparsevtabConnect() method is invoked to create a new 823 ** deltaparse virtual table. 824 ** 825 ** Think of this routine as the constructor for deltaparsevtab_vtab objects. 826 ** 827 ** All this routine needs to do is: 828 ** 829 ** (1) Allocate the deltaparsevtab_vtab object and initialize all fields. 830 ** 831 ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the 832 ** result set of queries against the virtual table will look like. 833 */ 834 static int deltaparsevtabConnect( 835 sqlite3 *db, 836 void *pAux, 837 int argc, const char *const*argv, 838 sqlite3_vtab **ppVtab, 839 char **pzErr 840 ){ 841 deltaparsevtab_vtab *pNew; 842 int rc; 843 844 rc = sqlite3_declare_vtab(db, 845 "CREATE TABLE x(op,a1,a2,delta HIDDEN)" 846 ); 847 /* For convenience, define symbolic names for the index to each column. */ 848 #define DELTAPARSEVTAB_OP 0 849 #define DELTAPARSEVTAB_A1 1 850 #define DELTAPARSEVTAB_A2 2 851 #define DELTAPARSEVTAB_DELTA 3 852 if( rc==SQLITE_OK ){ 853 pNew = sqlite3_malloc64( sizeof(*pNew) ); 854 *ppVtab = (sqlite3_vtab*)pNew; 855 if( pNew==0 ) return SQLITE_NOMEM; 856 memset(pNew, 0, sizeof(*pNew)); 857 sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS); 858 } 859 return rc; 860 } 861 862 /* 863 ** This method is the destructor for deltaparsevtab_vtab objects. 864 */ 865 static int deltaparsevtabDisconnect(sqlite3_vtab *pVtab){ 866 deltaparsevtab_vtab *p = (deltaparsevtab_vtab*)pVtab; 867 sqlite3_free(p); 868 return SQLITE_OK; 869 } 870 871 /* 872 ** Constructor for a new deltaparsevtab_cursor object. 873 */ 874 static int deltaparsevtabOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ 875 deltaparsevtab_cursor *pCur; 876 pCur = sqlite3_malloc64( sizeof(*pCur) ); 877 if( pCur==0 ) return SQLITE_NOMEM; 878 memset(pCur, 0, sizeof(*pCur)); 879 *ppCursor = &pCur->base; 880 return SQLITE_OK; 881 } 882 883 /* 884 ** Destructor for a deltaparsevtab_cursor. 885 */ 886 static int deltaparsevtabClose(sqlite3_vtab_cursor *cur){ 887 deltaparsevtab_cursor *pCur = (deltaparsevtab_cursor*)cur; 888 sqlite3_free(pCur->aDelta); 889 sqlite3_free(pCur); 890 return SQLITE_OK; 891 } 892 893 /* 894 ** Compute the difference (in bytes) between two pointers. 895 */ 896 #define PTR_DIFF(A,B) ((i64)(intptr_t)(A) - (i64)(intptr_t)(B)) 897 898 899 /* 900 ** Advance a deltaparsevtab_cursor to its next row of output. 901 */ 902 static int deltaparsevtabNext(sqlite3_vtab_cursor *cur){ 903 deltaparsevtab_cursor *pCur = (deltaparsevtab_cursor*)cur; 904 const char *z; 905 int i = 0; 906 907 pCur->iCursor = pCur->iNext; 908 if( pCur->iCursor >= pCur->nDelta ){ 909 pCur->eOp = DELTAPARSE_OP_ERROR; 910 pCur->iNext = pCur->nDelta; 911 return SQLITE_OK; 912 } 913 z = pCur->aDelta + pCur->iCursor; 914 i = pCur->nDelta - pCur->iCursor; 915 pCur->a1 = deltaGetInt(&z, &i); 916 switch( i>0 ? z[0] : 0 ){ 917 case '@': { 918 z++; 919 i--; 920 if( pCur->iNext>=pCur->nDelta ){ 921 pCur->eOp = DELTAPARSE_OP_ERROR; 922 pCur->iNext = pCur->nDelta; 923 break; 924 } 925 pCur->a2 = deltaGetInt(&z, &i); 926 pCur->eOp = DELTAPARSE_OP_COPY; 927 pCur->iNext = PTR_DIFF(&z[1],pCur->aDelta); 928 break; 929 } 930 case ':': { 931 z++; 932 pCur->a2 = (unsigned int)(z - pCur->aDelta); 933 pCur->eOp = DELTAPARSE_OP_INSERT; 934 pCur->iNext = PTR_DIFF(&z[pCur->a1],pCur->aDelta); 935 break; 936 } 937 case ';': { 938 pCur->eOp = DELTAPARSE_OP_CHECKSUM; 939 pCur->iNext = pCur->nDelta; 940 break; 941 } 942 default: { 943 if( pCur->iNext==pCur->nDelta ){ 944 pCur->eOp = DELTAPARSE_OP_EOF; 945 }else{ 946 pCur->eOp = DELTAPARSE_OP_ERROR; 947 pCur->iNext = pCur->nDelta; 948 } 949 break; 950 } 951 } 952 return SQLITE_OK; 953 } 954 955 /* 956 ** Return values of columns for the row at which the deltaparsevtab_cursor 957 ** is currently pointing. 958 */ 959 static int deltaparsevtabColumn( 960 sqlite3_vtab_cursor *cur, /* The cursor */ 961 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ 962 int i /* Which column to return */ 963 ){ 964 deltaparsevtab_cursor *pCur = (deltaparsevtab_cursor*)cur; 965 switch( i ){ 966 case DELTAPARSEVTAB_OP: { 967 sqlite3_result_text(ctx, azOp[pCur->eOp], -1, SQLITE_STATIC); 968 break; 969 } 970 case DELTAPARSEVTAB_A1: { 971 sqlite3_result_int64(ctx, pCur->a1); 972 break; 973 } 974 case DELTAPARSEVTAB_A2: { 975 if( pCur->eOp==DELTAPARSE_OP_COPY ){ 976 sqlite3_result_int64(ctx, pCur->a2); 977 }else if( pCur->eOp==DELTAPARSE_OP_INSERT ){ 978 if( (i64)pCur->a2 + (i64)pCur->a1 > pCur->nDelta ){ 979 sqlite3_result_zeroblob(ctx, pCur->a1); 980 }else{ 981 sqlite3_result_blob(ctx, pCur->aDelta+pCur->a2, pCur->a1, 982 SQLITE_TRANSIENT); 983 } 984 } 985 break; 986 } 987 case DELTAPARSEVTAB_DELTA: { 988 sqlite3_result_blob(ctx, pCur->aDelta, pCur->nDelta, SQLITE_TRANSIENT); 989 break; 990 } 991 } 992 return SQLITE_OK; 993 } 994 995 /* 996 ** Return the rowid for the current row. In this implementation, the 997 ** rowid is the same as the output value. 998 */ 999 static int deltaparsevtabRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ 1000 deltaparsevtab_cursor *pCur = (deltaparsevtab_cursor*)cur; 1001 *pRowid = pCur->iCursor; 1002 return SQLITE_OK; 1003 } 1004 1005 /* 1006 ** Return TRUE if the cursor has been moved off of the last 1007 ** row of output. 1008 */ 1009 static int deltaparsevtabEof(sqlite3_vtab_cursor *cur){ 1010 deltaparsevtab_cursor *pCur = (deltaparsevtab_cursor*)cur; 1011 return pCur->eOp==DELTAPARSE_OP_EOF || pCur->iCursor>=pCur->nDelta; 1012 } 1013 1014 /* 1015 ** This method is called to "rewind" the deltaparsevtab_cursor object back 1016 ** to the first row of output. This method is always called at least 1017 ** once prior to any call to deltaparsevtabColumn() or deltaparsevtabRowid() or 1018 ** deltaparsevtabEof(). 1019 */ 1020 static int deltaparsevtabFilter( 1021 sqlite3_vtab_cursor *pVtabCursor, 1022 int idxNum, const char *idxStr, 1023 int argc, sqlite3_value **argv 1024 ){ 1025 deltaparsevtab_cursor *pCur = (deltaparsevtab_cursor *)pVtabCursor; 1026 const char *a; 1027 int i = 0; 1028 pCur->eOp = DELTAPARSE_OP_ERROR; 1029 if( idxNum!=1 ){ 1030 return SQLITE_OK; 1031 } 1032 pCur->nDelta = sqlite3_value_bytes(argv[0]); 1033 a = (const char*)sqlite3_value_blob(argv[0]); 1034 if( pCur->nDelta==0 || a==0 ){ 1035 return SQLITE_OK; 1036 } 1037 sqlite3_free(pCur->aDelta); 1038 pCur->aDelta = sqlite3_malloc64(pCur->nDelta+1); 1039 if( pCur->aDelta==0 ){ 1040 pCur->nDelta = 0; 1041 return SQLITE_NOMEM; 1042 } 1043 memcpy(pCur->aDelta, a, pCur->nDelta); 1044 pCur->aDelta[pCur->nDelta] = 0; 1045 a = pCur->aDelta; 1046 i = pCur->nDelta; 1047 pCur->eOp = DELTAPARSE_OP_SIZE; 1048 pCur->a1 = deltaGetInt(&a, &i); 1049 if( i<=0 || a[0]!='\n' ){ 1050 pCur->eOp = DELTAPARSE_OP_ERROR; 1051 pCur->a1 = pCur->a2 = 0; 1052 pCur->iNext = pCur->nDelta; 1053 return SQLITE_OK; 1054 } 1055 a++; 1056 pCur->iNext = PTR_DIFF(a,pCur->aDelta); 1057 return SQLITE_OK; 1058 } 1059 1060 /* 1061 ** SQLite will invoke this method one or more times while planning a query 1062 ** that uses the virtual table. This routine needs to create 1063 ** a query plan for each invocation and compute an estimated cost for that 1064 ** plan. 1065 */ 1066 static int deltaparsevtabBestIndex( 1067 sqlite3_vtab *tab, 1068 sqlite3_index_info *pIdxInfo 1069 ){ 1070 int i; 1071 for(i=0; inConstraint; i++){ 1072 if( pIdxInfo->aConstraint[i].iColumn != DELTAPARSEVTAB_DELTA ) continue; 1073 if( pIdxInfo->aConstraint[i].usable==0 ) continue; 1074 if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; 1075 pIdxInfo->aConstraintUsage[i].argvIndex = 1; 1076 pIdxInfo->aConstraintUsage[i].omit = 1; 1077 pIdxInfo->estimatedCost = (double)1; 1078 pIdxInfo->estimatedRows = 10; 1079 pIdxInfo->idxNum = 1; 1080 return SQLITE_OK; 1081 } 1082 pIdxInfo->idxNum = 0; 1083 pIdxInfo->estimatedCost = (double)0x7fffffff; 1084 pIdxInfo->estimatedRows = 0x7fffffff; 1085 return SQLITE_CONSTRAINT; 1086 } 1087 1088 /* 1089 ** This following structure defines all the methods for the 1090 ** virtual table. 1091 */ 1092 static sqlite3_module deltaparsevtabModule = { 1093 /* iVersion */ 0, 1094 /* xCreate */ 0, 1095 /* xConnect */ deltaparsevtabConnect, 1096 /* xBestIndex */ deltaparsevtabBestIndex, 1097 /* xDisconnect */ deltaparsevtabDisconnect, 1098 /* xDestroy */ 0, 1099 /* xOpen */ deltaparsevtabOpen, 1100 /* xClose */ deltaparsevtabClose, 1101 /* xFilter */ deltaparsevtabFilter, 1102 /* xNext */ deltaparsevtabNext, 1103 /* xEof */ deltaparsevtabEof, 1104 /* xColumn */ deltaparsevtabColumn, 1105 /* xRowid */ deltaparsevtabRowid, 1106 /* xUpdate */ 0, 1107 /* xBegin */ 0, 1108 /* xSync */ 0, 1109 /* xCommit */ 0, 1110 /* xRollback */ 0, 1111 /* xFindMethod */ 0, 1112 /* xRename */ 0, 1113 /* xSavepoint */ 0, 1114 /* xRelease */ 0, 1115 /* xRollbackTo */ 0, 1116 /* xShadowName */ 0, 1117 /* xIntegrity */ 0 1118 }; 1119 1120 1121 1122 #ifdef _WIN32 1123 __declspec(dllexport) 1124 #endif 1125 int sqlite3_fossildelta_init( 1126 sqlite3 *db, 1127 char **pzErrMsg, 1128 const sqlite3_api_routines *pApi 1129 ){ 1130 static const int enc = SQLITE_UTF8|SQLITE_INNOCUOUS; 1131 int rc = SQLITE_OK; 1132 SQLITE_EXTENSION_INIT2(pApi); 1133 (void)pzErrMsg; /* Unused parameter */ 1134 rc = sqlite3_create_function(db, "delta_create", 2, enc, 0, 1135 deltaCreateFunc, 0, 0); 1136 if( rc==SQLITE_OK ){ 1137 rc = sqlite3_create_function(db, "delta_apply", 2, enc, 0, 1138 deltaApplyFunc, 0, 0); 1139 } 1140 if( rc==SQLITE_OK ){ 1141 rc = sqlite3_create_function(db, "delta_output_size", 1, enc, 0, 1142 deltaOutputSizeFunc, 0, 0); 1143 } 1144 if( rc==SQLITE_OK ){ 1145 rc = sqlite3_create_module(db, "delta_parse", &deltaparsevtabModule, 0); 1146 } 1147 return rc; 1148 }