Fetch player pos from postgres

This commit is contained in:
Sascha L. Teichmann 2022-02-28 13:21:28 +01:00
parent 3c4b217364
commit 8c6ab34e6a

View File

@ -7,6 +7,8 @@ package main
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context"
"database/sql"
"encoding/json" "encoding/json"
"html/template" "html/template"
"log" "log"
@ -16,6 +18,8 @@ import (
"sort" "sort"
"sync" "sync"
"time" "time"
"bitbucket.org/s_l_teichmann/mtsatellite/common"
) )
const sleepInterval = time.Second * 5 const sleepInterval = time.Second * 5
@ -78,7 +82,38 @@ func (pls sortPlayersByName) Swap(i, j int) {
pls[i], pls[j] = pls[j], pls[i] pls[i], pls[j] = pls[j], pls[i]
} }
const selectPlayersSQL = `
SELECT posx, posy, posz, name
FROM player
WHERE modification_date > now() - '2m'::interval`
func playersFromPostgreSQL(connS string) ([]*player, error) {
db, err := sql.Open("pgx", connS)
if err != nil {
return nil, err
}
defer db.Close()
rows, err := db.QueryContext(context.Background(), selectPlayersSQL)
if err != nil {
return nil, err
}
defer rows.Close()
var pls []*player
for rows.Next() {
var p player
if err := rows.Scan(&p.Y, &p.Y, &p.Z, &p.Name); err != nil {
return nil, err
}
pls = append(pls, &p)
}
return pls, rows.Err()
}
func (ps *players) readFromFIFO() ([]*player, error) { func (ps *players) readFromFIFO() ([]*player, error) {
if host, ok := common.IsPostgreSQL(ps.fifo); ok {
return playersFromPostgreSQL(host)
}
file, err := os.Open(ps.fifo) file, err := os.Open(ps.fifo)
if err != nil { if err != nil {
return nil, err return nil, err