Advertisement
krolaw

Go SQL Bug?

Feb 1st, 2012
439
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.26 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     _ "github.com/mattn/go-sqlite3"
  5.     "net/http"
  6.     "strconv"
  7.     "database/sql"
  8.     "os/signal"
  9.     "time"
  10. )
  11.  
  12. var getPageCountSQL, setPageCountSQL *sql.Stmt
  13.  
  14. func main() {
  15.     db,err := sql.Open("sqlite3","test.db")
  16.     if err != nil {
  17.         panic(err.Error())
  18.     }
  19.     defer db.Close()
  20.    
  21.     db.Exec("CREATE TABLE test (pageCount INT)") // Hopefully, only fails if table already exists.
  22.    
  23.     // Pre-prepare SQL statements for max speed
  24.     if getPageCountSQL,err = db.Prepare("SELECT pageCount FROM test ORDER BY pageCount DESC") ; err != nil {
  25.         panic(err.Error())
  26.     }
  27.     if setPageCountSQL,err = db.Prepare("INSERT INTO test (pageCount) VALUES (?)") ; err != nil {
  28.         panic(err.Error())
  29.     }
  30.  
  31.     http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  32.         count := 0
  33.         if err := getPageCountSQL.QueryRow().Scan(&count) ; err != nil && err != sql.ErrNoRows {
  34.             panic(err.Error())
  35.         }
  36.         // Simulate processing
  37.         time.Sleep(1e9)
  38.        
  39.         count++
  40.         w.Write([]byte("<html><form method=\"post\"><input type=\"submit\" value=\"Again\"/></form>Page view count: "+strconv.Itoa(count)+"</html>"))
  41.         if _,err := setPageCountSQL.Exec(count) ; err != nil {
  42.             panic(err.Error())
  43.         }
  44.     })
  45.  
  46.     go http.ListenAndServe(":7777", nil)
  47.     <-signal.Incoming // Exit on kill signal
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement