/ Check-in [44f157e0]
Login
SQLite training in Houston TX on 2019-11-05 (details)
Part of the 2019 Tcl Conference

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Fix the dbhash utility so that it ignores the root page number when hashing the sqlite_master table. Add new command-line options. Add the ability to hash multiple databases with a single command.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | dbhash
Files: files | file ages | folders
SHA1: 44f157e0f0d5a76ef9002b2592164c4fdae89e34
User & Date: drh 2016-06-08 13:49:28
Context
2016-06-08
13:59
Fix an undersized buffer in the SHA1 implementation. Closed-Leaf check-in: fb276815 user: drh tags: dbhash
13:49
Fix the dbhash utility so that it ignores the root page number when hashing the sqlite_master table. Add new command-line options. Add the ability to hash multiple databases with a single command. check-in: 44f157e0 user: drh tags: dbhash
01:03
An initial attempt at a "dbhash" command-line utility. check-in: 2247649c user: drh tags: dbhash
Changes
Hide Diffs Unified Diffs Show Whitespace Changes Patch

Changes to tool/dbhash.c.

6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
..
36
37
38
39
40
41
42
43
44
45
46
47
48





49
50
51
52
53
54
55
...
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
...
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
...
282
283
284
285
286
287
288
289

290
291

292
293
294
295






296


297
298
299
300
301

302
303
304
305
306
307
308
...
309
310
311
312
313
314
315



316
317
318
319
320
321
322
...
323
324
325
326
327
328
329



330
331
332
333
334
335
336



337
338
339
340
341
342
343



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359






360
361
362
363
364
365
366
367
368




369
370
371
372
373
374
375
...
378
379
380
381
382
383
384
385








386
387
388
389
390
391
392
393
394


395
396
397
398

399











400
401
402

403
404
405
406



407
408
409





410
411
412
413

414

415
416
417






418
419
420

421













422

423
424
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This is a utility program that computes a hash on the content
** of an SQLite database.
**
** The hash is computed over just the content of the database.  Free
** space inside of the database file, and alternative on-disk representations
** of the same content (ex: UTF8 vs UTF16) do not affect the hash.  So,
** for example, the database file page size, encoding, and auto_vacuum setting
** can all be changed without changing the hash.
................................................................................
};

/*
** All global variables are gathered into the "g" singleton.
*/
struct GlobalVars {
  const char *zArgv0;       /* Name of program */
  int bSchemaPK;            /* Use the schema-defined PK, not the true PK */
  unsigned fDebug;          /* Debug flags */
  sqlite3 *db;              /* The database connection */
  SHA1Context cx;           /* SHA1 hash context */
} g;






