hook.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package main
  2. import (
  3. "database/sql"
  4. "log"
  5. "os"
  6. "github.com/mattn/go-sqlite3"
  7. )
  8. func main() {
  9. sqlite3conn := []*sqlite3.SQLiteConn{}
  10. sql.Register("sqlite3_with_hook_example",
  11. &sqlite3.SQLiteDriver{
  12. ConnectHook: func(conn *sqlite3.SQLiteConn) error {
  13. sqlite3conn = append(sqlite3conn, conn)
  14. conn.RegisterUpdateHook(func(op int, db string, table string, rowid int64) {
  15. switch op {
  16. case sqlite3.SQLITE_INSERT:
  17. log.Println("Notified of insert on db", db, "table", table, "rowid", rowid)
  18. }
  19. })
  20. return nil
  21. },
  22. })
  23. os.Remove("./foo.db")
  24. os.Remove("./bar.db")
  25. srcDb, err := sql.Open("sqlite3_with_hook_example", "./foo.db")
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. defer srcDb.Close()
  30. srcDb.Ping()
  31. _, err = srcDb.Exec("create table foo(id int, value text)")
  32. if err != nil {
  33. log.Fatal(err)
  34. }
  35. _, err = srcDb.Exec("insert into foo values(1, 'foo')")
  36. if err != nil {
  37. log.Fatal(err)
  38. }
  39. _, err = srcDb.Exec("insert into foo values(2, 'bar')")
  40. if err != nil {
  41. log.Fatal(err)
  42. }
  43. _, err = srcDb.Query("select * from foo")
  44. if err != nil {
  45. log.Fatal(err)
  46. }
  47. destDb, err := sql.Open("sqlite3_with_hook_example", "./bar.db")
  48. if err != nil {
  49. log.Fatal(err)
  50. }
  51. defer destDb.Close()
  52. destDb.Ping()
  53. bk, err := sqlite3conn[1].Backup("main", sqlite3conn[0], "main")
  54. if err != nil {
  55. log.Fatal(err)
  56. }
  57. _, err = bk.Step(-1)
  58. if err != nil {
  59. log.Fatal(err)
  60. }
  61. _, err = destDb.Query("select * from foo")
  62. if err != nil {
  63. log.Fatal(err)
  64. }
  65. _, err = destDb.Exec("insert into foo values(3, 'bar')")
  66. if err != nil {
  67. log.Fatal(err)
  68. }
  69. bk.Finish()
  70. }