
#include <stdio.h>
#include <assert.h>
#include <sqlite3.h>

int main(int argc, char **argv)
{
 int rc;
 sqlite3 *db;
 char *error=NULL;
 sqlite3_stmt *stmt=NULL, *stmt2=NULL;;

 rc=sqlite3_open(":memory:", &db);
 assert(rc==SQLITE_OK);

 rc=sqlite3_exec(db,
     "PRAGMA FOREIGN_KEYS = ON; "
     "CREATE TABLE main(id INTEGER PRIMARY KEY); "
     "CREATE TABLE sub(id INT NOT NULL REFERENCES main(id)); "
     "INSERT INTO main VALUES(1); "
     "INSERT INTO main VALUES(2); "
     "INSERT INTO sub VALUES(1) ",
     NULL, NULL, &error);
 assert(rc==SQLITE_OK);

 rc=sqlite3_prepare_v2(db, "DELETE FROM main WHERE id=?", -1, &stmt, NULL);
 assert(rc==SQLITE_OK);
 assert(stmt);

 /* the statement will cause a constraint error with bindings of 1 */
 rc=sqlite3_bind_int(stmt, 1, 1);
 assert(rc==SQLITE_OK);
 rc=sqlite3_step(stmt);
 assert(rc!=SQLITE_DONE);
 /* reset it */
 rc=sqlite3_reset(stmt);
 assert(rc==SQLITE_CONSTRAINT);
 /* clear bindings */
 rc=sqlite3_clear_bindings(stmt);
 assert(rc==SQLITE_OK);

 /* now execute with binding of 2 which should be okay */
 rc=sqlite3_bind_int(stmt, 1, 2);
 assert(rc==SQLITE_OK);
 rc=sqlite3_step(stmt);
 if(rc!=SQLITE_DONE){
   printf("ERROR:\nrc=%d resetrc=%d errmsg=%s\n", rc,
         sqlite3_reset(stmt), sqlite3_errmsg(db));
 }

 /* Re-execute with a freshly prepared statement */
 rc=sqlite3_prepare_v2(db, "DELETE FROM main WHERE id=?",
                       -1, &stmt2, NULL);
 assert(rc==SQLITE_OK);
 assert(stmt2);
 rc=sqlite3_bind_int(stmt2, 1, 2);
 assert(rc==SQLITE_OK);
 rc=sqlite3_step(stmt2);
 assert(rc==SQLITE_DONE);

 return 0;
}