/******************************************************************************
** The Hash Engine
**
** Modify these routines (and appropriate state fields in global variable 'g')
** in order to compute a different (better?) hash of the database.
*/
/*
................................................................................
    i = 0;
  }
  (void)memcpy(&g.cx.buffer[j], &data[i], len - i);
}


/* Add padding and compute and output the message digest. */
static void hash_finish(void){
  unsigned int i;
  unsigned char finalcount[8];
  unsigned char digest[20];
  static const char zEncode[] = "0123456789abcdef";
  char zOut[40];

  for (i = 0; i < 8; i++){
................................................................................
    digest[i] = (unsigned char)((g.cx.state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
  }
  for(i=0; i<20; i++){
    zOut[i*2] = zEncode[(digest[i]>>4)&0xf];
    zOut[i*2+1] = zEncode[digest[i] & 0xf];
  }
  zOut[i*2]= 0;
  printf("%s\n", zOut);
}
/* End of the hashing logic
*******************************************************************************/
  
/*
** Print an error resulting from faulting command-line arguments and
** abort the program.
................................................................................
  va_start(ap, zFormat);
  pStmt = db_vprepare(zFormat, ap);
  va_end(ap);
  return pStmt;
}

/*
** Compute the hash for a single table named zTab

*/
static void hash_one_table(const char *zTab){

  sqlite3_stmt *pStmt;
  int nCol;
  int i;
  pStmt = db_prepare("SELECT * FROM \"%w\";", zTab);






  nCol = sqlite3_column_count(pStmt);


  while( SQLITE_ROW==sqlite3_step(pStmt) ){
    for(i=0; i<nCol; i++){
      switch( sqlite3_column_type(pStmt,i) ){
        case SQLITE_NULL: {
          hash_step((const unsigned char*)"0",1);

          break;
        }
        case SQLITE_INTEGER: {
          sqlite3_uint64 u;
          int j;
          unsigned char x[8];
          sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
................................................................................
          memcpy(&u, &v, 8);
          for(j=7; j>=0; j--){
            x[j] = u & 0xff;
            u >>= 8;
          }
          hash_step((const unsigned char*)"1",1);
          hash_step(x,8);



          break;
        }
        case SQLITE_FLOAT: {
          sqlite3_uint64 u;
          int j;
          unsigned char x[8];
          double r = sqlite3_column_double(pStmt,i);
................................................................................
          memcpy(&u, &r, 8);
          for(j=7; j>=0; j--){
            x[j] = u & 0xff;
            u >>= 8;
          }
          hash_step((const unsigned char*)"2",1);
          hash_step(x,8);



          break;
        }
        case SQLITE_TEXT: {
          int n = sqlite3_column_bytes(pStmt, i);
          const unsigned char *z = sqlite3_column_text(pStmt, i);
          hash_step((const unsigned char*)"3", 1);
          hash_step(z, n);



          break;
        }
        case SQLITE_BLOB: {
          int n = sqlite3_column_bytes(pStmt, i);
          const unsigned char *z = sqlite3_column_blob(pStmt, i);
          hash_step((const unsigned char*)"4", 1);
          hash_step(z, n);



          break;
        }
      }
    }
  }
  sqlite3_finalize(pStmt);
}


/*
** Print sketchy documentation for this utility program
*/
static void showHelp(void){
  printf("Usage: %s DB\n", g.zArgv0);
  printf(
"Compute a hash on the content of database DB\n"






  );
}

int main(int argc, char **argv){
  const char *zDb = 0;
  int i;
  int rc;
  char *zErrMsg;
  sqlite3_stmt *pStmt;





  g.zArgv0 = argv[0];
  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
  for(i=1; i<argc; i++){
    const char *z = argv[i];
    if( z[0]=='-' ){
      z++;
................................................................................
        if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
        g.fDebug = strtol(argv[++i], 0, 0);
      }else
      if( strcmp(z,"help")==0 ){
        showHelp();
        return 0;
      }else
      if( strcmp(z,"primarykey")==0 ){








        g.bSchemaPK = 1;
      }else
      {
        cmdlineError("unknown option: %s", argv[i]);
      }
    }else if( zDb==0 ){
      zDb = argv[i];
    }else{
      cmdlineError("unknown argument: %s", argv[i]);


    }
  }
  if( zDb==0 ){
    cmdlineError("database argument missing");

  }











  rc = sqlite3_open(zDb, &g.db);
  if( rc ){
    cmdlineError("cannot open database file \"%s\"", zDb);

  }
  rc = sqlite3_exec(g.db, "SELECT * FROM sqlite_master", 0, 0, &zErrMsg);
  if( rc || zErrMsg ){
    cmdlineError("\"%s\" does not appear to be a valid SQLite database", zDb);



  }

  /* Handle tables one by one */





  pStmt = db_prepare(
    "SELECT name FROM sqlite_master\n"
    " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
    "UNION SELECT 'sqlite_master' AS name\n"

    " ORDER BY name;\n"

  );
  hash_init();
  while( SQLITE_ROW==sqlite3_step(pStmt) ){






    hash_one_table((const char*)sqlite3_column_text(pStmt,0));
  }
  hash_finish();















  sqlite3_close(g.db);

  return 0;
}







|







 







<





>
>
>
>
>







 







|







 







|







 







|
>

|
>
|
<
<
|
>
>
>
>
>
>

>
>





>







 







>
>
>







 







>
>
>







>
>
>







>
>
>













|

|
>
>
>
>
>
>




|
|
|
|
|
>
>
>
>







 







|
>
>
>
>
>
>
>
>
|




<
<

<
>
>


|
<
>

>
>
>
>
>
>
>
>
>
>
>
|
|
|
>



|
>
>
>
|

<
>
>
>
>
>



|
>
|
>
|
<
|
>
>
>
>
>
>
|
|
<
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
..
36
37
38
39
40
41
42

43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
...
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
...
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
...
286
287
288
289
290
291
292
293
294
295
296
297
298


299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
...
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
...
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
...
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433


434

435
436
437
438
439

440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465

466
467
468
469
470
471
472
473
474
475
476
477
478

479
480
481
482
483
484
485
486
487

488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This is a utility program that computes an SHA1 hash on the content
** of an SQLite database.
**
** The hash is computed over just the content of the database.  Free
** space inside of the database file, and alternative on-disk representations
** of the same content (ex: UTF8 vs UTF16) do not affect the hash.  So,
** for example, the database file page size, encoding, and auto_vacuum setting
** can all be changed without changing the hash.
................................................................................
};

/*
** All global variables are gathered into the "g" singleton.
*/
struct GlobalVars {
  const char *zArgv0;       /* Name of program */

