Test_UpdateHook_Basic tests the basic functionality of the update hook, ensuring it is triggered for inserts, updates, and deletes, and not triggered for selects, executes that don't change anything, and when unregistered.
(t *testing.T)
| 13 | // it is triggered for inserts, updates, and deletes, and not triggered for selects, |
| 14 | // executes that don't change anything, and when unregistered. |
| 15 | func Test_UpdateHook_Basic(t *testing.T) { |
| 16 | path := mustTempPath() |
| 17 | defer os.Remove(path) |
| 18 | db, err := Open(path, false, false) |
| 19 | if err != nil { |
| 20 | t.Fatalf("error opening database") |
| 21 | } |
| 22 | defer db.Close() |
| 23 | mustExecute(db, "CREATE TABLE foo (id INTEGER PRIMARY KEY, name TEXT)") |
| 24 | |
| 25 | count := &atomic.Int32{} |
| 26 | hook := func(ev *command.UpdateHookEvent) error { |
| 27 | count.Add(1) |
| 28 | return nil |
| 29 | } |
| 30 | if err := db.RegisterUpdateHook(hook); err != nil { |
| 31 | t.Fatalf("error registering update hook") |
| 32 | } |
| 33 | |
| 34 | // A select should not trigger the hook and a basic insert should trigger the hook. |
| 35 | mustQuery(db, "SELECT * FROM foo") |
| 36 | mustExecute(db, "INSERT INTO foo(name) VALUES('fiona')") |
| 37 | if count.Load() != 1 { |
| 38 | t.Fatalf("expected count 1, got %d", count.Load()) |
| 39 | } |
| 40 | |
| 41 | // An update should trigger the hook, and an update that doesn't change anything |
| 42 | // should not trigger the hook. |
| 43 | mustExecute(db, "UPDATE foo SET name='fiona2' WHERE id=5") |
| 44 | mustExecute(db, "UPDATE foo SET name='fiona2' WHERE id=1") |
| 45 | if count.Load() != 2 { |
| 46 | t.Fatalf("expected count 2, got %d", count.Load()) |
| 47 | } |
| 48 | |
| 49 | // A delete should trigger the hook. |
| 50 | mustExecute(db, "DELETE FROM foo WHERE id=1") |
| 51 | if count.Load() != 3 { |
| 52 | t.Fatalf("expected count 3, got %d", count.Load()) |
| 53 | } |
| 54 | |
| 55 | // Insert 5 rows, make sure the hook is triggered 5 times. |
| 56 | for range 5 { |
| 57 | mustExecute(db, "INSERT INTO foo(name) VALUES('fiona')") |
| 58 | } |
| 59 | if count.Load() != 8 { |
| 60 | t.Fatalf("expected count 8, got %d", count.Load()) |
| 61 | } |
| 62 | |
| 63 | // Delete all rows, make sure the hook is triggered 5 times. |
| 64 | // To work around the TRUNCATE optimization, we delete all rows |
| 65 | // using a WHERE clause. |
| 66 | r := mustQuery(db, "SELECT COUNT(*) FROM foo") |
| 67 | if exp, got := int64(5), r[0].Values[0].Parameters[0].GetI(); exp != got { |
| 68 | t.Fatalf("expected count %d, got %d", exp, got) |
| 69 | } |
| 70 | mustExecute(db, "DELETE FROM foo WHERE id>0") |
| 71 | if count.Load() != 13 { |
| 72 | t.Fatalf("expected count 13, got %d", count.Load()) |
nothing calls this directly
no test coverage detected