C   48

sqlite3 db

Guest on 10th May 2022 05:49:09 PM

  1. #include <stdio.h>
  2. #include <sqlite3.h>
  3. #include <stdlib.h>
  4.  
  5. /* Instructions: grab a read lock, then try two inserts without resetting.
  6.  * $ rm a.db
  7.  * $ sqlite3 a.db < write-misuse-demo.sql
  8.  * $ sqlite3 a.db
  9.  * sqlite> BEGIN; SELECT * FROM c;
  10.  * a|b
  11.  * c|d
  12.  * sqlite> [stay at prompt]
  13.  *
  14.  * Now, in another shell:
  15.  * ./write-misuse-demo.sql a.db
  16.  * Insert 1 SQL error 5: database is locked
  17.  * Insert 2 succeeded, 1 rows changed          [?!]
  18.  *
  19.  * However, Insert 2 did not actually insert a row.
  20.  *
  21.  * Tested with SQLite 3.6.11 [prepare_v2] and 3.1.3 [prepare]
  22.  */
  23.  
  24. int main(int argc, char **argv){
  25.   sqlite3 *db;
  26.   sqlite3_stmt *s1 = NULL, *s2 = NULL;
  27.   char *zErrMsg = 0;
  28.   int rc;
  29.  
  30.   if (argc != 2){
  31.     fprintf(stderr, "usage: %s db\n", argv[0]);
  32.     exit(1);
  33.   }
  34.   rc = sqlite3_open(argv[1], &db);
  35.   if( rc ){
  36.     fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
  37.     sqlite3_close(db);
  38.     exit(1);
  39.   }
  40.  
  41.   rc = sqlite3_prepare_v2(db, "INSERT into c(k,v) VALUES('d', 'e');",
  42.                           -1, &s1, NULL);
  43.   if( rc!=SQLITE_OK ){
  44.       fprintf(stderr, "SQL error %d: %s\n", rc, sqlite3_errmsg(db));
  45.       goto end;
  46.   }
  47.  
  48.   rc = sqlite3_prepare_v2(db, "INSERT into c(k,v) VALUES('f', 'g');",
  49.                           -1, &s2, NULL);
  50.   if( rc!=SQLITE_OK ){
  51.       fprintf(stderr, "SQL error %d: %s\n", rc, sqlite3_errmsg(db));
  52.       goto end;
  53.   }
  54.  
  55.   rc = sqlite3_step(s1);
  56.   if( rc!=SQLITE_DONE ){
  57.       fprintf(stderr, "Insert 1 SQL error %d: %s\n", rc, sqlite3_errmsg(db));
  58.       /* sqlite3_reset(s1); */  /* reset required on BUSY, or Insert 2 "succeeds" */
  59.   } else {
  60.       fprintf(stderr, "Insert 1 succeeded, %d rows changed\n", sqlite3_changes(db));      
  61.   }
  62.  
  63.   rc = sqlite3_step(s2);  
  64.   if( rc!=SQLITE_DONE ){
  65.       fprintf(stderr, "Insert 2 SQL error %d: %s\n", rc, sqlite3_errmsg(db));
  66.   } else {
  67.       fprintf(stderr, "Insert 2 succeeded, %d rows changed\n", sqlite3_changes(db));
  68.   }
  69.  
  70.  
  71. end:
  72.   if (s1) sqlite3_finalize(s1);
  73.   if (s2) sqlite3_finalize(s2);
  74.   sqlite3_close(db);
  75.   return 0;
  76. }

Raw Paste


Login or Register to edit or fork this paste. It's free.