go-sqlite3/_example/hook/hook.go

79 lines
1.6 KiB
Go
Raw Permalink Normal View History

2014-01-30 14:45:09 +04:00
package main
import (
"database/sql"
"log"
"os"
2016-02-28 22:46:49 +03:00
"github.com/mattn/go-sqlite3"
2014-01-30 14:45:09 +04:00
)
func main() {
sqlite3conn := []*sqlite3.SQLiteConn{}
sql.Register("sqlite3_with_hook_example",
&sqlite3.SQLiteDriver{
ConnectHook: func(conn *sqlite3.SQLiteConn) error {
sqlite3conn = append(sqlite3conn, conn)
conn.RegisterUpdateHook(func(op int, db string, table string, rowid int64) {
switch op {
case sqlite3.SQLITE_INSERT:
log.Println("Notified of insert on db", db, "table", table, "rowid", rowid)
}
})
return nil
},
})
2014-01-30 14:45:09 +04:00
os.Remove("./foo.db")
os.Remove("./bar.db")
srcDb, err := sql.Open("sqlite3_with_hook_example", "./foo.db")
2014-01-30 14:45:09 +04:00
if err != nil {
log.Fatal(err)
}
defer srcDb.Close()
srcDb.Ping()
2014-01-30 14:45:09 +04:00
_, err = srcDb.Exec("create table foo(id int, value text)")
2014-01-30 14:45:09 +04:00
if err != nil {
log.Fatal(err)
}
_, err = srcDb.Exec("insert into foo values(1, 'foo')")
2014-01-30 14:45:09 +04:00
if err != nil {
log.Fatal(err)
}
_, err = srcDb.Exec("insert into foo values(2, 'bar')")
2014-01-30 14:45:09 +04:00
if err != nil {
log.Fatal(err)
}
_, err = srcDb.Query("select * from foo")
2014-01-30 14:45:09 +04:00
if err != nil {
log.Fatal(err)
}
destDb, err := sql.Open("sqlite3_with_hook_example", "./bar.db")
2014-01-30 14:45:09 +04:00
if err != nil {
log.Fatal(err)
}
defer destDb.Close()
destDb.Ping()
2014-01-30 14:45:09 +04:00
bk, err := sqlite3conn[1].Backup("main", sqlite3conn[0], "main")
if err != nil {
log.Fatal(err)
}
_, err = bk.Step(-1)
2014-01-30 14:45:09 +04:00
if err != nil {
log.Fatal(err)
}
_, err = destDb.Query("select * from foo")
if err != nil {
log.Fatal(err)
}
_, err = destDb.Exec("insert into foo values(3, 'bar')")
if err != nil {
log.Fatal(err)
}
bk.Finish()
}