  unsigned fDebug;          /* Debug flags */
  sqlite3 *db;              /* The database connection */
  SHA1Context cx;           /* SHA1 hash context */
} g;

/*
** Debugging flags
*/
#define DEBUG_FULLTRACE   0x00000001   /* Trace hash to stderr */

/******************************************************************************
** The Hash Engine
**
** Modify these routines (and appropriate state fields in global variable 'g')
** in order to compute a different (better?) hash of the database.
*/
/*
................................................................................
    i = 0;
  }
  (void)memcpy(&g.cx.buffer[j], &data[i], len - i);
}


/* Add padding and compute and output the message digest. */
static void hash_finish(const char *zName){
  unsigned int i;
  unsigned char finalcount[8];
  unsigned char digest[20];
  static const char zEncode[] = "0123456789abcdef";
  char zOut[40];

  for (i = 0; i < 8; i++){
................................................................................
    digest[i] = (unsigned char)((g.cx.state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
  }
  for(i=0; i<20; i++){
    zOut[i*2] = zEncode[(digest[i]>>4)&0xf];
    zOut[i*2+1] = zEncode[digest[i] & 0xf];
  }
  zOut[i*2]= 0;
  printf("%s %s\n", zOut, zName);
}
/* End of the hashing logic
*******************************************************************************/
  
/*
** Print an error resulting from faulting command-line arguments and
** abort the program.
................................................................................
  va_start(ap, zFormat);
  pStmt = db_vprepare(zFormat, ap);
  va_end(ap);
  return pStmt;
}

/*
** Compute the hash for all rows of the query formed from the printf-style
** zFormat and its argument.
*/
static void hash_one_query(const char *zFormat, ...){
  va_list ap;
  sqlite3_stmt *pStmt;        /* The query defined by zFormat and "..." */


  int nCol;                   /* Number of columns in the result set */
  int i;                      /* Loop counter */

  /* Prepare the query defined by zFormat and "..." */
  va_start(ap, zFormat);
  pStmt = db_vprepare(zFormat, ap);
  va_end(ap);
  nCol = sqlite3_column_count(pStmt);

  /* Compute a hash over the result of the query */
  while( SQLITE_ROW==sqlite3_step(pStmt) ){
    for(i=0; i<nCol; i++){
      switch( sqlite3_column_type(pStmt,i) ){
        case SQLITE_NULL: {
          hash_step((const unsigned char*)"0",1);
          if( g.fDebug & DEBUG_FULLTRACE ) fprintf(stderr, "NULL\n");
          break;
        }
        case SQLITE_INTEGER: {
          sqlite3_uint64 u;
          int j;
          unsigned char x[8];
          sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
................................................................................
          memcpy(&u, &v, 8);
          for(j=7; j>=0; j--){
            x[j] = u & 0xff;
            u >>= 8;
          }
          hash_step((const unsigned char*)"1",1);
          hash_step(x,8);
          if( g.fDebug & DEBUG_FULLTRACE ){
            fprintf(stderr, "INT %s\n", sqlite3_column_text(pStmt,i));
          }
          break;
        }
        case SQLITE_FLOAT: {
          sqlite3_uint64 u;
          int j;
          unsigned char x[8];
          double r = sqlite3_column_double(pStmt,i);
................................................................................
          memcpy(&u, &r, 8);
          for(j=7; j>=0; j--){
            x[j] = u & 0xff;
            u >>= 8;
          }
          hash_step((const unsigned char*)"2",1);
          hash_step(x,8);
          if( g.fDebug & DEBUG_FULLTRACE ){
            fprintf(stderr, "FLOAT %s\n", sqlite3_column_text(pStmt,i));
          }
          break;
        }
        case SQLITE_TEXT: {
          int n = sqlite3_column_bytes(pStmt, i);
          const unsigned char *z = sqlite3_column_text(pStmt, i);
          hash_step((const unsigned char*)"3", 1);
          hash_step(z, n);
          if( g.fDebug & DEBUG_FULLTRACE ){
            fprintf(stderr, "TEXT '%s'\n", sqlite3_column_text(pStmt,i));
          }
          break;
        }
        case SQLITE_BLOB: {
          int n = sqlite3_column_bytes(pStmt, i);
          const unsigned char *z = sqlite3_column_blob(pStmt, i);
          hash_step((const unsigned char*)"4", 1);
          hash_step(z, n);
          if( g.fDebug & DEBUG_FULLTRACE ){
            fprintf(stderr, "BLOB (%d bytes)\n", n);
          }
          break;
        }
      }
    }
  }
  sqlite3_finalize(pStmt);
}


/*
** Print sketchy documentation for this utility program
*/
static void showHelp(void){
  printf("Usage: %s [options] FILE ...\n", g.zArgv0);
  printf(
"Compute a SHA1 hash on the content of database FILE.  System tables such as\n"
"sqlite_stat1, sqlite_stat4, and sqlite_sequence are omitted from the hash.\n"
"Options:\n"
"   --debug N           Set debugging flags to N (experts only)\n"
"   --like PATTERN      Only hash tables whose name is LIKE the pattern\n"
"   --schema-only       Only hash the schema - omit table content\n"
"   --without-schema    Only hash table content - omit the schema\n"
  );
}

int main(int argc, char **argv){
  const char *zDb = 0;         /* Name of the database currently being hashed */
  int i;                       /* Loop counter */
  int rc;                      /* Subroutine return code */
  char *zErrMsg;               /* Error message when opening database */
  sqlite3_stmt *pStmt;         /* An SQLite query */
  const char *zLike = 0;       /* LIKE pattern of tables to hash */
  int omitSchema = 0;          /* True to compute hash on content only */
  int omitContent = 0;         /* True to compute hash on schema only */
  int nFile = 0;               /* Number of input filenames seen */

  g.zArgv0 = argv[0];
  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
  for(i=1; i<argc; i++){
    const char *z = argv[i];
    if( z[0]=='-' ){
      z++;
................................................................................
        if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
        g.fDebug = strtol(argv[++i], 0, 0);
      }else
      if( strcmp(z,"help")==0 ){
        showHelp();
        return 0;
      }else
      if( strcmp(z,"like")==0 ){
        if( i==argc-1 ) cmdlineError("missing argument to %s", argv[i]);
        if( zLike!=0 ) cmdlineError("only one --like allowed");
        zLike = argv[++i];
      }else
      if( strcmp(z,"schema-only")==0 ){
        omitContent = 1;
      }else
      if( strcmp(z,"without-schema")==0 ){
        omitSchema = 1;
      }else
      {
        cmdlineError("unknown option: %s", argv[i]);
      }


    }else{

      nFile++;
      if( nFile<i ) argv[nFile] = argv[i];
    }
  }
  if( nFile==0 ){

    cmdlineError("no input files specified - nothing to do");
  }
  if( omitSchema && omitContent ){
    cmdlineError("only one of --without-schema and --omit-schema allowed");
  }
  if( zLike==0 ) zLike = "%";

  for(i=1; i<=nFile; i++){
    static const int openFlags = 
       SQLITE_OPEN_READWRITE |     /* Read/write so hot journals can recover */
       SQLITE_OPEN_URI
    ;
    zDb = argv[i];
    rc = sqlite3_open_v2(zDb, &g.db, openFlags, 0);
    if( rc ){
      fprintf(stderr, "cannot open database file '%s'\n", zDb);
      continue;
    }
    rc = sqlite3_exec(g.db, "SELECT * FROM sqlite_master", 0, 0, &zErrMsg);
    if( rc || zErrMsg ){
      sqlite3_close(g.db);
      g.db = 0;
      fprintf(stderr, "'%s' is not a valid SQLite database\n", zDb);
      continue;
    }


    /* Start the hash */
    hash_init();
  
    /* Hash table content */
    if( !omitContent ){
      pStmt = db_prepare(
        "SELECT name FROM sqlite_master\n"
        " WHERE type='table' AND sql NOT LIKE 'CREATE VIRTUAL%%'\n"
        "   AND name NOT LIKE 'sqlite_%%'\n"
        "   AND name LIKE '%q'\n"
        " ORDER BY name COLLATE nocase;\n",
        zLike
      );

      while( SQLITE_ROW==sqlite3_step(pStmt) ){
        /* We want rows of the table to be hashed in PRIMARY KEY order.
        ** Technically, an ORDER BY clause is required to guarantee that
        ** order.  However, though not guaranteed by the documentation, every
        ** historical version of SQLite has always output rows in PRIMARY KEY
        ** order when there is no WHERE or GROUP BY clause, so the ORDER BY
        ** can be safely omitted. */
        hash_one_query("SELECT * FROM \"%w\"", sqlite3_column_text(pStmt,0));
      }

      sqlite3_finalize(pStmt);
    }
  
    /* Hash the database schema */
    if( !omitSchema ){
      hash_one_query(
         "SELECT type, name, tbl_name, sql FROM sqlite_master\n"
         " WHERE tbl_name LIKE '%q'\n"
         " ORDER BY name COLLATE nocase;\n",
         zLike
      );
    }
  
    /* Finish and output the hash and close the database connection. */
    hash_finish(zDb);
    sqlite3_close(g.db);
  }
  return 0;
}