func updateHandler(ctx *fasthttp.RequestCtx) { n := common.GetQueriesCount(ctx) worlds := make([]common.World, n) for i := 0; i < n; i++ { w := &worlds[i] fetchRandomWorld(w) w.RandomNumber = int32(common.RandomWorldNum()) } // sorting is required for insert deadlock prevention. sort.Sort(common.WorldsByID(worlds)) txn, err := db.Begin() if err != nil { log.Fatalf("Error starting transaction: %s", err) } for i := 0; i < n; i++ { w := &worlds[i] if _, err = txn.Exec("worldUpdateStmt", w.RandomNumber, w.Id); err != nil { log.Fatalf("Error updating world row %d: %s", i, err) } } if err = txn.Commit(); err != nil { log.Fatalf("Error when commiting world rows: %s", err) } common.JSONMarshal(ctx, worlds) }
func initDatabase(dbHost string, dbUser string, dbPass string, dbName string, dbPort uint16, maxConnectionsInPool int) (*pgx.ConnPool, error) { var successOrFailure string = "OK" var config pgx.ConnPoolConfig config.Host = dbHost config.User = dbUser config.Password = dbPass config.Database = dbName config.Port = dbPort config.MaxConnections = maxConnectionsInPool config.AfterConnect = func(conn *pgx.Conn) error { worldSelectStmt = mustPrepare(conn, "worldSelectStmt", "SELECT id, randomNumber FROM World WHERE id = $1") worldUpdateStmt = mustPrepare(conn, "worldUpdateStmt", "UPDATE World SET randomNumber = $1 WHERE id = $2") fortuneSelectStmt = mustPrepare(conn, "fortuneSelectStmt", "SELECT id, message FROM Fortune") return nil } fmt.Println("--------------------------------------------------------------------------------------------") connPool, err := pgx.NewConnPool(config) if err != nil { successOrFailure = "FAILED" log.Println("Connecting to database ", dbName, " as user ", dbUser, " ", successOrFailure, ": \n ", err) } else { log.Println("Connecting to database ", dbName, " as user ", dbUser, ": ", successOrFailure) log.Println("Fetching one record to test if db connection is valid...") var w common.World n := common.RandomWorldNum() if errPing := connPool.QueryRow("worldSelectStmt", n).Scan(&w.Id, &w.RandomNumber); errPing != nil { log.Fatalf("Error scanning world row: %s", errPing) } log.Println("OK") } fmt.Println("--------------------------------------------------------------------------------------------") return connPool, err }
func fetchRandomWorld(w *common.World) { n := common.RandomWorldNum() if err := db.QueryRow("worldSelectStmt", n).Scan(&w.Id, &w.RandomNumber); err != nil { log.Fatalf("Error scanning world row: %s", err) } }