|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "database/sql" |
| 5 | + "flag" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/mattn/go-sqlite3" |
| 9 | +) |
| 10 | + |
| 11 | +// A busy handler can be as simple as a hardcoded sleep |
| 12 | +// We use the count along with the sleep duration to decide |
| 13 | +// roughly when we've hit the timeout |
| 14 | +func simpleBusyCallback(count int) int { |
| 15 | + const timeout = 5 * time.Second |
| 16 | + const delay = 1 * time.Millisecond |
| 17 | + |
| 18 | + if delay*time.Duration(count) >= timeout { |
| 19 | + // Trigger a SQLITE_BUSY error |
| 20 | + return 0 |
| 21 | + } |
| 22 | + |
| 23 | + time.Sleep(delay) |
| 24 | + |
| 25 | + // Attempt to access the database again |
| 26 | + return 1 |
| 27 | +} |
| 28 | + |
| 29 | +// This is a copy of the sqliteDefaultBusyCallback implementation |
| 30 | +// from the SQLite3 source code with minor changes |
| 31 | +// |
| 32 | +// This is equivalent to the function that's used when the |
| 33 | +// busy_timeout pragma is set |
| 34 | +func defaultBusyCallback(count int) int { |
| 35 | + // All durations are in milliseconds |
| 36 | + const timeout = 5000 |
| 37 | + delays := [...]int{1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100} |
| 38 | + totals := [...]int{0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228} |
| 39 | + |
| 40 | + var delay, prior int |
| 41 | + if count < len(delays) { |
| 42 | + delay = delays[count] |
| 43 | + prior = totals[count] |
| 44 | + } else { |
| 45 | + delay = delays[len(delays)-1] |
| 46 | + prior = totals[len(totals)-1] + delay*(count-len(totals)) |
| 47 | + } |
| 48 | + |
| 49 | + if prior+delay > timeout { |
| 50 | + delay = timeout - prior |
| 51 | + |
| 52 | + if delay <= 0 { |
| 53 | + // Trigger a SQLITE_BUSY error |
| 54 | + return 0 |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + time.Sleep(time.Duration(delay) * time.Millisecond) |
| 59 | + |
| 60 | + // Attempt to access the database again |
| 61 | + return 1 |
| 62 | +} |
| 63 | + |
| 64 | +func main() { |
| 65 | + var simple bool |
| 66 | + flag.BoolVar(&simple, "simple", false, "Use the simple busy handler") |
| 67 | + flag.Parse() |
| 68 | + |
| 69 | + sql.Register("sqlite3_with_busy_handler_example", &sqlite3.SQLiteDriver{ |
| 70 | + ConnectHook: func(conn *sqlite3.SQLiteConn) error { |
| 71 | + if simple { |
| 72 | + conn.RegisterBusyHandler(simpleBusyCallback) |
| 73 | + } else { |
| 74 | + conn.RegisterBusyHandler(defaultBusyCallback) |
| 75 | + } |
| 76 | + |
| 77 | + return nil |
| 78 | + }, |
| 79 | + }) |
| 80 | +} |
0 commit comments